package data

import (
	"errors"
	"eta/eta_mobile/models/data_manage"
	"eta/eta_mobile/models/system"
	"eta/eta_mobile/services/data/data_manage_permission"
	"eta/eta_mobile/services/eta_forum"
	"eta/eta_mobile/utils"
	"fmt"
	"strconv"
	"strings"
	"time"
)

func chartClassifyHaveChild(allNode []*data_manage.ChartClassifyItems, node *data_manage.ChartClassifyItems) (childs []*data_manage.ChartClassifyItems, yes bool) {
	for _, v := range allNode {
		if v.ParentId == node.ChartClassifyId {
			childs = append(childs, v)
		}
	}
	if len(childs) > 0 {
		yes = true
	}
	return
}

func ChartClassifyItemsMakeTree(sysUser *system.Admin, allNode []*data_manage.ChartClassifyItems, node *data_manage.ChartClassifyItems, permissionClassifyIdList []int) {
	node.HaveOperaAuth = data_manage_permission.CheckEdbClassifyPermissionByPermissionIdList(node.IsJoinPermission, node.ChartClassifyId, permissionClassifyIdList)
	button := GetChartClassifyOpButton(sysUser, node.SysUserId, node.HaveOperaAuth)
	node.Button = button

	childs, _ := chartClassifyHaveChild(allNode, node) //判断节点是否有子节点并返回
	if len(childs) > 0 {
		for _, child := range childs {
			child.HaveOperaAuth = data_manage_permission.CheckEdbClassifyPermissionByPermissionIdList(child.IsJoinPermission, child.ChartClassifyId, permissionClassifyIdList)
			childButton := GetChartClassifyOpButton(sysUser, child.SysUserId, child.HaveOperaAuth)
			if child.Level == 3 {
				childButton.AddButton = false //第三级的话，默认图表都是没有添加按钮的
			}
			child.Button = childButton
			//node.Children = append(node.Children, child)
		}
		node.Children = append(node.Children, childs[0:]...) //添加子节点
		for _, v := range childs {
			v.HaveOperaAuth = data_manage_permission.CheckEdbClassifyPermissionByPermissionIdList(v.IsJoinPermission, v.ChartClassifyId, permissionClassifyIdList)
			//查询子节点的子节点，并添加到子节点
			_, has := chartClassifyHaveChild(allNode, v)
			if has {
				ChartClassifyItemsMakeTree(sysUser, allNode, v, permissionClassifyIdList) //递归添加节点
			} else {
				childrenArr := make([]*data_manage.ChartClassifyItems, 0)
				v.Children = childrenArr
			}
		}
	} else {
		childrenArr := make([]*data_manage.ChartClassifyItems, 0)
		node.Children = childrenArr
	}
}

func FixChartClassify() {
	//新增三级分类
	list, err := data_manage.GetChartClassifyByLevel(2, 1)
	if err != nil {
		return
	}

	for _, v := range list {
		classify := new(data_manage.ChartClassify)
		classify.ParentId = v.ChartClassifyId
		classify.ChartClassifyName = v.ChartClassifyName
		classify.HasData = 0
		classify.CreateTime = time.Now()
		classify.ModifyTime = time.Now()
		if utils.RunMode == "debug" {
			classify.SysUserId = 11
		} else {
			classify.SysUserId = 163
		}
		classify.SysUserRealName = "admin"
		classify.Level = 3
		timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
		classify.UniqueCode = utils.MD5(utils.DATA_PREFIX + "_" + timestamp)
		classify.Sort = v.Sort
		classify.Source = utils.CHART_SOURCE_DEFAULT

		id, err := data_manage.AddChartClassify(classify)
		if err != nil {
			return
		}

		err = data_manage.FIXChartClassifyId(int(id), v.ChartClassifyId)
		if err != nil {
			return
		}
	}
}

func FixChartClassifySysUserId() {
	//获取所有父级分类信息
	list, err := data_manage.GetChartClassifyByLevel(2, 1)
	if err != nil {
		return
	}

	for _, v := range list {
		err := data_manage.EditChartClassifySysUser(v.ChartClassifyId, v.SysUserId, v.SysUserRealName)
		if err != nil {
			return
		}
		fmt.Println("ChartClassifyId:", v.ChartClassifyId)
	}
	fmt.Println("FixChartClassifySysUserId end")
}

// GetChartClassifyOpButton 获取ETA图库分类的操作权限
func GetChartClassifyOpButton(sysUser *system.Admin, belongUserId int, haveOperaAuth bool) (button data_manage.ChartClassifyItemsButton) {
	// 没有数据权限就直接返回
	if !haveOperaAuth {
		return
	}

	//ficc管理员和超管和ficc研究员有权限创建和管理分类，可以编辑分类名称（分类名称不允许重复），可以拖动分类，改变分类顺序，可以拖动分类下模型，改变顺序，可以删除分类，若分类下有预测指标，则不允许删除；
	//if utils.InArrayByStr([]string{utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_RESEARCHR, utils.ROLE_TYPE_CODE_FICC_RESEARCHR}, sysUser.RoleTypeCode) {
	button.AddButton = true
	button.OpButton = true
	button.DeleteButton = true
	button.MoveButton = true
	//}

	return
}

// GetCanOpChartClassify 获取是否允许添加图表分类
func GetCanOpChartClassify(roleTypeCode string) (canOpClassify bool) {
	// 如果不是 超管 或者 ficc管理员 或者 ficc研究员，那么就没有权限
	if utils.InArrayByStr([]string{utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_RESEARCHR, utils.ROLE_TYPE_CODE_FICC_RESEARCHR}, roleTypeCode) {
		canOpClassify = true
	}

	return
}

// GetChartOpButton 获取ETA图库的操作权限
func GetChartOpButton(sysUser *system.Admin, belongUserId int, haveOperaAuth bool) (button data_manage.ChartClassifyItemsButton) {
	// 数据权限判断
	if !haveOperaAuth {
		return
	}
	//预测指标的添加人对该预测指标有全部操作权限，ficc管理员、超管对所有预测指标有全部操作权限；
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || sysUser.AdminId == belongUserId || sysUser.PredictEdbPermission == 1 {
		button.AddButton = true
		button.OpButton = true
		button.DeleteButton = true
		button.MoveButton = true
	}

	return
}

// HandleNoPermissionChart 图表列表返回，将没有权限的图表移除
func HandleNoPermissionChart(allNodes []*data_manage.ChartClassifyItems, noPermissionChartIdMap map[int]bool, sysUserId int) (newAllNodes []*data_manage.ChartClassifyItems) {
	// 涉及分类id
	classifyIdList := make([]int, 0)
	// 移除没有权限的图表
	newAllNodes = make([]*data_manage.ChartClassifyItems, 0)
	for _, node := range allNodes {
		// 二级分类
		tmpNodeInfo := *node
		tmpNodeList := make([]*data_manage.ChartClassifyItems, 0)

		if node.Children != nil {
			for _, chartInfo := range node.Children {
				// 如果指标不可见，那么就不返回该指标
				if _, ok := noPermissionChartIdMap[chartInfo.ChartInfoId]; ok {
					continue
				}
				tmpNodeList = append(tmpNodeList, chartInfo)
				classifyIdList = append(classifyIdList, chartInfo.ChartClassifyId)
			}
		}

		tmpNodeInfo.Children = tmpNodeList
		newAllNodes = append(newAllNodes, &tmpNodeInfo)
		classifyIdList = append(classifyIdList, node.ChartClassifyId)
	}

	// 数据权限
	if len(classifyIdList) > 0 {
		// 图表分类
		chartClassifyList, err := data_manage.GetChartClassifyByIdList(classifyIdList)
		if err != nil {
			return
		}

		chartClassifyMap := make(map[int]*data_manage.ChartClassify)
		for _, v := range chartClassifyList {
			chartClassifyMap[v.ChartClassifyId] = v
		}

		// 已授权分类id
		permissionChartIdList, permissionClassifyIdList, err := data_manage_permission.GetUserChartAndClassifyPermissionList(sysUserId, 0, 0)
		if err != nil {
			return
		}

		for _, node := range newAllNodes {
			if node.Children != nil {
				for _, chartInfo := range node.Children {
					if currClassify, ok := chartClassifyMap[chartInfo.ChartClassifyId]; ok {
						chartInfo.HaveOperaAuth = data_manage_permission.CheckChartPermissionByPermissionIdList(chartInfo.IsJoinPermission, currClassify.IsJoinPermission, chartInfo.ChartInfoId, chartInfo.ChartClassifyId, permissionChartIdList, permissionClassifyIdList)
					}
				}
			}

			if currClassify, ok := chartClassifyMap[node.ChartClassifyId]; ok {
				node.HaveOperaAuth = data_manage_permission.CheckChartPermissionByPermissionIdList(node.IsJoinPermission, currClassify.IsJoinPermission, node.ChartInfoId, node.ChartClassifyId, permissionChartIdList, permissionClassifyIdList)
			}

		}
	}

	return
}

// AddChartClassify
// @Description: 添加图表分类
// @author: Roc
// @datetime 2024-04-17 14:48:23
// @param chartClassifyName string
// @param parentId int
// @param level int
// @param source int
// @param lang string
// @param sysUser *system.Admin
// @return classifyInfo *data_manage.ChartClassify
// @return err error
// @return errMsg string
// @return isSendEmail bool
func AddChartClassify(chartClassifyName string, parentId, level, source int, lang string, sysUser *system.Admin) (classifyInfo *data_manage.ChartClassify, err error, errMsg string, isSendEmail bool) {
	isSendEmail = true
	errMsg = "保存分类失败"
	isSelected := 0
	// 校验分类名称相同的数量
	{
		var count int
		switch lang {
		case utils.EnLangVersion:
			count, err = data_manage.GetChartClassifyEnCount(chartClassifyName, parentId, source)
		default:
			count, err = data_manage.GetChartClassifyCount(chartClassifyName, parentId, source)
		}
		if err != nil {
			errMsg = "判断名称是否已存在失败"
			return
		}
		if count > 0 {
			errMsg = "分类名称已存在，请重新输入"
			err = errors.New(errMsg)
			isSendEmail = false
			return
		}
	}

	//获取该层级下最大的排序数
	maxSort, err := data_manage.GetChartClassifyMaxSort(parentId, source)
//查询顶级rootId
	rootId := 0
	levelPath := ""
	if parentId > 0 {
		parentClassify, tErr := data_manage.GetChartClassifyById(parentId)
		if tErr != nil {
			if tErr.Error() == utils.ErrNoRow() {
				errMsg = "父级分类不存在"
				err = errors.New(errMsg)
				return
			}
			errMsg = "获取失败"
			err = errors.New("获取分类信息失败，Err:" + tErr.Error())
			return
		}
		rootId = parentClassify.RootId
		levelPath = parentClassify.LevelPath
		isSelected = parentClassify.IsSelected
	}
	classifyInfo = new(data_manage.ChartClassify)
	classifyInfo.ParentId = parentId
	classifyInfo.ChartClassifyName = chartClassifyName
	classifyInfo.ChartClassifyNameEn = chartClassifyName
	classifyInfo.HasData = 0
	classifyInfo.CreateTime = time.Now()
	classifyInfo.ModifyTime = time.Now()
	classifyInfo.SysUserId = sysUser.AdminId
	classifyInfo.SysUserRealName = sysUser.RealName
	classifyInfo.Level = level + 1
	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	classifyInfo.UniqueCode = utils.MD5(utils.DATA_PREFIX + "_" + timestamp)
	classifyInfo.Sort = maxSort + 1
	classifyInfo.Source = source
	classifyInfo.RootId = rootId
	classifyInfo.IsSelected = isSelected
	newId, err := data_manage.AddChartClassify(classifyInfo)
	if err != nil {
		return
	}
	updateCols := make([]string, 0)
	if parentId == 0 { //一级目录的rootId等于自己本身
		classifyInfo.RootId = int(newId)
		updateCols = append(updateCols, "RootId")
	}
	if parentId > 0 {
		levelPath = fmt.Sprintf("%s%d,", levelPath, newId)
	} else {
		levelPath = fmt.Sprintf("%d,", newId)
	}
	updateCols = append(updateCols, "LevelPath")
	classifyInfo.LevelPath = levelPath
	classifyInfo.ChartClassifyId = int(newId)
	err = classifyInfo.Update(updateCols)
	if err != nil {
		errMsg = "更新分类失败"
		return
	}
	// 目前只有ETA图库需要继承分类权限
	if classifyInfo.Source == utils.CHART_SOURCE_DEFAULT {
		go data_manage_permission.InheritParentClassify(5, classifyInfo.Source, classifyInfo.ChartClassifyId, classifyInfo.ParentId, classifyInfo.ChartClassifyName)
		if isSelected == utils.ChartClassifyIsSelected { // 如果分类设置为精选资源，则需要同步到ETA资源库
			go eta_forum.ChartClassifySave(classifyInfo.ChartClassifyId)
		}
	}

	return
}

// EditChartClassify
// @Description: 修改图表分类
// @author: Roc
// @datetime 2024-04-17 14:59:37
// @param chartClassifyId int
// @param source int
// @param chartClassifyName string
// @param lang string
// @param sysUser *system.Admin
// @return classifyInfo *data_manage.ChartClassify
// @return err error
// @return errMsg string
// @return isSendEmail bool
func EditChartClassify(chartClassifyId, source int, chartClassifyName, lang string, sysUser *system.Admin) (classifyInfo *data_manage.ChartClassify, err error, errMsg string, isSendEmail bool) {
	isSendEmail = true
	errMsg = "保存失败"
	
	// 获取分类信息
	classifyInfo, err = data_manage.GetChartClassifyById(chartClassifyId)
	if err != nil {
		return
	}
	// 分类来源校验
	if classifyInfo.Source != source {
		errMsg = "图表分类异常"
		err = errors.New(fmt.Sprintf("图表分类来源异常，修改来源：%d,分类来源：%d", source, classifyInfo.Source))
		isSendEmail = false
		return
	}

	// 权限校验
	if classifyInfo.Source == utils.CHART_SOURCE_DEFAULT {
		// 已授权分类id
		permissionClassifyIdList, tmpErr := data_manage_permission.GetUserChartClassifyPermissionList(sysUser.AdminId, classifyInfo.ChartClassifyId)
		if tmpErr != nil {
			err = errors.New("获取已授权分类id数据失败，Err:" + err.Error())
			return
		}
		haveOperaAuth := data_manage_permission.CheckEdbClassifyPermissionByPermissionIdList(classifyInfo.IsJoinPermission, classifyInfo.ChartClassifyId, permissionClassifyIdList)

		// 权限校验
		{
			button := GetChartClassifyOpButton(sysUser, classifyInfo.SysUserId, haveOperaAuth)
			if !button.OpButton {
				errMsg = "无操作权限"
				err = errors.New(errMsg)
				isSendEmail = false
				return
			}
		}
	}

	// 需要变更的字段
	updateCols := make([]string, 0)

	// 语言版本校验
	switch lang {
	case utils.EnLangVersion:
		if classifyInfo.ChartClassifyNameEn != chartClassifyName {
			count, tmpErr := data_manage.GetChartClassifyEnCount(chartClassifyName, classifyInfo.ParentId, source)
			if tmpErr != nil {
				errMsg = "判断名称是否已存在失败"
				err = errors.New("判断名称是否已存在失败，Err:" + tmpErr.Error())
				return
			}
			if count > 0 {
				errMsg = "分类名称已存在，请重新输入"
				err = errors.New(errMsg)
				isSendEmail = false
				return
			}

			classifyInfo.ChartClassifyNameEn = chartClassifyName
			classifyInfo.ModifyTime = time.Now()
			updateCols = append(updateCols, "ChartClassifyNameEn", "ModifyTime")
		}
	default:
		if classifyInfo.ChartClassifyName != chartClassifyName {
			count, tmpErr := data_manage.GetChartClassifyCount(chartClassifyName, classifyInfo.ParentId, source)
			if tmpErr != nil {
				errMsg = "判断名称是否已存在失败"
				err = errors.New("判断名称是否已存在失败，Err:" + tmpErr.Error())
				return
			}
			if count > 0 {
				errMsg = "分类名称已存在，请重新输入"
				err = errors.New(errMsg)
				isSendEmail = false
				return
			}

			classifyInfo.ChartClassifyName = chartClassifyName
			classifyInfo.ModifyTime = time.Now()
			updateCols = append(updateCols, "ChartClassifyName", "ModifyTime")
		}
	}

	if len(updateCols) > 0 {
		err = classifyInfo.Update(updateCols)
	}

	return
}

// GetChartClassifyTreeRecursive 递归获取分类树形结构
func GetChartClassifyTreeRecursive(list []*data_manage.ChartClassifyItems, parentId int) []*data_manage.ChartClassifyItems {
	res := make([]*data_manage.ChartClassifyItems, 0)
	for _, v := range list {
		if v.ParentId == parentId {
			v.Children = GetChartClassifyTreeRecursive(list, v.ChartClassifyId)
			res = append(res, v)
		}
	}
	return res
}

// GetChartClassifyParentRecursive 根据子目录递归父级目录
func GetChartClassifyParentRecursive(list []*data_manage.ChartClassifyItems, classifyId int) []*data_manage.ChartClassifyItems {
	res := make([]*data_manage.ChartClassifyItems, 0)
	for _, v := range list {
		if v.ChartClassifyId == classifyId {
			if v.ParentId > 0 {
				res = GetChartClassifyParentRecursive(list, v.ParentId)
			}
			res = append(res, v)
		}
	}
	return res
}

// 新增处理子分类精选状态的函数
func UpdateChildClassifySelection(classifyInfo *data_manage.ChartClassify, parentClassifyInfo *data_manage.ChartClassify, oldSelected int) error {
	// 处理一级目录
	if classifyInfo.ParentId == 0 {
		if oldSelected != classifyInfo.IsSelected {
			return data_manage.UpdateChartClassifyIsSelected(
				classifyInfo.Source,
				classifyInfo.IsSelected,
				classifyInfo.LevelPath,
			)
		}
		return nil
	}else {
		// 处理二级及以上目录
		if classifyInfo.IsSelected != parentClassifyInfo.IsSelected {
			return data_manage.UpdateChartClassifyIsSelected(
				classifyInfo.Source,
				parentClassifyInfo.IsSelected,
				classifyInfo.LevelPath,
			)
		}
	}

	
	return nil
}

// 新增内部函数
func UpdateChartClassifyLevelPathWithChildren(chartClassifyInfo *data_manage.ChartClassify, parentChartClassifyInfo *data_manage.ChartClassify, oldParentId int, oldLevelPath string) error {
	levelPath := fmt.Sprintf("%s%d,", parentChartClassifyInfo.LevelPath, chartClassifyInfo.ChartClassifyId)
	chartClassifyInfo.LevelPath = levelPath
	if err := chartClassifyInfo.Update([]string{"LevelPath"}); err != nil {
		return fmt.Errorf("修改失败,Err:" + err.Error())
	}

	// 更新子分类的levelpath
	tmpList, err := data_manage.GetChartClassifyByLevelPath(oldLevelPath, chartClassifyInfo.Source)
	if err != nil {
		return fmt.Errorf("保存分类失败,Err:" + err.Error())
	}
    // 把原先的父级levePath，替换成最新的父级序列
	for _, tmp := range tmpList {
		after, _ := strings.CutPrefix(tmp.LevelPath, oldLevelPath)
		if after != "" {
			tmp.LevelPath = levelPath + after
			tmp.ModifyTime = time.Now()
			if e := tmp.Update([]string{"LevelPath", "ModifyTime"}); e != nil {
				return fmt.Errorf("修改子分类,Err:" + e.Error())
			}
		}
	}
	return nil
}