// @Author gmy 2024/9/19 16:45:00
package document_manage_service

import (
	"eta/eta_api/models"
	"eta/eta_api/models/document_manage_model"
	"eta/eta_api/utils"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"github.com/rdlucklib/rdluck_tools/paging"
)

func DocumentClassifyList() ([]models.ClassifyVO, error) {
	logs.Info("DocumentClassifyList")

	//获取所有已启用分类
	classifyList, err := models.GetClassifyListByKeyword(``, utils.IS_ENABLE)
	if err != nil {
		return nil, err
	}

	// 递归处理分类 拿到父级分类和对应的子级分类
	classifyVOList := make([]models.ClassifyVO, 0)
	for _, classify := range classifyList {
		if classify.ParentId == 0 {
			classifyVO := models.ClassifyVO{
				Id:           classify.Id,
				ClassifyName: classify.ClassifyName,
				ParentId:     classify.ParentId,
				Sort:         classify.Sort,
				Enabled:      classify.Enabled,
				Level:        classify.Level,
			}
			classifyVO.Children = getChildClassify(classifyList, classify.Id)
			classifyVOList = append(classifyVOList, classifyVO)
		}
	}

	return classifyVOList, nil
}

func getChildClassify(classifyList []*models.ClassifyList, classifyId int) *[]models.ClassifyVO {
	childList := make([]models.ClassifyVO, 0)
	for _, classify := range classifyList {
		if classify.ParentId == classifyId {
			classifyVO := models.ClassifyVO{
				Id:           classify.Id,
				ClassifyName: classify.ClassifyName,
				ParentId:     classify.ParentId,
				Sort:         classify.Sort,
				Enabled:      classify.Enabled,
			}
			classifyVO.Children = getChildClassify(classifyList, classify.Id)
			childList = append(childList, classifyVO)
		}
	}
	return &childList
}

func DocumentVarietyList() ([]models.ChartPermissionVO, error) {
	logs.Info("DocumentVarietyList")

	cp := new(models.ChartPermission)
	var condition string
	pars := make([]interface{}, 0)

	condition = ` and enabled=?`
	pars = append(pars, 1)

	chartPermissionList, err := cp.GetItemsByCondition(condition, pars)
	if err != nil {
		return nil, err
	}

	// 递归处理品种 拿到父级品种和对应的子级品种
	permissionVOList := make([]models.ChartPermissionVO, 0)
	for _, chartPermission := range chartPermissionList {
		if chartPermission.ParentId == 0 {
			permissionVO := models.ChartPermissionVO{
				ChartPermissionId:   chartPermission.ChartPermissionId,
				ChartPermissionName: chartPermission.ChartPermissionName,
				ParentId:            chartPermission.ParentId,
				Enabled:             chartPermission.Enabled,
				Sort:                chartPermission.Sort,
				CreatedTime:         chartPermission.CreatedTime,
			}
			permissionVO.Children = getChildVariety(chartPermissionList, permissionVO.ChartPermissionId)
			permissionVOList = append(permissionVOList, permissionVO)
		}
	}

	return permissionVOList, nil
}

func getChildVariety(permissionList []*models.ChartPermission, permissionId int) []*models.ChartPermissionVO {
	childList := make([]*models.ChartPermissionVO, 0)
	for _, permission := range permissionList {
		if permission.ParentId == permissionId {
			permissionVO := models.ChartPermissionVO{
				ChartPermissionId:   permission.ChartPermissionId,
				ChartPermissionName: permission.ChartPermissionName,
				ParentId:            permission.ParentId,
				Enabled:             permission.Enabled,
				Sort:                permission.Sort,
				CreatedTime:         permission.CreatedTime,
			}
			permissionVO.Children = getChildVariety(permissionList, permissionVO.ChartPermissionId)
			childList = append(childList, &permissionVO)
		}
	}
	return childList

}

func DocumentReportList(documentType int, chartPermissionIdList []string, classifyIdList []string, keyword string, orderField, orderType string, startSize, pageSize int) (*document_manage_model.OutsideReportPage, error) {
	logs.Info("DocumentVarietyList")

	var condition string
	pars := make([]interface{}, 0)

	if documentType == 1 {
		condition = ` and t1.source!=3`
	}
	if len(classifyIdList) > 0 {
		condition += ` and t1.classify_id in (` + utils.GetOrmInReplace(len(classifyIdList)) + `)`
		for _, classifyId := range classifyIdList {
			pars = append(pars, classifyId)
		}
	}
	if len(chartPermissionIdList) > 0 {
		condition += ` and t2.chart_permission_id in (` + utils.GetOrmInReplace(len(chartPermissionIdList)) + `)`
		for _, chartPermissionId := range chartPermissionIdList {
			pars = append(pars, chartPermissionId)
		}
	}
	if keyword != "" {
		condition += ` and t1.title like ? or t1.sys_user_name like ?`
		pars = append(pars, "%"+keyword+"%", "%"+keyword+"%")
	}

	count, err := document_manage_model.GetOutsideReportListByConditionCount(condition, pars)
	if err != nil {
		return nil, err
	}
	reportPage := document_manage_model.OutsideReportPage{}

	page := paging.GetPaging(startSize, pageSize, count)
	if count <= 0 {
		reportPage.Paging = page
		return &reportPage, nil
	}

	if orderField != "" && orderType != "" {
		condition += ` order by t1.` + orderField + ` ` + orderType
	} else {
		condition += ` order by t1.modify_time desc`
	}

	outsideReportList, err := document_manage_model.GetOutsideReportListByCondition(condition, pars, startSize, pageSize)
	if err != nil {
		return nil, err
	}
	reportPage.Paging = page
	reportPage.List = outsideReportList

	return &reportPage, nil
}

func RuiSiReportList(classifyIdFirst, classifyIdSecond, classifyIdThird int, keyword string, orderField, orderType string, startSize, pageSize int) (*models.ReportListResp, error) {
	logs.Info("RuiSiReportList")

	var condition string
	pars := make([]interface{}, 0)

	if classifyIdFirst > 0 {
		condition += ` AND a.classify_id_first = ? `
		pars = append(pars, classifyIdFirst)
	}
	if classifyIdSecond > 0 {
		condition += ` AND a.classify_id_second = ? `
		pars = append(pars, classifyIdSecond)
	}
	if classifyIdThird > 0 {
		condition += ` AND a.classify_id_third = ? `
		pars = append(pars, classifyIdThird)
	}
	if keyword != "" {
		condition += ` and a.title like ? or a.admin_real_name like ?`
		pars = append(pars, "%"+keyword+"%", "%"+keyword+"%")
	}

	// 作者为 全球市场战略研究中心 PCI Research
	condition += ` and a.author = '全球市场战略研究中心 PCI Research'`
	// 已发布的报告
	condition += ` and a.state = 2`

	count, err := models.GetReportListCountV1(condition, pars)
	if err != nil {
		return nil, err
	}
	reportPage := models.ReportListResp{}

	page := paging.GetPaging(startSize, pageSize, count)
	if count <= 0 {
		reportPage.Paging = page
		return &reportPage, nil
	}

	if orderField != "" && orderType != "" {
		condition += ` order by a.` + orderField + ` ` + orderType
	} else {
		condition += ` order by a.publish_time desc`
	}

	reportList, err := models.GetReportListByCondition(condition, pars, startSize, pageSize)
	if err != nil {
		return nil, err
	}

	reportPage.Paging = page
	reportPage.List = reportList

	return &reportPage, nil
}

func DocumentRuiSiDetail(reportId int) (*models.ReportDetail, error) {
	logs.Info("DocumentRuiSiDetail")

	reportDetail, err := models.GetReportById(reportId)
	if err != nil {
		return nil, err
	}

	return reportDetail, nil
}

func DocumentSave(outsideReport *document_manage_model.OutsideReportBO) error {
	logs.Info("DocumentSave")

	// 保存报告
	report := document_manage_model.OutsideReport{
		Source:           outsideReport.Source,
		Title:            outsideReport.Title,
		Abstract:         outsideReport.Abstract,
		ClassifyId:       outsideReport.ClassifyId,
		ClassifyName:     outsideReport.ClassifyName,
		Content:          outsideReport.Content,
		SysUserId:        outsideReport.SysUserId,
		SysUserName:      outsideReport.SysUserName,
		ReportUpdateTime: utils.GetCurrentTime(),
		ModifyTime:       utils.GetCurrentTime(),
		CreateTime:       utils.GetCurrentTime(),
	}
	id, err := document_manage_model.SaveOutsideReport(report)
	if err != nil {
		return err
	}

	// 保存附件
	attachmentList := outsideReport.AttachmentList
	if len(attachmentList) > 0 {
		for _, attachment := range attachmentList {
			if attachment.Title == "" || attachment.Url == "" {
				continue
			}
			attachment.OutsideReportId = int(id)
			attachment.CreateTime = utils.GetCurrentTime()
			_, err := document_manage_model.SaveOutsideReportAttachment(attachment)
			if err != nil {
				return err
			}
		}
	}
	return err
}

func DocumentReportDetail(outsideReportId int) (*document_manage_model.OutsideReportBO, error) {
	logs.Info("DocumentReportDetail")

	outsideReport, err := document_manage_model.GetOutsideReportById(outsideReportId)
	if err != nil {
		return nil, err
	}

	attachmentList, err := document_manage_model.GetOutsideReportAttachmentListByReportId(outsideReportId)
	if err != nil {
		return nil, err
	}

	outsideReportBO := document_manage_model.OutsideReportBO{
		OutsideReportId: outsideReportId,
		Source:          outsideReport.Source,
		Title:           outsideReport.Title,
		Abstract:        outsideReport.Abstract,
		ClassifyId:      outsideReport.ClassifyId,
		ClassifyName:    outsideReport.ClassifyName,
		Content:         outsideReport.Content,
		SysUserId:       outsideReport.SysUserId,
		SysUserName:     outsideReport.SysUserName,
		AttachmentList:  attachmentList,
	}
	return &outsideReportBO, nil
}

func DocumentUpdate(outsideReport *document_manage_model.OutsideReportBO) error {
	logs.Info("DocumentUpdate")
	report, err := document_manage_model.GetOutsideReportById(outsideReport.OutsideReportId)
	if err != nil {
		return err
	}

	if report == nil {
		return fmt.Errorf("报告不存在")
	}
	// 更新报告
	if outsideReport.Title != "" {
		report.Title = outsideReport.Title
	}
	if outsideReport.Abstract != "" {
		report.Abstract = outsideReport.Abstract
	}
	if outsideReport.ClassifyId > 0 {
		report.ClassifyId = outsideReport.ClassifyId
	}
	if outsideReport.ClassifyName != "" {
		report.ClassifyName = outsideReport.ClassifyName
	}
	if outsideReport.Content != "" {
		report.Content = outsideReport.Content
	}
	report.ModifyTime = utils.GetCurrentTime()
	report.ReportUpdateTime = utils.GetCurrentTime()
	err = document_manage_model.UpdateOutsideReport(report)
	if err != nil {
		return fmt.Errorf("更新报告失败, Err: %s", err.Error())
	}

	// 更新报告附件
	attachmentList := outsideReport.AttachmentList
	if len(attachmentList) > 0 {
		err = document_manage_model.DeleteReportAttachmentByReportId(outsideReport.OutsideReportId)
		if err != nil {
			return fmt.Errorf("删除报告附件失败, Err: %s", err.Error())
		}

		for _, attachment := range attachmentList {
			if attachment.Title == "" || attachment.Url == "" {
				continue
			}
			attachment.OutsideReportId = outsideReport.OutsideReportId
			attachment.CreateTime = utils.GetCurrentTime()
			_, err := document_manage_model.SaveOutsideReportAttachment(attachment)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func DocumentDelete(outsideReportId int) error {
	logs.Info("DocumentDelete")

	report, err := document_manage_model.GetOutsideReportById(outsideReportId)
	if err != nil {
		return err
	}
	if report == nil {
		return fmt.Errorf("报告不存在")
	}

	err = document_manage_model.DeleteOutsideReport(outsideReportId)
	if err != nil {
		return err
	}
	err = document_manage_model.DeleteReportAttachmentByReportId(outsideReportId)
	if err != nil {
		return err
	}
	return nil
}