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

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

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

	//获取所有已启用分类
	var condition string
	pars := make([]interface{}, 0)

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

	classifyList, err := models.GetClassifyListByCondition(condition, pars)
	if err != nil {
		return nil, err
	}

	// 查询用户已收藏的分类
	collectClassifyList, err := models.GetUserCollectClassifyList(userId, 0)
	if err != nil {
		return nil, err
	}
	// 转换成map
	collectClassifyMap := make(map[int]bool)
	for _, collectClassify := range collectClassifyList {
		collectClassifyMap[collectClassify.ClassifyId] = true
	}

	// 递归处理分类 拿到父级分类和对应的子级分类
	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,
			}
			if _, ok := collectClassifyMap[classify.Id]; ok {
				classifyVO.IsCollect = 1
			}

			classifyVO.Children = getChildClassify(classifyList, classify.Id, collectClassifyMap)
			classifyVOList = append(classifyVOList, classifyVO)
		}
	}

	return classifyVOList, nil
}

func getChildClassify(classifyList []models.Classify, classifyId int, collectClassifyMap map[int]bool) *[]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,
			}
			if _, ok := collectClassifyMap[classify.Id]; ok {
				classifyVO.IsCollect = 1
			}
			classifyVO.Children = getChildClassify(classifyList, classify.Id, collectClassifyMap)
			childList = append(childList, classifyVO)
		}
	}
	return &childList
}

func DocumentCollectClassify(classifyId, userId int) error {
	logs.Info("DocumentCollectClassify")

	// 查询用户是否已收藏该分类
	collectClassifyList, err := models.GetUserCollectClassifyList(userId, classifyId)
	if err != nil {
		return err
	}
	if len(collectClassifyList) > 0 {
		err := models.DeleteUserCollectClassify(userId, classifyId)
		if err != nil {
			return err
		}
	} else {
		err = models.InsertUserCollectClassify(models.UserCollectClassify{
			ClassifyId: classifyId,
			SysUserId:  userId,
			CreateTime: utils.GetCurrentTime(),
		})
		if err != nil {
			return err
		}
	}

	return nil
}

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,
				PermissionName:      chartPermission.PermissionName,
				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,
				PermissionName:      permission.PermissionName,
				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(userId, 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 {
		// 递归查询子分类
		for _, classifyId := range classifyIdList {
			id, err := strconv.Atoi(classifyId)
			if err != nil {
				return nil, err
			}

			if id == 0 {
				classifyIdList = append(classifyIdList, classifyId)
			} else {
				childrenClassifyIdList, err := GetAllClassifyIdsByParentId(id)
				if err != nil {
					return nil, err
				}
				classifyIdList = append(classifyIdList, childrenClassifyIdList...)
			}
		}
		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+"%")
	}

	if len(chartPermissionIdList) > 0 {
		condition += ` GROUP BY t1.outside_report_id HAVING COUNT(DISTINCT t2.chart_permission_id) = ` + strconv.Itoa(len(chartPermissionIdList))
	}

	count, err := document_manage_model.GetOutsideReportListByConditionCount(condition, pars, chartPermissionIdList)
	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.report_update_time desc`
	}

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

	// 查询用户已收藏的分类
	collectClassifyList, err := models.GetUserCollectClassifyList(userId, 0)
	if err != nil {
		return nil, err
	}
	// 转换成map
	collectClassifyMap := make(map[int]bool)
	for _, collectClassify := range collectClassifyList {
		collectClassifyMap[collectClassify.ClassifyId] = true
	}

	for i, _ := range outsideReportList {
		if _, ok := collectClassifyMap[outsideReportList[i].ClassifyId]; ok {
			outsideReportList[i].IsCollect = 1
		}
	}

	reportPage.Paging = page
	reportPage.List = outsideReportList

	return &reportPage, nil
}

// GetAllClassifyIdsByParentId 递归查询子分类
func GetAllClassifyIdsByParentId(parentId int) ([]string, error) {
	var classifyIdList []string

	// 获取子分类
	classifyList, err := models.GetClassifyListByParentId(parentId)
	if err != nil {
		return nil, err
	}

	// 遍历子分类
	for _, classify := range classifyList {
		classifyIdList = append(classifyIdList, strconv.Itoa(classify.Id))
		// 递归调用
		subClassifyIds, err := GetAllClassifyIdsByParentId(classify.Id)
		if err != nil {
			return nil, err
		}
		classifyIdList = append(classifyIdList, subClassifyIds...)
	}

	return classifyIdList, nil
}

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

	// 作者为 全球市场战略研究中心 PCI Research
	author := "全球市场战略研究中心 PCI Research"
	// 已发布的报告
	state := 2

	count, err := models.GetReportListByCollectCount(classifyIdFirst, classifyIdSecond, classifyIdThird, keyword, author, state)
	if err != nil {
		return nil, err
	}
	reportPage := models.ReportListResp{}

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

	reportList, err := models.GetReportListByCollectList(classifyIdFirst, classifyIdSecond, classifyIdThird, keyword, orderField, orderType, startSize, pageSize, author, state)
	if err != nil {
		return nil, err
	}

	for _, report := range reportList {
		report.ModifyTime = report.ModifyTime.UTC()
	}

	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:         html.UnescapeString(outsideReport.Content),
		SysUserId:       outsideReport.SysUserId,
		SysUserName:     outsideReport.SysUserName,
		CreateTime:      outsideReport.CreateTime,
		ModifyTime:      outsideReport.ModifyTime,
		ReportCode:      outsideReport.ReportCode,
		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
}

func RuiSiReportListV2(classifyIdList, chartPermissionIdList []string, keyword, orderField, orderType string, userId, startSize, pageSize int) (*models.ReportListResp, error) {
	logs.Info("RuiSiReportList")

	allClassifyList, err := models.GetClassifyListByIdStrList(classifyIdList)
	if err != nil {
		return nil, err
	}
	classifyIdFirst := make([]string, 0)
	classifyIdSecond := make([]string, 0)
	classifyIdThird := make([]string, 0)
	for _, v := range allClassifyList {
		switch v.Level {
		case 1:
			classifyIdFirst = append(classifyIdFirst, strconv.Itoa(v.Id))
		case 2:
			classifyIdSecond = append(classifyIdSecond, strconv.Itoa(v.Id))
		case 3:
			classifyIdThird = append(classifyIdThird, strconv.Itoa(v.Id))
		}
	}
	// 作者为 全球市场战略研究中心 PCI Research
	var author string
	//author := "战研中心 PCIR"
	// 已发布/已审批的公开发布的报告
	isPublic := 1
	stateArr := []int{2, 6}

	count, err := models.GetReportListByCollectCountV2(classifyIdFirst, classifyIdSecond, classifyIdThird, chartPermissionIdList, keyword, author, isPublic, stateArr)
	if err != nil {
		return nil, err
	}
	reportPage := models.ReportListResp{}

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

	reportList, err := models.GetReportListByCollectListV2(classifyIdFirst, classifyIdSecond, classifyIdThird, chartPermissionIdList, keyword, orderField, orderType, startSize, pageSize, author, isPublic, stateArr)
	if err != nil {
		return nil, err
	}

	// 查询用户已收藏的分类
	collectClassifyList, err := models.GetUserCollectClassifyList(userId, 0)
	if err != nil {
		return nil, err
	}
	// 转换成map
	collectClassifyMap := make(map[int]bool)
	for _, collectClassify := range collectClassifyList {
		collectClassifyMap[collectClassify.ClassifyId] = true
	}

	for i, report := range reportList {
		report.ModifyTime = report.ModifyTime.UTC()
		if _, ok := collectClassifyMap[reportList[i].ClassifyIdFirst]; ok {
			reportList[i].IsCollect = 1
		}
		if _, ok := collectClassifyMap[reportList[i].ClassifyIdSecond]; ok {
			reportList[i].IsCollect = 1
		}
		if _, ok := collectClassifyMap[reportList[i].ClassifyIdThird]; ok {
			reportList[i].IsCollect = 1
		}
	}

	reportPage.Paging = page
	reportPage.List = reportList

	return &reportPage, nil
}
