package data_manage_permission

import (
	"eta/eta_api/utils"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"strconv"
	"time"
)

// ChartInfoPermission
// @Description: 图表信息权限表
type ChartInfoPermission struct {
	ChartInfoPermissionId int64     `json:"chart_info_permission_id" orm:"column(chart_info_permission_id);pk"`
	ChartInfoId           int32     `json:"chart_info_id"` // 图表id
	Source                int32     `json:"source"`        // 1：ETA图库；2：商品价格曲线；3：相关性图
	SysUserId             int32     `json:"sys_user_id"`   // 系统用户id
	ModifyTime            time.Time `json:"modify_time"`   // 变更时间
	CreateTime            time.Time `json:"create_time"`   // 关系建立时间
}

// ChartClassifyPermission
// @Description: 图表分类权限表
type ChartClassifyPermission struct {
	ChartClassifyPermissionId int64     `json:"chart_classify_permission_id" orm:"column(chart_classify_permission_id);pk"`
	ChartClassifyId           int32     `json:"chart_classify_id"` // 分类id
	Source                    int32     `json:"source"`            // 分类来源: 1-图库; 2-商品价格曲线; 3-相关性图表; 6-拟合方程图表; 7-统计特征
	SysUserId                 int32     `json:"sys_user_id"`       // 系统用户id
	ModifyTime                time.Time `json:"modify_time"`       // 变更时间
	CreateTime                time.Time `json:"create_time"`       // 关系建立时间
}

// SetIsPermissionByChartClassifyIdList
// @Description: 设置图表分类是否涉密
// @author: Roc
// @datetime 2024-04-01 10:53:23
// @param classifyIdList []int
// @param chartClassifySource int
// @return err error
func SetIsPermissionByChartClassifyIdList(classifyIdList []int, chartClassifySource int) (err error) {
	num := len(classifyIdList)
	o, err := orm.NewOrmUsingDB("data").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
		} else {
			_ = o.Commit()
		}
	}()

	//// 获取已经配置涉密的分类权限
	//chartClassifyList := make([]*ChartClassify, 0)
	//sql := `SELECT * FROM chart_classify WHERE is_join_permission = ? `
	//_, err = o.Raw(sql, 1).QueryRows(&chartClassifyList)
	//if err != nil {
	//	return
	//}
	//chartClassifyMap := make(map[int]*ChartClassify)
	//for _, v := range chartClassifyList {
	//	chartClassifyMap[v.ClassifyId] = v
	//}

	// 先将所有已经设置了涉密的分类设置为不涉密
	sql := `UPDATE chart_classify SET is_join_permission=?,modify_time=now() WHERE is_join_permission = 1 AND source = ?`
	_, err = o.Raw(sql, 0, chartClassifySource).Exec()
	if err != nil {
		return
	}

	if num > 0 {
		// 将对应的分类设置为涉密
		sql = `UPDATE chart_classify SET is_join_permission=?,modify_time=now() WHERE source = ? AND chart_classify_id in (` + utils.GetOrmInReplace(num) + `) `
		_, err = o.Raw(sql, 1, chartClassifySource, classifyIdList).Exec()
		if err != nil {
			return
		}
	}

	return
}

// SetPermissionByChartIdList
// @Description: 根据图表ID列表设置图表的用户权限
// @author: Roc
// @datetime 2024-04-01 10:26:17
// @param chartIdList []string
// @param userIdList []int
// @param source int
// @return err error
func SetPermissionByChartIdList(chartIdList []string, userIdList []int, source int) (err error) {
	chartNum := len(chartIdList)
	if chartNum <= 0 {
		return
	}
	o, err := orm.NewOrmUsingDB("data").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
		} else {
			_ = o.Commit()
		}
	}()

	// 获取已经配置的图表权限用户
	chartInfoPermissionList := make([]*ChartInfoPermission, 0)
	sql := `SELECT * FROM chart_info_permission WHERE source = ? AND chart_info_id in (` + utils.GetOrmInReplace(chartNum) + `) `
	_, err = o.Raw(sql, source, chartIdList).QueryRows(&chartInfoPermissionList)
	if err != nil {
		return
	}
	chartInfoPermissionMap := make(map[string]*ChartInfoPermission)
	for _, v := range chartInfoPermissionList {
		chartInfoPermissionMap[fmt.Sprint(v.ChartInfoId, "_", v.SysUserId)] = v
	}

	// 标记图表是否纳入权限管控
	{
		// 默认 标记图表为纳入权限管控
		isJoinPermission := 1
		// 用户不选的情况下，说明是要给这些图表移除权限管控
		if len(userIdList) <= 0 {
			// 标记图表为不纳入权限管控
			isJoinPermission = 0
		}
		sql = `UPDATE chart_info SET is_join_permission=?,modify_time=now() WHERE source = ? AND chart_info_id in (` + utils.GetOrmInReplace(chartNum) + `) `
		_, err = o.Raw(sql, isJoinPermission, source, chartIdList).Exec()
		if err != nil {
			return
		}
	}

	// 待添加的配置项
	addList := make([]*ChartInfoPermission, 0)

	// 遍历待配置的图表和用户，筛选出需要添加的配置项
	for _, chartInfoIdStr := range chartIdList {
		chartInfoId, tmpErr := strconv.ParseInt(chartInfoIdStr, 10, 64)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		for _, userId := range userIdList {
			key := fmt.Sprint(chartInfoId, "_", userId)
			if _, ok := chartInfoPermissionMap[key]; ok {
				// 如果存在那么就移除，说明不需要处理了
				delete(chartInfoPermissionMap, key)
			} else {
				// 如果不存在，那么就添加
				addList = append(addList, &ChartInfoPermission{
					//PermissionId: 0,
					ChartInfoId: int32(chartInfoId),
					SysUserId:   int32(userId),
					Source:      int32(source),
					ModifyTime:  time.Now(),
					CreateTime:  time.Now(),
				})
			}
		}
	}

	// 添加待配置项
	if len(addList) > 0 {
		_, err = o.InsertMulti(500, addList)
		if err != nil {
			return
		}
	}

	// 移除废弃的配置项
	{
		// 待移除的配置项
		deletePermissionIdList := make([]int64, 0)
		for _, v := range chartInfoPermissionMap {
			deletePermissionIdList = append(deletePermissionIdList, v.ChartInfoPermissionId)
		}

		deletePermissionIdNum := len(deletePermissionIdList)
		if deletePermissionIdNum > 0 {
			sql = "DELETE FROM chart_info_permission WHERE chart_info_permission_id in (" + utils.GetOrmInReplace(deletePermissionIdNum) + ")"
			_, err = o.Raw(sql, deletePermissionIdList).Exec()
			if err != nil {
				return
			}
		}
	}

	return
}

// SetPermissionByChartClassifyIdList
// @Description: 根据图表分类ID列表设置分类的用户权限
// @author: Roc
// @datetime 2024-03-28 14:53:04
// @param classifyIdList []int
// @param userIdList []int
// @return err error
func SetPermissionByChartClassifyIdList(classifyIdList []int, userIdList []int, classifyType int) (err error) {
	userNum := len(userIdList)
	if userNum <= 0 {
		return
	}
	o, err := orm.NewOrmUsingDB("data").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
		} else {
			_ = o.Commit()
		}
	}()

	// 获取当前选择用户已经配置的图表分类权限
	classifyPermissionList := make([]*ChartClassifyPermission, 0)
	sql := `SELECT * FROM chart_classify_permission WHERE source = ? AND sys_user_id in (` + utils.GetOrmInReplace(userNum) + `) `
	_, err = o.Raw(sql, classifyType, userIdList).QueryRows(&classifyPermissionList)
	if err != nil {
		return
	}
	classifyPermissionMap := make(map[string]*ChartClassifyPermission)
	for _, v := range classifyPermissionList {
		classifyPermissionMap[fmt.Sprint(v.ChartClassifyId, "_", v.SysUserId)] = v
	}

	// 待添加的配置项
	addList := make([]*ChartClassifyPermission, 0)

	// 遍历待配置的图表和用户，筛选出需要添加的配置项
	for _, userId := range userIdList {
		for _, classifyId := range classifyIdList {
			key := fmt.Sprint(classifyId, "_", userId)
			if _, ok := classifyPermissionMap[key]; ok {
				// 如果存在那么就移除，说明不需要处理了
				delete(classifyPermissionMap, key)
			} else {
				// 如果不存在，那么就提那家
				addList = append(addList, &ChartClassifyPermission{
					//PermissionId: 0,
					ChartClassifyId: int32(classifyId),
					Source:          int32(classifyType),
					SysUserId:       int32(userId),
					ModifyTime:      time.Now(),
					CreateTime:      time.Now(),
				})
			}
		}
	}

	// 添加待配置项
	if len(addList) > 0 {
		_, err = o.InsertMulti(500, addList)
		if err != nil {
			return
		}
	}

	// 移除废弃的配置项
	{
		// 获取移除的配置项
		deletePermissionIdList := make([]int64, 0)
		for _, v := range classifyPermissionMap {
			deletePermissionIdList = append(deletePermissionIdList, v.ChartClassifyPermissionId)
		}

		deletePermissionIdNum := len(deletePermissionIdList)
		if deletePermissionIdNum > 0 {
			sql = "DELETE FROM chart_classify_permission WHERE chart_classify_permission_id in (" + utils.GetOrmInReplace(deletePermissionIdNum) + ")"
			_, err = o.Raw(sql, deletePermissionIdList).Exec()
			if err != nil {
				return
			}
		}
	}

	return
}

// GetPermissionChartClassifyIdListByUserId
// @Description: 根据用户ID获取已经配置的分类id列表
// @author: Roc
// @datetime 2024-03-29 16:24:46
// @param userId int
// @param classifyType int
// @return chartClassifyIdList []int
// @return err error
func GetPermissionChartClassifyIdListByUserId(userId int, classifyType int) (chartClassifyIdList []int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT chart_classify_id FROM chart_classify_permission WHERE source = ? AND sys_user_id = ? `
	_, err = o.Raw(sql, classifyType, userId).QueryRows(&chartClassifyIdList)

	return
}

// GetPermissionUserIdListByChartId
// @Description: 根据图表ID获取已经配置的用户id列表
// @author: Roc
// @datetime 2024-03-29 16:24:46
// @param dataId int
// @param source int
// @return chartIdList []int
// @return err error
func GetPermissionUserIdListByChartId(dataId int, source int) (userIdList []int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT sys_user_id FROM chart_info_permission WHERE source = ? AND chart_info_id= ? `
	_, err = o.Raw(sql, source, dataId).QueryRows(&userIdList)

	return
}

// GetPermissionUserIdListByChartClassifyId
// @Description: 根据图表分类ID获取已经配置的用户id列表
// @author: Roc
// @datetime 2024-03-29 16:24:46
// @param classifyId int
// @param source int
// @return userIdList []int
// @return err error
func GetPermissionUserIdListByChartClassifyId(classifyId int, source int) (userIdList []int, err error) {
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT sys_user_id FROM chart_classify_permission WHERE source = ? AND chart_classify_id= ? `
	_, err = o.Raw(sql, source, classifyId).QueryRows(&userIdList)

	return
}

// GetPermissionChartIdList
// @Description: 获取用户权限的图表列表
// @author: Roc
// @datetime 2024-03-28 16:50:47
// @param userId int
// @param chartInfoId int
// @return idList []int
// @return err error
func GetPermissionChartIdList(userId, chartInfoId int) (idList []int, err error) {
	pars := []interface{}{userId}
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT chart_info_id FROM chart_info_permission WHERE sys_user_id = ? `
	if chartInfoId > 0 {
		sql += ` AND chart_info_id = ? `
		pars = append(pars, chartInfoId)
	}
	_, err = o.Raw(sql, pars).QueryRows(&idList)

	return
}

// GetPermissionChartClassifyIdList
// @Description: 获取用户权限的图表分类列表
// @author: Roc
// @datetime 2024-03-28 16:50:47
// @param userId int
// @param classifyId int
// @return idList []int
// @return err error
func GetPermissionChartClassifyIdList(userId, classifyId int) (idList []int, err error) {
	pars := []interface{}{userId}
	o := orm.NewOrmUsingDB("data")
	sql := `SELECT chart_classify_id FROM chart_classify_permission WHERE sys_user_id = ? `
	if classifyId > 0 {
		sql += ` AND chart_classify_id = ? `
		pars = append(pars, classifyId)
	}
	_, err = o.Raw(sql, pars).QueryRows(&idList)

	return
}

// InheritParentClassifyByChartClassifyId
// @Description: 继承父级分类的图表权限信息
// @author: Roc
// @datetime 2024-04-07 21:02:51
// @param dataSource int
// @param chartSource int
// @param classifyId int
// @param parentClassifyId int
// @param classifyName string
// @param uniqueCode string
// @return err error
func InheritParentClassifyByChartClassifyId(dataSource, chartSource, classifyId, parentClassifyId int, classifyName, uniqueCode string) (err error) {
	o, err := orm.NewOrmUsingDB("data").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
		} else {
			_ = o.Commit()
		}
	}()

	// 将对应的分类设置为涉密
	sql := `UPDATE chart_classify SET is_join_permission=?,modify_time=now() WHERE source = ? AND chart_classify_id = ? `
	_, err = o.Raw(sql, 1, chartSource, classifyId).Exec()
	if err != nil {
		return
	}

	// 添加未授权记录
	{
		// 获取父级未授权的用户记录
		var parentRecordItems []*ChartInfoClassifyPermissionNoAuthRecord
		sql = `SELECT * FROM data_permission_classify_no_auth_record WHERE classify_id = ? AND source = ? AND sub_source = ? ORDER BY data_permission_classify_no_auth_record_id desc LIMIT ?,? `
		_, err = o.Raw(sql, parentClassifyId, dataSource, chartSource).QueryRows(&parentRecordItems)

		addNoAuthRecordItems := make([]*ChartInfoClassifyPermissionNoAuthRecord, 0)
		for _, v := range parentRecordItems {
			addNoAuthRecordItems = append(addNoAuthRecordItems, &ChartInfoClassifyPermissionNoAuthRecord{
				ChartInfoClassifyPermissionNoAuthRecordId: 0,
				Source:       v.Source,
				OpUniqueCode: uniqueCode,
				ClassifyId:   fmt.Sprint(classifyId),
				ClassifyName: classifyName,
				SysUserId:    v.SysUserId,
				CreateTime:   time.Now(),
			})
		}

		// 添加待配置项
		if len(addNoAuthRecordItems) > 0 {
			_, err = o.InsertMulti(500, addNoAuthRecordItems)
			if err != nil {
				return
			}
		}

	}

	// 添加授权记录
	{
		// 获取父级分类已经授权的用户
		parentClassifyPermissionList := make([]*ChartClassifyPermission, 0)
		sql = `SELECT * FROM chart_classify_permission WHERE source = ? AND chart_classify_id = ? `
		_, err = o.Raw(sql, chartSource, parentClassifyId).QueryRows(&parentClassifyPermissionList)
		if err != nil {
			return
		}

		addList := make([]*ChartClassifyPermission, 0)
		for _, v := range parentClassifyPermissionList {
			// 如果不存在，那么就提那家
			addList = append(addList, &ChartClassifyPermission{
				//PermissionId: 0,
				ChartClassifyId: int32(classifyId),
				Source:          int32(chartSource),
				SysUserId:       v.SysUserId,
				ModifyTime:      time.Now(),
				CreateTime:      time.Now(),
			})
		}
		// 添加待配置项
		if len(addList) > 0 {
			_, err = o.InsertMulti(500, addList)
			if err != nil {
				return
			}
		}
	}

	return
}

// ChartInfoPermissionNoAuthRecord
// @Description: 图表数据权限未授权记录表
type ChartInfoPermissionNoAuthRecord struct {
	ChartInfoPermissionNoAuthRecordId int64     `json:"chart_info_permission_no_auth_record_id"  orm:"column(chart_info_permission_no_auth_record_id);pk"` // 资产数据操作记录id
	OpUniqueCode                      string    `json:"op_unique_code"`                                                                                    // 操作的唯一编码，主要是记录统一操作的日志
	Source                            int32     `json:"source"`                                                                                            // 1：ETA图库；2：商品价格曲线；3：相关性图
	ChartInfoId                       int32     `json:"chart_info_id"`                                                                                     // 指标id
	ChartName                         string    `json:"chart_name"`                                                                                        // 图表名称
	SysUserId                         int32     `json:"sys_user_id"`                                                                                       // 系统用户id
	CreateTime                        time.Time `json:"create_time"`                                                                                       // 创建时间
}

// AddChartInfoPermissionNoAuthRecordBySourceAndDataIdList
// @Description: 添加未授权用户记录
// @author: Roc
// @datetime 2024-04-07 15:25:49
// @param source int
// @param chartSource int
// @param dataList []DataItem
// @param noAuthUserIdList []int 未授权用户
// @param authUserIdList []int 已授权用户
// @param uniqueCode
// @param content string
// @param opUserId int
// @return err error
func AddChartInfoPermissionNoAuthRecordBySourceAndDataIdList(source, chartSource int, dataList []DataItem, noAuthUserIdList, authUserIdList []int, uniqueCode, title, content string, opUserId int) (err error) {
	num := len(dataList)
	if num <= 0 {
		return
	}
	dataIdList := make([]int, 0)
	for _, v := range dataList {
		dataIdList = append(dataIdList, v.DataId)
	}
	userNum := len(noAuthUserIdList)
	if userNum <= 0 {
		return
	}
	o, err := orm.NewOrmUsingDB("data").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
		} else {
			_ = o.Commit()
		}
	}()

	// 根据指标获取已经存在的未授权记录
	var existList []*ChartInfoPermissionNoAuthRecord
	sql := `SELECT * FROM chart_info_permission_no_auth_record WHERE  source = ? AND chart_info_id in (` + utils.GetOrmInReplace(num) + `)`
	_, err = o.Raw(sql, chartSource, dataIdList).QueryRows(&existList)
	if err != nil {
		return
	}

	// 已经标记了的数据
	existMap := make(map[int32]map[string]*ChartInfoPermissionNoAuthRecord)
	for _, v := range existList {
		tmpUserExistMap, ok := existMap[v.SysUserId]
		if !ok {
			tmpUserExistMap = make(map[string]*ChartInfoPermissionNoAuthRecord)
		}

		key := fmt.Sprint(v.Source, "_", v.ChartInfoId)
		tmpUserExistMap[key] = v
		existMap[v.SysUserId] = tmpUserExistMap
	}

	addMessageList := make([]*DataPermissionMessage, 0)
	addRecordList := make([]*ChartInfoPermissionNoAuthRecord, 0)
	for _, userId := range noAuthUserIdList {
		isAdd := false

		tmpUserExistMap, userExistOk := existMap[int32(userId)]

		for _, dataItem := range dataList {
			// 判断是否已经存在，已经存在就过滤
			if userExistOk {
				key := fmt.Sprint(chartSource, "_", dataItem.DataId)
				_, ok := tmpUserExistMap[key]
				if ok {
					continue
				}
			}

			isAdd = true
			addRecordList = append(addRecordList, &ChartInfoPermissionNoAuthRecord{
				ChartInfoPermissionNoAuthRecordId: 0,
				OpUniqueCode:                      uniqueCode,
				Source:                            int32(chartSource),
				ChartInfoId:                       int32(dataItem.DataId),
				ChartName:                         dataItem.DataName,
				SysUserId:                         int32(userId),
				CreateTime:                        time.Now(),
			})
		}

		// 有记录的话，需要添加消息
		if isAdd {
			addMessageList = append(addMessageList, &DataPermissionMessage{
				DataPermissionMessageId: 0,
				SendUserId:              int32(opUserId),
				ReceiveUserId:           int32(userId),
				Content:                 title,
				Remark:                  content,
				OpType:                  3,
				Source:                  int32(source),
				SubSource:               int32(chartSource),
				OpUniqueCode:            uniqueCode,
				IsRead:                  0,
				CreateTime:              time.Now(),
				ModifyTime:              time.Now(),
			})
		}
	}

	// 添加消息
	if len(addMessageList) > 0 {
		_, err = o.InsertMulti(500, addMessageList)
		if err != nil {
			return
		}
	}

	// 添加记录
	if len(addRecordList) > 0 {
		_, err = o.InsertMulti(500, addRecordList)
		if err != nil {
			return
		}
	}

	// 已经授权了的用户，需要删除未授权记录
	authUserIdNum := len(authUserIdList)
	if authUserIdNum > 0 {
		sql = `DELETE FROM chart_info_permission_no_auth_record WHERE  source = ? AND sys_user_id in (` + utils.GetOrmInReplace(authUserIdNum) + `) AND chart_info_id in (` + utils.GetOrmInReplace(num) + `)`
		_, err = o.Raw(sql, chartSource, authUserIdList, dataIdList).Exec()
	}

	return
}

// DeleteChartInfoPermissionNoAuthRecordBySourceAndDataIdList
// @Description: 根据来源和数据id列表删除记录
// @author: Roc
// @datetime 2024-04-07 14:47:37
// @param chartSource int
// @param dataIdList []string
// @return err error
func DeleteChartInfoPermissionNoAuthRecordBySourceAndDataIdList(chartSource int, dataIdList []string) (err error) {
	num := len(dataIdList)
	if num <= 0 {
		return
	}
	o := orm.NewOrmUsingDB("data")

	sql := `DELETE FROM chart_info_permission_no_auth_record WHERE source = ? AND chart_info_id in (` + utils.GetOrmInReplace(num) + `)`
	_, err = o.Raw(sql, chartSource, dataIdList).Exec()

	return
}

func GetChartInfoDataPermissionNoAuthRecordListByUserId(userId int32, chartSource, startSize, pageSize int) (total int, items []*DataPermissionNoAuthRecord, err error) {
	o := orm.NewOrmUsingDB("data")

	// 获取总数
	sql := `SELECT count(1) AS total FROM chart_info_permission_no_auth_record WHERE sys_user_id = ? AND source = ? `
	err = o.Raw(sql, userId, chartSource).QueryRow(&total)
	if err != nil {
		return
	}

	sql = `SELECT chart_info_permission_no_auth_record_id as data_permission_no_auth_record_id,op_unique_code,source as sub_source,chart_info_id as data_id,chart_name as data_name,sys_user_id,create_time FROM chart_info_permission_no_auth_record WHERE sys_user_id = ? AND source = ? ORDER BY chart_info_permission_no_auth_record_id desc LIMIT ?,? `
	_, err = o.Raw(sql, userId, chartSource, startSize, pageSize).QueryRows(&items)

	return
}

type ChartInfoClassifyPermissionNoAuthRecord struct {
	ChartInfoClassifyPermissionNoAuthRecordId int64     `json:"chart_info_classify_permission_no_auth_record_id" orm:"column(chart_info_classify_permission_no_auth_record_id);pk"` // 资产分类数据操作记录id
	Source                                    int32     `json:"source"`                                                                                                             // 子来源 ：ETA表格中的各种表格类型，以及图表的来源（这个是后续的扩展方向）
	OpUniqueCode                              string    `json:"op_unique_code"`                                                                                                     // 操作的唯一编码，主要是记录统一操作的日志
	ClassifyId                                string    `json:"classify_id"`                                                                                                        // 图表资产分类id
	ClassifyName                              string    `json:"classify_name"`                                                                                                      // 图表资产分类名称
	SysUserId                                 int32     `json:"sys_user_id"`                                                                                                        // 系统用户id
	CreateTime                                time.Time `json:"create_time"`                                                                                                        // 创建时间
}

// AddChartInfoClassifyNoAuthRecordBySourceAndClassifyIdList
// @Description: 根据分类添加用户分类未授权记录
// @author: Roc
// @datetime 2024-04-07 16:44:21
// @param source int
// @param chartSource int
// @param classifyInfoList []ClassifyDataItem
// @param noAuthUserIdList []int
// @param uniqueCode string
// @param content string
// @param opUserId int
// @return err error
func AddChartInfoClassifyNoAuthRecordBySourceAndClassifyIdList(source, chartSource int, classifyInfoList []ClassifyDataItem, noAuthUserIdList []int, uniqueCode, title, content string, opUserId int) (err error) {
	num := len(classifyInfoList)
	if num <= 0 {
		return
	}
	// 分类id
	classifyIdList := make([]int, 0)
	for _, v := range classifyInfoList {
		classifyIdList = append(classifyIdList, v.ClassifyId)
	}

	userNum := len(noAuthUserIdList)
	if userNum <= 0 {
		return
	}
	o, err := orm.NewOrmUsingDB("data").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
		} else {
			_ = o.Commit()
		}
	}()

	// 根据分类获取已经存在的未授权记录
	var existList []*ChartInfoClassifyPermissionNoAuthRecord
	sql := `SELECT * FROM chart_info_classify_permission_no_auth_record WHERE source = ? AND classify_id in (` + utils.GetOrmInReplace(num) + `)`
	_, err = o.Raw(sql, chartSource, classifyIdList).QueryRows(&existList)
	if err != nil {
		return
	}

	// 已经标记了的数据
	existMap := make(map[int32]map[string]*ChartInfoClassifyPermissionNoAuthRecord)
	for _, v := range existList {
		tmpUserExistMap, ok := existMap[v.SysUserId]
		if !ok {
			tmpUserExistMap = make(map[string]*ChartInfoClassifyPermissionNoAuthRecord)
		}

		key := fmt.Sprint(v.Source, "_", v.ClassifyId)
		tmpUserExistMap[key] = v
		existMap[v.SysUserId] = tmpUserExistMap
	}

	addMessageList := make([]*DataPermissionMessage, 0)
	addRecordList := make([]*ChartInfoClassifyPermissionNoAuthRecord, 0)
	for _, userId := range noAuthUserIdList {
		isAdd := false

		tmpUserExistMap, userExistOk := existMap[int32(userId)]

		for _, dataItem := range classifyInfoList {
			// 判断是否已经存在，已经存在就过滤
			if userExistOk {
				key := fmt.Sprint(chartSource, "_", dataItem.ClassifyId)
				_, ok := tmpUserExistMap[key]
				if ok {
					continue
				}
			}

			isAdd = true
			addRecordList = append(addRecordList, &ChartInfoClassifyPermissionNoAuthRecord{
				ChartInfoClassifyPermissionNoAuthRecordId: 0,
				Source:       int32(chartSource),
				OpUniqueCode: uniqueCode,
				ClassifyId:   fmt.Sprint(dataItem.ClassifyId),
				ClassifyName: dataItem.ClassifyName,
				SysUserId:    int32(userId),
				CreateTime:   time.Now(),
			})
		}

		// 有记录的话，需要添加消息
		if isAdd {
			addMessageList = append(addMessageList, &DataPermissionMessage{
				DataPermissionMessageId: 0,
				SendUserId:              int32(opUserId),
				ReceiveUserId:           int32(userId),
				Content:                 title,
				Remark:                  content,
				OpType:                  4,
				Source:                  int32(source),
				SubSource:               int32(chartSource),
				OpUniqueCode:            uniqueCode,
				IsRead:                  0,
				CreateTime:              time.Now(),
				ModifyTime:              time.Now(),
			})
		}
	}

	// 添加消息
	if len(addMessageList) > 0 {
		_, err = o.InsertMulti(500, addMessageList)
		if err != nil {
			return
		}
	}

	// 添加记录
	if len(addRecordList) > 0 {
		_, err = o.InsertMulti(500, addRecordList)
		if err != nil {
			return
		}
	}

	// 移除已经公开了的分类权限，需要删除未授权记录
	authUserIdNum := len(classifyIdList)
	if authUserIdNum > 0 {
		sql = `DELETE FROM chart_info_classify_permission_no_auth_record WHERE source = ? AND classify_id not in (` + utils.GetOrmInReplace(num) + `)`
		_, err = o.Raw(sql, chartSource, classifyIdList).Exec()
	}

	return
}

// AddChartInfoClassifyNoAuthRecordBySourceAndUserIdList
// @Description: 根据用户添加用户分类未授权记录
// @author: Roc
// @datetime 2024-04-07 20:12:44
// @param source int
// @param chartSource int
// @param noAuthClassifyMap map[int]ClassifyDataItem
// @param configUserIdList []int
// @param uniqueCode string
// @param content string
// @param opUserId int
// @return err error
func AddChartInfoClassifyNoAuthRecordBySourceAndUserIdList(source, chartSource int, noAuthClassifyMap map[int]ClassifyDataItem, configUserIdList []int, uniqueCode, title, content string, opUserId int) (err error) {
	// 当前配置用户
	configUserNum := len(configUserIdList)
	if configUserNum <= 0 {
		return
	}

	//// 总共的涉密分类
	//noAuthClassifyInfoNum := len(noAuthClassifyMap)
	//if noAuthClassifyInfoNum <= 0 {
	//	return
	//}

	o, err := orm.NewOrmUsingDB("data").Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
		} else {
			_ = o.Commit()
		}
	}()

	// 根据当前配置用户获取已经存在的未授权记录
	var existList []*ChartInfoClassifyPermissionNoAuthRecord
	sql := `SELECT * FROM chart_info_classify_permission_no_auth_record WHERE source = ? AND sys_user_id in (` + utils.GetOrmInReplace(configUserNum) + `)`
	_, err = o.Raw(sql, chartSource, configUserIdList).QueryRows(&existList)
	if err != nil {
		return
	}

	// 已经标记了的数据
	existMap := make(map[int32]map[string]*ChartInfoClassifyPermissionNoAuthRecord)
	delRecordIdMap := make(map[int64]int64)
	for _, v := range existList {
		tmpUserExistMap, ok := existMap[v.SysUserId]
		if !ok {
			tmpUserExistMap = make(map[string]*ChartInfoClassifyPermissionNoAuthRecord)
		}

		tmpUserExistMap[v.ClassifyId] = v
		existMap[v.SysUserId] = tmpUserExistMap

		// 已经配置了的记录id
		delRecordIdMap[v.ChartInfoClassifyPermissionNoAuthRecordId] = v.ChartInfoClassifyPermissionNoAuthRecordId
	}

	addMessageList := make([]*DataPermissionMessage, 0)
	addRecordList := make([]*ChartInfoClassifyPermissionNoAuthRecord, 0)
	for _, userId := range configUserIdList {
		isAdd := false

		tmpUserExistMap, userExistOk := existMap[int32(userId)]

		for _, dataItem := range noAuthClassifyMap {
			// 判断是否已经存在，已经存在就过滤
			if userExistOk {
				key := fmt.Sprint(dataItem.ClassifyId)
				tmpUserRecord, ok := tmpUserExistMap[key]
				if ok {
					delete(delRecordIdMap, tmpUserRecord.ChartInfoClassifyPermissionNoAuthRecordId)
					continue
				}
			}

			isAdd = true
			addRecordList = append(addRecordList, &ChartInfoClassifyPermissionNoAuthRecord{
				ChartInfoClassifyPermissionNoAuthRecordId: 0,
				Source:       int32(chartSource),
				OpUniqueCode: uniqueCode,
				ClassifyId:   fmt.Sprint(dataItem.ClassifyId),
				ClassifyName: dataItem.ClassifyName,
				SysUserId:    int32(userId),
				CreateTime:   time.Now(),
			})
		}

		// 有记录的话，需要添加消息
		if isAdd {
			addMessageList = append(addMessageList, &DataPermissionMessage{
				DataPermissionMessageId: 0,
				SendUserId:              int32(opUserId),
				ReceiveUserId:           int32(userId),
				Content:                 content,
				Remark:                  content,
				OpType:                  4,
				Source:                  int32(source),
				SubSource:               int32(chartSource),
				OpUniqueCode:            uniqueCode,
				IsRead:                  0,
				CreateTime:              time.Now(),
				ModifyTime:              time.Now(),
			})
		}
	}

	// 添加消息
	if len(addMessageList) > 0 {
		_, err = o.InsertMulti(500, addMessageList)
		if err != nil {
			return
		}
	}

	// 添加记录
	if len(addRecordList) > 0 {
		_, err = o.InsertMulti(500, addRecordList)
		if err != nil {
			return
		}
	}

	// 需要删除未授权记录
	delRecordIdNum := len(delRecordIdMap)
	if delRecordIdNum > 0 {
		delRecordIdList := make([]int64, 0)
		for _, v := range delRecordIdMap {
			delRecordIdList = append(delRecordIdList, v)
		}
		sql = `DELETE FROM chart_info_classify_permission_no_auth_record WHERE chart_info_classify_permission_no_auth_record_id in (` + utils.GetOrmInReplace(delRecordIdNum) + `) `
		_, err = o.Raw(sql, delRecordIdList).Exec()
	}

	return
}

// DeleteChartInfoClassifyNoAuthRecordBySourceAndClassifyIdList
// @Description: 根据来源和删除分类授权记录
// @author: Roc
// @datetime 2024-04-07 14:47:37
// @param chartSource int
// @return err error
func DeleteChartInfoClassifyNoAuthRecordBySourceAndClassifyIdList(chartSource int) (err error) {
	o := orm.NewOrmUsingDB("data")

	sql := `DELETE FROM chart_info_classify_permission_no_auth_record WHERE source = ?`
	_, err = o.Raw(sql, chartSource).Exec()

	return
}

// GetChartInfoDataPermissionClassifyNoAuthRecordListByUserId
// @Description: 根据用户获取未授权的资产分类记录
// @author: Roc
// @datetime 2024-04-07 20:14:49
// @param userId int
// @param source int
// @param subSource int
// @param startSize int
// @param pageSize int
// @return total int
// @return items []*DataPermissionClassifyNoAuthRecord
// @return err error
func GetChartInfoDataPermissionClassifyNoAuthRecordListByUserId(userId int32, chartSource, startSize, pageSize int) (total int, items []*DataPermissionClassifyNoAuthRecord, err error) {
	o := orm.NewOrmUsingDB("data")

	// 获取总数
	sql := `SELECT count(1) AS total FROM chart_info_classify_permission_no_auth_record WHERE sys_user_id = ? AND source = ? `
	err = o.Raw(sql, userId, chartSource).QueryRow(&total)
	if err != nil {
		return
	}

	sql = `SELECT chart_info_classify_permission_no_auth_record_id as data_permission_classify_no_auth_record_id,source as sub_source,op_unique_code,classify_id,classify_name,sys_user_id,create_time  FROM chart_info_classify_permission_no_auth_record WHERE sys_user_id = ? AND source = ? ORDER BY chart_info_classify_permission_no_auth_record_id desc LIMIT ?,? `
	_, err = o.Raw(sql, userId, chartSource, startSize, pageSize).QueryRows(&items)

	return
}
