package data_manage_permission

import (
	"eta/eta_api/models/data_manage"
	"eta/eta_api/models/data_manage/data_manage_permission"
	"eta/eta_api/models/data_manage/excel"
	"eta/eta_api/models/system"
	"eta/eta_api/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/uuid"
	"strings"
)

// SetEdbChartPermission
// @Description:  单独给资产(指标、图表、ETA表格)设置权限
// @author: Roc
// @datetime 2024-03-27 10:52:32
// @param source int
// @param subSource int
// @param userId int
// @param authUserList []int
// @param isSelectAll bool
// @param dataId []string
// @param noDataId []string
// @param keyword string
// @param classify string
// @param opUserId int 操作人
// @return err error
// @return errMsg string
func SetEdbChartPermission(source, subSource, userId int, authUserList []int, isSelectAll bool, dataIdList, noDataIdList []string, keyword, classify string, opUserId int) (err error, errMsg string) {
	// 如果勾选全部数据,那么
	if isSelectAll {
		// 找出不要的指标ID列表
		noDataIdMap := make(map[string]string, 0)
		for _, v := range noDataIdList {
			noDataIdMap[v] = v
		}

		// 需要转义的指标/图表ID列表
		dataIdList = make([]string, 0)
		// 获取所有指标/图表
		list, _, tmpErr := GetMoveEdbChartList(source, subSource, userId, keyword, classify, 0, 100000)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		for _, v := range list {
			if _, ok := noDataIdMap[v.DataId]; !ok {
				dataIdList = append(dataIdList, v.DataId)
			}
		}
	}

	if len(authUserList) <= 0 {
		// 说明是取消权限管控
	}

	uniqueCode := uuid.NewUUID().Hex32()
	title := `数据权限变更`
	content := `数据权限`
	dataList := make([]data_manage_permission.DataItem, 0)

	switch source {
	case 3, 4:
		//ETA指标库、ETA预测指标
		if source == 3 {
			content += `(ETA指标库)`
		} else {
			content += `(ETA预测指标)`
		}

		tmpList, tmpErr := data_manage.GetEdbInfoListByEdbInfoId(dataIdList)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		dataIdList = make([]string, 0)
		if len(tmpList) > 0 {
			for _, v := range tmpList {
				dataList = append(dataList, data_manage_permission.DataItem{
					DataId:   v.EdbInfoId,
					DataCode: v.EdbCode,
					DataName: v.EdbName,
				})
				dataIdList = append(dataIdList, fmt.Sprint(v.EdbInfoId))
			}
			// 重新设置权限
			edbInfoType := 0
			if source == 4 {
				edbInfoType = 1
			}
			err = data_manage_permission.SetPermissionByEdbIdList(dataIdList, authUserList, edbInfoType)
		}

	case 5:
		//图库
		content += `(ETA图库)`
		tmpList, tmpErr := data_manage.GetChartInfoListByChartIdList(dataIdList)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		if len(tmpList) > 0 {
			dataIdList = make([]string, 0)
			for _, v := range tmpList {
				dataList = append(dataList, data_manage_permission.DataItem{
					DataId:   v.ChartInfoId,
					DataCode: fmt.Sprint(v.ChartInfoId),
					DataName: v.ChartName,
				})
				dataIdList = append(dataIdList, fmt.Sprint(v.ChartInfoId))
			}

			// 重新设置权限
			chartSource := utils.CHART_SOURCE_DEFAULT
			err = data_manage_permission.SetPermissionByChartIdList(dataIdList, authUserList, chartSource)
		}

	case 6:
		// ETA表格
		content += `(ETA表格)`
		tmpList := make([]*excel.MyExcelInfoList, 0)
		var tmpErr error
		if subSource == utils.BALANCE_TABLE {
			tmpList, tmpErr = excel.GetNoContentExcelListByExcelInfoIdAndParentId(dataIdList)
		} else {
			tmpList, tmpErr = excel.GetNoContentExcelListByExcelInfoIdList(dataIdList)
		}
		if tmpErr != nil {
			err = tmpErr
			return
		}
		if len(tmpList) > 0 {
			dataIdList = make([]string, 0)
			for _, v := range tmpList {
				dataList = append(dataList, data_manage_permission.DataItem{
					DataId:   v.ExcelInfoId,
					DataCode: fmt.Sprint(v.ExcelInfoId),
					DataName: v.ExcelName,
				})
				dataIdList = append(dataIdList, fmt.Sprint(v.ExcelInfoId))
			}

			// 重新设置权限
			err = data_manage_permission.SetPermissionByExcelIdList(dataIdList, authUserList, subSource)
		}
	default:
		return
	}

	if err != nil {
		return
	}

	var authRecordErr error
	defer func() {
		if authRecordErr != nil {
			utils.FileLog.Error(fmt.Sprintf("记录未设置记录资产权限的记录失败:%s;source:%d;sub_source:%d;数据ID列表:%s;授权人列表:%v", authRecordErr.Error(), source, subSource, strings.Join(dataIdList, ","), authUserList))

		}
	}()

	// 获取所有在用的用户
	cond := ` AND enabled = 1`
	pars := make([]interface{}, 0)

	adminList, authRecordErr := system.GetSysAdminList(cond, pars, []string{}, "")
	if authRecordErr != nil {
		return
	}

	// 如果没有授权人,那么就删除未授权记录
	if len(authUserList) < 0 {
		authRecordErr = data_manage_permission.DeleteRecordBySourceAndDataIdList(source, subSource, dataIdList)
		return
	}

	userIdMap := make(map[int]int)
	for _, tmpUserId := range authUserList {
		userIdMap[tmpUserId] = tmpUserId
	}

	noAuthUserIdList := make([]int, 0)
	for _, v := range adminList {
		if _, ok := userIdMap[v.AdminId]; !ok {
			noAuthUserIdList = append(noAuthUserIdList, v.AdminId)
		}
	}

	content += "已关闭"

	// 添加未授权记录
	authRecordErr = data_manage_permission.AddRecordBySourceAndDataIdList(source, subSource, dataList, noAuthUserIdList, authUserList, uniqueCode, title, content, opUserId)

	return
}

// SetDataClassifyIsPermission
// @Description:  设置资产(指标、图表、ETA表格)分类是否涉密
// @author: Roc
// @datetime 2024-03-27 10:52:32
// @param source int
// @param subSource int
// @param dataId []string
// @param opUserId int 操作人id
// @return err error
// @return errMsg string
func SetDataClassifyIsPermission(source, subSource int, classifyIdList []int, opUserId int) (err error, errMsg string) {
	uniqueCode := uuid.NewUUID().Hex32()
	title := `数据权限变更`
	content := `分类权限`
	classifyDataList := make([]data_manage_permission.ClassifyDataItem, 0)

	switch source {
	case 3, 4:
		//ETA指标库、ETA预测指标
		if source == 3 {
			content += `(ETA指标库)`
		} else {
			content += `(ETA预测指标)`
		}
		{
			// 分类信息
			classifyInfoList, tmpErr := data_manage.GetEdbClassifyByIdList(classifyIdList)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			for _, v := range classifyInfoList {
				classifyDataList = append(classifyDataList, data_manage_permission.ClassifyDataItem{
					ClassifyId:   v.ClassifyId,
					ClassifyName: v.ClassifyName,
				})
			}
		}

		// 重新设置权限
		classifyType := 0
		if source == 4 {
			classifyType = 1
		}
		err = data_manage_permission.SetIsPermissionEdbChartByEdbClassifyIdList(classifyIdList, classifyType)

	case 5:
		//图库
		content += `(ETA图库)`
		{
			// 分类信息
			classifyInfoList, tmpErr := data_manage.GetChartClassifyByIdList(classifyIdList)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			for _, v := range classifyInfoList {
				classifyDataList = append(classifyDataList, data_manage_permission.ClassifyDataItem{
					ClassifyId:   v.ChartClassifyId,
					ClassifyName: v.ChartClassifyName,
				})
			}
		}

		// 重新设置权限
		chartClassifySource := utils.CHART_SOURCE_DEFAULT
		err = data_manage_permission.SetIsPermissionByChartClassifyIdList(classifyIdList, chartClassifySource)

	case 6:
		// ETA表格
		content += `(ETA表格)`
		{
			// 分类信息
			classifyInfoList, tmpErr := excel.GetExcelClassifyByIdList(classifyIdList)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			for _, v := range classifyInfoList {
				classifyDataList = append(classifyDataList, data_manage_permission.ClassifyDataItem{
					ClassifyId:   v.ExcelClassifyId,
					ClassifyName: v.ExcelClassifyName,
				})
			}
		}
		// 重新设置权限
		err = data_manage_permission.SetIsPermissionByExcelClassifyIdList(classifyIdList, subSource)

	default:
		return
	}
	if err != nil {
		return
	}

	var authRecordErr error
	defer func() {
		if authRecordErr != nil {
			utils.FileLog.Error(fmt.Sprintf("记录未设置记录资产权限的记录失败:%s;source:%d;sub_source:%d;分类ID列表:%v", authRecordErr.Error(), source, subSource, classifyIdList))

		}
	}()

	// 如果没有涉密的分类,那么就移除所有删除未授权记录
	if len(classifyIdList) <= 0 {
		authRecordErr = data_manage_permission.DeleteClassifyNoAuthRecordBySourceAndClassifyIdList(source, subSource)
		return
	}

	// 获取所有在用的用户
	cond := ` AND enabled = 1`
	pars := make([]interface{}, 0)

	adminList, authRecordErr := system.GetSysAdminList(cond, pars, []string{}, "")
	if authRecordErr != nil {
		return
	}
	noAuthUserIdList := make([]int, 0)
	for _, v := range adminList {
		noAuthUserIdList = append(noAuthUserIdList, v.AdminId)
	}

	content += "已关闭"
	// 添加未授权记录
	authRecordErr = data_manage_permission.AddClassifyNoAuthRecordBySourceAndClassifyIdList(source, subSource, classifyDataList, noAuthUserIdList, uniqueCode, title, content, opUserId)

	return
}

// SetEdbChartClassifyPermission
// @Description: 给用户设置涉密分类的权限
// @author: Roc
// @datetime 2024-03-28 14:22:30
// @param source int
// @param subSource int
// @param authUserList []int
// @param classifyIdList []int
// @param opUserId int 操作人id
// @return err error
// @return errMsg string
func SetEdbChartClassifyPermission(source, subSource int, authUserList []int, classifyIdList []int, opUserId int) (err error, errMsg string) {
	uniqueCode := uuid.NewUUID().Hex32()
	title := `数据权限变更`
	content := `分类权限`
	secretClassifyInfoList := make([]data_manage_permission.ClassifyDataItem, 0)

	if len(classifyIdList) <= 0 {
		// 说明是取消权限管控
	}

	// 先获取所有的涉密分类,然后根据用户去判断那些分类给权限了

	switch source {
	case 3, 4: //ETA指标库、ETA预测指标

		//ETA指标库、ETA预测指标
		if source == 3 {
			content += `(ETA指标库)`
		} else {
			content += `(ETA预测指标)`
		}

		classifyType := 0
		if source == 4 {
			classifyType = 1
		}

		{
			// 获取已经设置加密的分类信息
			classifyInfoList, tmpErr := data_manage.GetEdbClassifyByClassifyTypeAndIsJoinPermission(classifyType, 1)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			for _, v := range classifyInfoList {
				secretClassifyInfoList = append(secretClassifyInfoList, data_manage_permission.ClassifyDataItem{
					ClassifyId:   v.ClassifyId,
					ClassifyName: v.ClassifyName,
				})
			}
		}
		// 重新设置权限
		err = data_manage_permission.SetPermissionByEdbClassifyIdList(classifyIdList, authUserList, classifyType)
	case 5:
		subSource = utils.CHART_SOURCE_DEFAULT
		//图库
		content += `(ETA图库)`
		{
			// 分类信息
			classifyInfoList, tmpErr := data_manage.GetChartClassifyBySourceAndIsJoinPermission(subSource, 1)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			for _, v := range classifyInfoList {
				secretClassifyInfoList = append(secretClassifyInfoList, data_manage_permission.ClassifyDataItem{
					ClassifyId:   v.ChartClassifyId,
					ClassifyName: v.ChartClassifyName,
				})
			}
		}

		// 重新设置权限
		err = data_manage_permission.SetPermissionByChartClassifyIdList(classifyIdList, authUserList, subSource)
	case 6:
		// ETA表格
		content += `(ETA表格)`
		{
			// 分类信息
			classifyInfoList, tmpErr := excel.GetExcelClassifyBySourceAndIsJoinPermission(subSource, 1)
			if tmpErr != nil {
				err = tmpErr
				return
			}
			for _, v := range classifyInfoList {
				secretClassifyInfoList = append(secretClassifyInfoList, data_manage_permission.ClassifyDataItem{
					ClassifyId:   v.ExcelClassifyId,
					ClassifyName: v.ExcelClassifyName,
				})
			}
		}

		err = data_manage_permission.SetPermissionByExcelClassifyIdList(classifyIdList, authUserList, subSource)
	default:
		return
	}

	if err != nil {
		return
	}

	var authRecordErr error
	defer func() {
		if authRecordErr != nil {
			utils.FileLog.Error(fmt.Sprintf("记录未设置记录资产权限的记录失败:%s;source:%d;sub_source:%d;分类ID列表:%v", authRecordErr.Error(), source, subSource, classifyIdList))

		}
	}()

	content += "已关闭"

	authClassifyIdMap := make(map[int]int)
	for _, v := range classifyIdList {
		authClassifyIdMap[v] = v
	}

	noAuthClassifyMap := make(map[int]data_manage_permission.ClassifyDataItem)
	for _, classifyInfo := range secretClassifyInfoList {
		if _, ok := authClassifyIdMap[classifyInfo.ClassifyId]; !ok {
			noAuthClassifyMap[classifyInfo.ClassifyId] = classifyInfo
		}
	}

	// 添加未授权记录
	authRecordErr = data_manage_permission.AddClassifyNoAuthRecordBySourceAndUserIdList(source, subSource, noAuthClassifyMap, authUserList, uniqueCode, title, content, opUserId)

	return
}

// GetEdbChartClassifyIdListPermissionByUserId
// @Description: 根据用户id获取已经配置的分类id列表
// @author: Roc
// @datetime 2024-03-29 16:26:10
// @param source int
// @param subSource int
// @param userId int
// @return idList []int
// @return err error
func GetEdbChartClassifyIdListPermissionByUserId(source, subSource, userId int) (idList []int, err error) {
	switch source {
	case 3, 4: //ETA指标库、ETA预测指标
		//tmpList, tmpErr := data_manage.GetEdbInfoListGroupByUserId(dataId)
		//if tmpErr != nil {
		//	err = tmpErr
		//	return
		//}
		//if len(tmpList) > 0 {
		//}
		// 重新设置权限
		classifyType := 0
		if source == 4 {
			classifyType = 1
		}
		idList, err = data_manage_permission.GetPermissionEdbClassifyIdListByUserId(userId, classifyType)
	case 5:
		//图库
		chartClassifySource := utils.CHART_SOURCE_DEFAULT
		idList, err = data_manage_permission.GetPermissionChartClassifyIdListByUserId(userId, chartClassifySource)
	case 6:
		// ETA表格
		idList, err = data_manage_permission.GetPermissionExcelClassifyIdListByUserId(userId, subSource)
	default:
		return
	}
	return
}

// GetUserIdListPermissionByDataId
// @Description: 根据资产(指标、图表、表格)id获取已经配置的用户id
// @author: Roc
// @datetime 2024-03-29 16:26:10
// @param source int
// @param subSource int
// @param dataId int
// @return idList []int
// @return err error
func GetUserIdListPermissionByDataId(source, subSource, dataId int) (idList []int, err error) {
	switch source {
	case 3, 4:
		// ETA指标库、ETA预测指标
		edbInfoType := 0
		if source == 4 {
			edbInfoType = 1
		}
		idList, err = data_manage_permission.GetPermissionUserIdListByEdbId(dataId, edbInfoType)
	case 5:
		// 图库
		chartClassifySource := utils.CHART_SOURCE_DEFAULT
		idList, err = data_manage_permission.GetPermissionUserIdListByChartId(dataId, chartClassifySource)
	case 6:
		// ETA表格
		idList, err = data_manage_permission.GetPermissionUserIdListByExcelId(dataId, subSource)
	default:
		return
	}
	return
}

// GetUserIdListNoPermissionByDataId
// @Description: 根据资产(指标、图表、表格)id获取没有该资产分类权限的用户id
// @author: Roc
// @datetime 2024-03-29 16:26:10
// @param source int
// @param subSource int
// @param dataId int
// @return idList []int
// @return err error
func GetUserIdListNoPermissionByDataId(source, subSource, dataId int) (idList []int, err error) {
	// 已经授权的用户map
	authIdList := make([]int, 0)

	switch source {
	case 3, 4:
		// ETA指标库、ETA预测指标
		edbInfoType := 0
		if source == 4 {
			edbInfoType = 1
		}

		// 获取指标
		edbInfoItem, tmpErr := data_manage.GetEdbInfoById(dataId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 获取分类
		classifyItem, tmpErr := data_manage.GetEdbClassifyById(edbInfoItem.ClassifyId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 判断分类是否涉密,不涉密就直接返回
		if classifyItem.IsJoinPermission == 0 {
			return
		}

		// 获取已经配置分类权限的用户ID列表
		authIdList, err = data_manage_permission.GetPermissionUserIdListByEdbClassifyId(dataId, edbInfoType)
	case 5:
		// 图库

		// 获取图表
		chartInfoItem, tmpErr := data_manage.GetChartInfoById(dataId)
		if tmpErr != nil {
			err = tmpErr
			return
		}

		// 获取分类
		classifyItem, tmpErr := data_manage.GetChartClassifyById(chartInfoItem.ChartClassifyId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 判断分类是否涉密,不涉密就直接返回
		if classifyItem.IsJoinPermission == 0 {
			return
		}

		chartClassifySource := utils.CHART_SOURCE_DEFAULT
		authIdList, err = data_manage_permission.GetPermissionUserIdListByChartClassifyId(dataId, chartClassifySource)
	case 6:
		// ETA表格

		// 获取图表
		excelInfoItem, tmpErr := excel.GetNoContentExcelInfoByExcelId(dataId)
		if tmpErr != nil {
			err = tmpErr
			return
		}

		// 获取分类
		classifyItem, tmpErr := excel.GetExcelClassifyById(excelInfoItem.ExcelClassifyId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 判断分类是否涉密,不涉密就直接返回
		if classifyItem.IsJoinPermission == 0 {
			return
		}

		authIdList, err = data_manage_permission.GetPermissionUserIdListByExcelClassifyId(dataId, subSource)
	default:
		return
	}

	// 已经授权的用户map
	authUserIdMap := make(map[int]int)
	for _, v := range authIdList {
		authUserIdMap[v] = v
	}

	// 获取所有在用的用户
	cond := ` AND enabled = 1`
	pars := make([]interface{}, 0)

	adminList, authRecordErr := system.GetSysAdminList(cond, pars, []string{}, "")
	if authRecordErr != nil {
		return
	}

	for _, v := range adminList {
		if _, ok := authUserIdMap[v.AdminId]; !ok {
			idList = append(idList, v.AdminId)
		}
	}

	return
}

// InheritParentClassify
// @Description: 继承父级分类的涉密权限
// @author: Roc
// @datetime 2024-04-07 21:09:16
// @param source int
// @param subSource int
// @param classifyId int
// @param parentClassifyId int
// @param classifyName string
func InheritParentClassify(source, subSource, classifyId, parentClassifyId int, classifyName string) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(fmt.Sprintf("继承父级分类失败:%s;source:%d;sub_source:%d;分类ID列表:%v", err.Error(), source, subSource, classifyId))
			utils.FileLog.Error(fmt.Sprintf("继承父级分类失败:%s;source:%d;sub_source:%d;分类ID列表:%v", err.Error(), source, subSource, classifyId))
		}
	}()

	// 一级分类不用继承
	if parentClassifyId <= 0 {
		return
	}
	uniqueCode := uuid.NewUUID().Hex32()
	switch source {
	case 3, 4:
		//ETA指标库、ETA预测指标
		// 分类信息
		parentClassifyInfo, tmpErr := data_manage.GetEdbClassifyById(parentClassifyId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 没有标记涉密那么就忽略
		if parentClassifyInfo.IsJoinPermission == 0 {
			return
		}

		// 重新设置权限
		classifyType := 0
		if source == 4 {
			classifyType = 1
		}

		err = data_manage_permission.InheritParentClassifyByEdbClassifyId(source, classifyType, classifyId, parentClassifyId, classifyName, uniqueCode)

	case 5:
		//图库
		// 分类信息
		parentClassifyInfo, tmpErr := data_manage.GetChartClassifyById(parentClassifyId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 没有标记涉密那么就忽略
		if parentClassifyInfo.IsJoinPermission == 0 {
			return
		}

		// 重新设置权限
		chartClassifySource := utils.CHART_SOURCE_DEFAULT
		err = data_manage_permission.InheritParentClassifyByChartClassifyId(source, chartClassifySource, classifyId, parentClassifyId, classifyName, uniqueCode)

	case 6:
		// ETA表格

		// 分类信息
		parentClassifyInfo, tmpErr := excel.GetExcelClassifyById(parentClassifyId)
		if tmpErr != nil {
			err = tmpErr
			return
		}
		// 没有标记涉密那么就忽略
		if parentClassifyInfo.IsJoinPermission == 0 {
			return
		}

		// 重新设置权限
		err = data_manage_permission.InheritParentClassifyByExcelClassifyId(source, subSource, classifyId, parentClassifyId, classifyName, uniqueCode)

	default:
		return
	}
}