package cygx

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"time"
)

// AddCygxReportMappingCategoryGroupByArticleId  根据文章ID建立分类分组，主客观权限分组
func AddCygxReportMappingCategoryGroupByArticleId(articleId int) {
	time.Sleep(5 * time.Second)
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("根据文章ID建立分类分组，主客观权限分组，失败"+err.Error()+fmt.Sprint("articleId", articleId), 2)
		}
	}()
	detail, e := cygx.GetArticleDetailByArticleId(articleId)
	if e != nil {
		err = errors.New("GetArticleDetailById, Err: " + e.Error())
		return
	}
	categoryId := detail.CategoryId

	var condition string
	var pars []interface{}
	condition += ` AND category_id_celue = ? `
	pars = append(pars, categoryId)
	list, e := cygx.GetCygxReportMappingGroupList(condition, pars, 0, 999)
	if e != nil {
		err = errors.New("GetCygxReportMappingGroupList, Err: " + e.Error())
		return
	}
	pars = make([]interface{}, 0)
	var idCygxs []int
	for _, v := range list {
		idCygxs = append(idCygxs, v.IdCygx)
	}
	condition = ` AND id  IN (` + utils.GetOrmInReplace(len(idCygxs)) + `)`
	pars = append(pars, idCygxs)
	cygxlist, e := cygx.GetCygxReportMappingCygxByCon(condition, pars)
	if e != nil {
		err = errors.New("GetCygxReportMappingCygxByCon, Err: " + e.Error())
		return
	}
	var items []*cygx.CygxReportMappingCategoryGroup
	for _, v := range cygxlist {
		item := new(cygx.CygxReportMappingCategoryGroup)
		item.IdCygx = v.Id
		item.ChartPermissionId = v.ChartPermissionId
		//如果类型是报告就是主观，类型是纪要就是客观
		if detail.TypeName == "报告" {
			item.PermissionType = 1
		}
		if detail.TypeName == "纪要" {
			item.PermissionType = 2
		}
		item.ArticleId = articleId
		item.IsByHand = 1
		item.CreateTime = time.Now()
		item.ModifyTime = time.Now()
		items = append(items, item)
	}
	e = cygx.AddCygxReportMappingCategoryGroupMulti(items, articleId)
	return
}
