package data_manage_permission

import (
	"errors"
	"eta/eta_api/utils"
	"time"
)

// DataPermissionClassifyNoAuthRecord
// @Description: 资产分类数据权限未授权记录表
type DataPermissionClassifyNoAuthRecord struct {
	DataPermissionClassifyNoAuthRecordId int64     `json:"data_permission_classify_no_auth_record_id" orm:"column(data_permission_classify_no_auth_record_id);pk"` // 资产分类数据操作记录id
	Source                               int32     `json:"source"`                                                                                                 // 数据来源，1：手工数据指标 2：钢联化工数据库 3：ETA指标库 4：ETA预测指标 5：图库 6：ETA表格
	SubSource                            int32     `json:"sub_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"`                                                                                            // 创建时间
}

type ClassifyDataItem struct {
	ClassifyId   int    // 资产分类id（指标、图表、表格）
	ClassifyName string // 资产名称（指标、图表、表格）
}

//
//// AddClassifyNoAuthRecordBySourceAndClassifyIdList
//// @Description: 根据分类添加用户分类未授权记录
//// @author: Roc
//// @datetime 2024-04-07 16:44:21
//// @param source int
//// @param subSource int
//// @param classifyInfoList []ClassifyDataItem
//// @param noAuthUserIdList []int
//// @param uniqueCode string
//// @param content string
//// @param opUserId int
//// @return err error
//func AddClassifyNoAuthRecordBySourceAndClassifyIdList(source, subSource int, classifyInfoList []ClassifyDataItem, noAuthUserIdList []int, uniqueCode, 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 []*DataPermissionClassifyNoAuthRecord
//	sql := `SELECT * FROM data_permission_classify_no_auth_record WHERE source = ? AND sub_source = ? AND classify_id in (` + utils.GetOrmInReplace(num) + `)`
//	_, err = o.Raw(sql, source, subSource, classifyIdList).QueryRows(&existList)
//	if err != nil {
//		return
//	}
//
//	// 已经标记了的数据
//	existMap := make(map[int32]map[string]*DataPermissionClassifyNoAuthRecord)
//	for _, v := range existList {
//		tmpUserExistMap, ok := existMap[v.SysUserId]
//		if !ok {
//			tmpUserExistMap = make(map[string]*DataPermissionClassifyNoAuthRecord)
//		}
//
//		key := fmt.Sprint(v.Source, "_", v.SubSource, "_", v.ClassifyId)
//		tmpUserExistMap[key] = v
//		existMap[v.SysUserId] = tmpUserExistMap
//	}
//
//	addMessageList := make([]*DataPermissionMessage, 0)
//	addRecordList := make([]*DataPermissionClassifyNoAuthRecord, 0)
//	for _, userId := range noAuthUserIdList {
//		isAdd := false
//
//		tmpUserExistMap, userExistOk := existMap[int32(userId)]
//
//		for _, dataItem := range classifyInfoList {
//			// 判断是否已经存在，已经存在就过滤
//			if userExistOk {
//				key := fmt.Sprint(source, "_", subSource, "_", dataItem.ClassifyId)
//				_, ok := tmpUserExistMap[key]
//				if ok {
//					continue
//				}
//			}
//
//			isAdd = true
//			addRecordList = append(addRecordList, &DataPermissionClassifyNoAuthRecord{
//				DataPermissionClassifyNoAuthRecordId: 0,
//				Source:                               int32(source),
//				SubSource:                            int32(subSource),
//				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(subSource),
//				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 data_permission_classify_no_auth_record WHERE source = ? AND sub_source = ? AND classify_id not in (` + utils.GetOrmInReplace(num) + `)`
//		_, err = o.Raw(sql, source, subSource, classifyIdList).Exec()
//	}
//
//	return
//}
//
//// AddClassifyNoAuthRecordBySourceAndUserIdList
//// @Description: 根据用户添加用户分类未授权记录
//// @author: Roc
//// @datetime 2024-04-07 20:12:44
//// @param source int
//// @param subSource int
//// @param noAuthClassifyMap map[int]ClassifyDataItem
//// @param configUserIdList []int
//// @param uniqueCode string
//// @param content string
//// @param opUserId int
//// @return err error
//func AddClassifyNoAuthRecordBySourceAndUserIdList(source, subSource int, noAuthClassifyMap map[int]ClassifyDataItem, configUserIdList []int, uniqueCode, 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 []*DataPermissionClassifyNoAuthRecord
//	sql := `SELECT * FROM data_permission_classify_no_auth_record WHERE source = ? AND sub_source = ? AND sys_user_id in (` + utils.GetOrmInReplace(configUserNum) + `)`
//	_, err = o.Raw(sql, source, subSource, configUserIdList).QueryRows(&existList)
//	if err != nil {
//		return
//	}
//
//	// 已经标记了的数据
//	existMap := make(map[int32]map[string]*DataPermissionClassifyNoAuthRecord)
//	delRecordIdMap := make(map[int64]int64)
//	for _, v := range existList {
//		tmpUserExistMap, ok := existMap[v.SysUserId]
//		if !ok {
//			tmpUserExistMap = make(map[string]*DataPermissionClassifyNoAuthRecord)
//		}
//
//		tmpUserExistMap[v.ClassifyId] = v
//		existMap[v.SysUserId] = tmpUserExistMap
//
//		// 已经配置了的记录id
//		delRecordIdMap[v.DataPermissionClassifyNoAuthRecordId] = v.DataPermissionClassifyNoAuthRecordId
//	}
//
//	addMessageList := make([]*DataPermissionMessage, 0)
//	addRecordList := make([]*DataPermissionClassifyNoAuthRecord, 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.DataPermissionClassifyNoAuthRecordId)
//					continue
//				}
//			}
//
//			isAdd = true
//			addRecordList = append(addRecordList, &DataPermissionClassifyNoAuthRecord{
//				DataPermissionClassifyNoAuthRecordId: 0,
//				Source:                               int32(source),
//				SubSource:                            int32(subSource),
//				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(subSource),
//				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 data_permission_classify_no_auth_record WHERE data_permission_classify_no_auth_record_id in (` + utils.GetOrmInReplace(delRecordIdNum) + `) `
//		_, err = o.Raw(sql, delRecordIdList).Exec()
//	}
//
//	return
//}
//
//// DeleteClassifyNoAuthRecordBySourceAndClassifyIdList
//// @Description: 根据来源和删除分类授权记录
//// @author: Roc
//// @datetime 2024-04-07 14:47:37
//// @param source int
//// @param subSource int
//// @return err error
//func DeleteClassifyNoAuthRecordBySourceAndClassifyIdList(source, subSource int) (err error) {
//	o := orm.NewOrmUsingDB("data")
//
//	sql := `DELETE FROM data_permission_classify_no_auth_record WHERE source = ? AND sub_source = ?`
//	_, err = o.Raw(sql, source, subSource).Exec()
//
//	return
//}
//
//// GetDataPermissionClassifyNoAuthRecordListByUserId
//// @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 GetDataPermissionClassifyNoAuthRecordListByUserId(userId, source, subSource int32, startSize, pageSize int) (total int, items []*DataPermissionClassifyNoAuthRecord, err error) {
//	o := orm.NewOrmUsingDB("data")
//
//	// 获取总数
//	sql := `SELECT count(1) AS total FROM data_permission_classify_no_auth_record WHERE sys_user_id = ? AND source = ? AND sub_source = ? `
//	err = o.Raw(sql, userId, source, subSource).QueryRow(&total)
//	if err != nil {
//		return
//	}
//
//	sql = `SELECT * FROM data_permission_classify_no_auth_record WHERE sys_user_id = ? AND source = ? AND sub_source = ? ORDER BY data_permission_classify_no_auth_record_id desc LIMIT ?,? `
//	_, err = o.Raw(sql, userId, source, subSource, startSize, pageSize).QueryRows(&items)
//
//	return
//}

// AddClassifyNoAuthRecordBySourceAndClassifyIdList
// @Description: 根据分类添加用户分类未授权记录
// @author: Roc
// @datetime 2024-04-07 16:44:21
// @param source int
// @param subSource int
// @param classifyInfoList []ClassifyDataItem
// @param noAuthUserIdList []int
// @param uniqueCode string
// @param content string
// @param opUserId int
// @return err error
func AddClassifyNoAuthRecordBySourceAndClassifyIdList(source, subSource int, classifyInfoList []ClassifyDataItem, noAuthUserIdList []int, uniqueCode, title, content string, opUserId int) (err error) {
	switch source {
	case 3, 4:
		edbClassifyType := 0
		if source == 4 {
			edbClassifyType = 1
		}
		err = AddEdbInfoClassifyNoAuthRecordBySourceAndClassifyIdList(source, edbClassifyType, classifyInfoList, noAuthUserIdList, uniqueCode, title, content, opUserId)
	case 5:
		//图库
		chartSource := utils.CHART_SOURCE_DEFAULT
		err = AddChartInfoClassifyNoAuthRecordBySourceAndClassifyIdList(source, chartSource, classifyInfoList, noAuthUserIdList, uniqueCode, title, content, opUserId)

	case 6:
		// ETA表格
		err = AddExcelInfoClassifyNoAuthRecordBySourceAndClassifyIdList(source, subSource, classifyInfoList, noAuthUserIdList, uniqueCode, title, content, opUserId)

	default:
		err = errors.New("错误的source")
		return
	}

	return
}

// AddClassifyNoAuthRecordBySourceAndUserIdList
// @Description: 根据用户添加用户分类未授权记录
// @author: Roc
// @datetime 2024-04-07 20:12:44
// @param source int
// @param subSource int
// @param noAuthClassifyMap map[int]ClassifyDataItem
// @param configUserIdList []int
// @param uniqueCode string
// @param content string
// @param opUserId int
// @return err error
func AddClassifyNoAuthRecordBySourceAndUserIdList(source, subSource int, noAuthClassifyMap map[int]ClassifyDataItem, configUserIdList []int, uniqueCode, title, content string, opUserId int) (err error) {
	switch source {
	case 3, 4:
		edbClassifyType := 0
		if source == 4 {
			edbClassifyType = 1
		}
		err = AddEdbInfoClassifyNoAuthRecordBySourceAndUserIdList(source, edbClassifyType, noAuthClassifyMap, configUserIdList, uniqueCode, title, content, opUserId)
	case 5:
		//图库
		chartSource := utils.CHART_SOURCE_DEFAULT
		err = AddChartInfoClassifyNoAuthRecordBySourceAndUserIdList(source, chartSource, noAuthClassifyMap, configUserIdList, uniqueCode, title, content, opUserId)

	case 6:
		// ETA表格
		err = AddExcelInfoClassifyNoAuthRecordBySourceAndUserIdList(source, subSource, noAuthClassifyMap, configUserIdList, uniqueCode, title, content, opUserId)

	default:
		err = errors.New("错误的source")
		return
	}

	return
}

// DeleteClassifyNoAuthRecordBySourceAndClassifyIdList
// @Description: 根据来源和删除分类授权记录
// @author: Roc
// @datetime 2024-04-07 14:47:37
// @param source int
// @param subSource int
// @return err error
func DeleteClassifyNoAuthRecordBySourceAndClassifyIdList(source, subSource int) (err error) {
	switch source {
	case 3, 4:
		edbClassifyType := 0
		if source == 4 {
			edbClassifyType = 1
		}
		err = DeleteEdbInfoClassifyNoAuthRecordBySourceAndClassifyIdList(edbClassifyType)
	case 5:
		//图库
		chartSource := utils.CHART_SOURCE_DEFAULT
		err = DeleteChartInfoClassifyNoAuthRecordBySourceAndClassifyIdList(chartSource)

	case 6:
		// ETA表格
		err = DeleteExcelInfoClassifyNoAuthRecordBySourceAndClassifyIdList(subSource)

	default:
		err = errors.New("错误的source")
		return
	}

	return
}

// GetDataPermissionClassifyNoAuthRecordListByUserId
// @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 GetDataPermissionClassifyNoAuthRecordListByUserId(userId, source, subSource int32, startSize, pageSize int) (total int, items []*DataPermissionClassifyNoAuthRecord, err error) {
	switch source {
	case 3, 4:
		edbClassifyType := 0
		if source == 4 {
			edbClassifyType = 1
		}
		total, items, err = GetEdbInfoDataPermissionClassifyNoAuthRecordListByUserId(userId, edbClassifyType, startSize, pageSize)
	case 5:
		//图库
		chartSource := utils.CHART_SOURCE_DEFAULT
		total, items, err = GetChartInfoDataPermissionClassifyNoAuthRecordListByUserId(userId, chartSource, startSize, pageSize)

	case 6:
		// ETA表格
		total, items, err = GetExcelInfoDataPermissionClassifyNoAuthRecordListByUserId(userId, subSource, startSize, pageSize)

	default:
		err = errors.New("错误的source")
		return
	}

	return
}
