package data

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/data_manage"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/utils"
	"strconv"
	"time"
)

func EdbClassifyListMakeTree(allNode []*data_manage.EdbClassifyItems, node *data_manage.EdbClassifyItems) {
	childs, _ := edbClassifyHaveChild(allNode, node) //判断节点是否有子节点并返回
	allEdbInfo, _ := GetEdbClassifyEdbInfo()
	if len(childs) > 0 {
		node.Children = append(node.Children, childs[0:]...) //添加子节点
		for _, v := range childs {                           //查询子节点的子节点，并添加到子节点
			_, has := edbClassifyHaveChild(allNode, v)
			if has {
				EdbClassifyListMakeTree(allNode, v) //递归添加节点
			} else {
				edbInfoList := allEdbInfo[v.ClassifyId]
				v.Children = edbInfoList
				if v.Children == nil {
					childrenArr := make([]*data_manage.EdbClassifyItems, 0)
					v.Children = childrenArr
				}
			}
		}
	} else {
		childrenArr := make([]*data_manage.EdbClassifyItems, 0)
		node.Children = childrenArr
	}
}

func edbClassifyHaveChild(allNode []*data_manage.EdbClassifyItems, node *data_manage.EdbClassifyItems) (childs []*data_manage.EdbClassifyItems, yes bool) {
	for _, v := range allNode {
		if v.ParentId == node.ClassifyId {
			childs = append(childs, v)
		}
	}

	if len(childs) > 0 {
		yes = true
	}
	return
}

func GetEdbClassifyEdbInfo() (result map[int][]*data_manage.EdbClassifyItems, err error) {
	cMap := make(map[int][]*data_manage.EdbClassifyItems)
	items, err := data_manage.GetEdbInfoAll(0)
	if err != nil {
		return
	}
	for _, v := range items {
		childrenArr := make([]*data_manage.EdbClassifyItems, 0)
		v.Children = childrenArr
		if items, ok := cMap[v.ClassifyId]; ok {
			items = append(items, v)
			cMap[v.ClassifyId] = items
		} else {
			infoList := make([]*data_manage.EdbClassifyItems, 0)
			infoList = append(infoList, v)
			cMap[v.ClassifyId] = infoList
		}
	}
	result = cMap
	return
}

func EdbClassifyItemsMakeTree(allNode []*data_manage.EdbClassifyItems, node *data_manage.EdbClassifyItems) {
	childs, _ := edbClassifyHaveChild(allNode, node) //判断节点是否有子节点并返回
	if len(childs) > 0 {
		node.Children = append(node.Children, childs[0:]...) //添加子节点
		for _, v := range childs {                           //查询子节点的子节点，并添加到子节点
			_, has := edbClassifyHaveChild(allNode, v)
			if has {
				EdbClassifyItemsMakeTree(allNode, v) //递归添加节点
			} else {
				childrenArr := make([]*data_manage.EdbClassifyItems, 0)
				v.Children = childrenArr
			}
		}
	} else {
		childrenArr := make([]*data_manage.EdbClassifyItems, 0)
		node.Children = childrenArr
	}
}

// GetEdbClassifyListByAdminId 根据账户类型获取分类id集合
func GetEdbClassifyListByAdminId(adminId int64) (classifyIdList []string, err error) {
	list, err := models.GetEdbdataClassify(adminId)
	if err != nil {
		return
	}
	for _, parent := range list {
		if parent.Child != nil {
			for _, classify := range parent.Child {
				classifyIdList = append(classifyIdList, fmt.Sprint(classify.ClassifyId))
			}
		}
	}
	return
}

// GetEdbClassifyNameListByAdminId 根据账户类型获取分类名称集合
func GetEdbClassifyNameListByAdminId(adminId int64) (classifyNameList []string, edbDataClassifyMap map[string]*models.EdbdataClassify, err error) {
	list, err := models.GetEdbdataClassify(adminId)
	edbDataClassifyMap = make(map[string]*models.EdbdataClassify)
	if err != nil {
		return
	}
	for _, parent := range list {
		if parent.Child != nil {
			for _, classify := range parent.Child {
				classifyNameList = append(classifyNameList, classify.ClassifyName)
				edbDataClassifyMap[classify.ClassifyName] = classify
			}
		}
	}
	return
}

// AddEdbClassify 添加指标分类
func AddEdbClassify(classifyName string, parentId, level int, classifyType uint8, sysUserId int, sysUserName string) (classifyInfo *data_manage.EdbClassify, err error, errMsg string) {
	count, err := data_manage.GetEdbClassifyCount(classifyName, parentId, classifyType)
	if err != nil {
		errMsg = `判断名称是否已存在失败`
		return
	}
	if count > 0 {
		errMsg = `分类名称已存在，请重新输入`
		return
	}
	//获取该层级下最大的排序数
	maxSort, err := data_manage.GetEdbClassifyMaxSort(parentId, classifyType)

	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	classifyInfo = &data_manage.EdbClassify{
		//ClassifyId:      0,
		ClassifyType:    classifyType,
		ClassifyName:    classifyName,
		ParentId:        parentId,
		HasData:         0,
		CreateTime:      time.Now(),
		ModifyTime:      time.Now(),
		SysUserId:       sysUserId,
		SysUserRealName: sysUserName,
		Level:           level + 1,
		UniqueCode:      utils.MD5(utils.DATA_PREFIX + "_" + timestamp),
		Sort:            maxSort,
	}
	_, err = data_manage.AddEdbClassify(classifyInfo)
	if err != nil {
		errMsg = "保存分类失败"
	}
	return
}

// EditEdbClassify 编辑指标分类
func EditEdbClassify(classifyId int, classifyName string) (err error, errMsg string) {
	item, err := data_manage.GetEdbClassifyById(classifyId)
	if err != nil {
		errMsg = `保存失败`
		return
	}
	// 名字相同，那么就直接返回
	if item.ClassifyName == classifyName {
		return
	}

	// 判断名称是否已存在
	count, err := data_manage.GetEdbClassifyCount(classifyName, item.ParentId, item.ClassifyType)
	if err != nil {
		errMsg = "判断名称是否已存在失败"
		return
	}
	if count > 0 {
		errMsg = "分类名称已存在，请重新输入"
		return
	}

	// 修改数据
	err = data_manage.EditEdbClassify(classifyId, classifyName)
	if err != nil {
		errMsg = "保存失败"
	}
	return
}

// DeleteCheck 删除检测
func DeleteCheck(classifyId, edbInfoId int) (deleteStatus int, tipsMsg string, err error, errMsg string) {
	//删除分类
	if classifyId > 0 && edbInfoId == 0 {
		//判断分类下，是否含有指标
		count, tmpErr := data_manage.GetEdbInfoCountByClassifyId(classifyId)
		if tmpErr != nil {
			errMsg = "删除失败"
			err = errors.New("分类下是否含有指标失败，Err:" + tmpErr.Error())
			return
		}

		if count > 0 {
			deleteStatus = 1
			tipsMsg = "若目录关联指标不可删除"
		}
	}

	if deleteStatus != 1 && edbInfoId == 0 {
		classifyCount, tmpErr := data_manage.GetClassifyCountByClassifyId(classifyId)
		if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
			errMsg = "删除失败"
			err = errors.New("分类下是否含有指标失败，Err:" + tmpErr.Error())
			return
		}
		if classifyCount > 0 {
			deleteStatus = 2
			tipsMsg = "确认删除当前目录及包含的子目录吗"
		}
	}

	//删除指标
	if edbInfoId > 0 {
		//判断指标是否用于作图，如果用于作图，则不可删除
		chartCount, tmpErr := data_manage.GetChartEdbMappingCount(edbInfoId)
		if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
			errMsg = "删除失败"
			err = errors.New("判断指标是否被用于作图失败，Err:" + tmpErr.Error())
			return
		}
		if chartCount > 0 {
			deleteStatus = 3
			tipsMsg = "当前指标已用作画图，不可删除"
		}
		//判断指标是否用于计算
		{
			calculateCount, tmpErr := data_manage.GetEdbInfoCalculateMappingCount(edbInfoId)
			if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
				errMsg = "删除失败"
				err = errors.New("判断指标是否被用于计算失败，GetEdbInfoCalculateCount Err:" + tmpErr.Error())
				return
			}
			if calculateCount > 0 {
				deleteStatus = 4
				tipsMsg = "当前指标已用作，指标运算，不可删除"
			}
		}
	}
	return
}

// Delete 删除分类/指标
func Delete(classifyId, edbInfoId, sysUserId int, sysUserName string, requestBody, requestUrl string) (nextItem *data_manage.EdbInfo, err error, errMsg string) {
	//删除分类
	if classifyId > 0 && edbInfoId == 0 {
		//判断是否含有指标
		count, tmpErr := data_manage.GetEdbInfoCountByClassifyId(classifyId)
		if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
			errMsg = "删除失败"
			err = errors.New("分类下是否含有指标失败，Err:" + tmpErr.Error())
			return
		}

		if count > 0 {
			errMsg = "该目录下存在关联指标，不可删除"
			return
		}

		tmpErr = data_manage.DeleteEdbClassify(classifyId)
		if tmpErr != nil {
			errMsg = "删除失败"
			err = errors.New("删除失败,Err:" + tmpErr.Error())
			return
		}
	}

	//删除指标
	if edbInfoId > 0 {
		edbInfo, tmpErr := data_manage.GetEdbInfoById(edbInfoId)
		if tmpErr != nil {
			if tmpErr.Error() == utils.ErrNoRow() {
				errMsg = "指标已删除，请刷新页面"
				err = errors.New("指标不存在，Err:" + tmpErr.Error())
				return
			} else {
				errMsg = "删除失败"
				err = errors.New("删除失败，获取指标信息失败，Err:" + tmpErr.Error())
				return
			}
		}
		if edbInfo == nil {
			errMsg = "指标已删除，请刷新页面"
			return
		}

		//判断指标是否用于作图，如果用于作图，则不可删除
		chartCount, tmpErr := data_manage.GetChartEdbMappingCount(edbInfoId)
		if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
			errMsg = "删除失败"
			err = errors.New("判断指标是否被用于作图失败，Err:" + tmpErr.Error())
			return
		}
		if chartCount > 0 {
			errMsg = "当前指标已用作画图，不可删除"
			return
		}

		//如果是普通指标，那么还需要判断是否被预测指标作为源指标
		if edbInfo.EdbInfoType == 0 {
			predictEdbInfoCount, tmpErr := data_manage.GetPredictEdbConfCount(edbInfoId)
			if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
				errMsg = "删除失败"
				err = errors.New("判断指标是否被用于预测指标失败，Err:" + tmpErr.Error())
				return
			}
			if predictEdbInfoCount > 0 {
				errMsg = "当前指标已用作预测指标，不可删除"
				return
			}
		}

		//判断指标是否用作其他指标的计算
		{
			calculateCount, tmpErr := data_manage.GetEdbInfoCalculateMappingCount(edbInfoId)
			if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
				errMsg = "删除失败"
				err = errors.New("判断指标是否被用于计算失败，GetEdbInfoCalculateCount Err:" + tmpErr.Error())
				return
			}
			if calculateCount > 0 {
				errMsg = "当前指标已用作，指标运算，不可删除"
				return
			}
		}

		//真实删除
		tmpErr = data_manage.DeleteEdbInfoAndData(edbInfo.EdbInfoId, edbInfo.Source)
		if tmpErr != nil {
			errMsg = "删除失败"
			err = errors.New("删除失败，Err:" + tmpErr.Error())
			return
		}

		// 返回下一个表格的信息
		{
			var condition string
			var pars []interface{}
			condition += " AND edb_info_type=? AND classify_id=? "
			pars = append(pars, edbInfo.EdbInfoType, edbInfo.ClassifyId)

			condition += " AND (sort>? OR (sort=? AND edb_info_id<?) ) "
			pars = append(pars, edbInfo.Sort, edbInfo.Sort, edbInfo.EdbInfoId)
			nextItem, tmpErr = data_manage.GetNextEdbInfoByCondition(condition, pars)
			if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
				errMsg = "删除失败"
				err = errors.New("获取下一级预测指标信息失败，Err:" + tmpErr.Error())
				return
			}

			// 如果没找到，那么查找下一个分类的第一个表格
			if nextItem == nil {
				currClassifyInfo, tmpErr := data_manage.GetEdbClassifyById(edbInfo.ClassifyId)
				if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
					errMsg = "删除失败"
					err = errors.New("获取当前预测指标分类信息失败，Err:" + tmpErr.Error())
					return
				}

				nextItem, err = data_manage.GetNextEdbInfo(edbInfo.ClassifyId, currClassifyInfo.Sort, int(currClassifyInfo.ClassifyType), edbInfo.EdbInfoType)
				if err != nil && err.Error() != utils.ErrNoRow() {
					errMsg = "删除失败"
					err = errors.New("获取下一级预测指标信息失败，Err:" + tmpErr.Error())
					return
				}
			}
		}

		//新增操作日志
		{
			edbLog := new(data_manage.EdbInfoLog)
			edbLog.EdbInfoId = edbInfo.EdbInfoId
			edbLog.SourceName = edbInfo.SourceName
			edbLog.Source = edbInfo.Source
			edbLog.EdbCode = edbInfo.EdbCode
			edbLog.EdbName = edbInfo.EdbName
			edbLog.ClassifyId = edbInfo.ClassifyId
			edbLog.SysUserId = sysUserId
			edbLog.SysUserRealName = sysUserName
			edbLog.CreateTime = time.Now()
			edbLog.Content = requestBody
			edbLog.Status = "删除指标"
			edbLog.Method = requestUrl
			go data_manage.AddEdbInfoLog(edbLog)
		}

		// 删除es中的数据
		DeleteEdbInfoToEs(edbInfoId)
	}
	return
}

// MoveEdbClassify 移动指标分类
func MoveEdbClassify(classifyId, parentClassifyId, prevClassifyId, nextClassifyId int) (err error, errMsg string) {
	//判断分类是否存在
	edbClassifyInfo, err := data_manage.GetEdbClassifyById(classifyId)
	if err != nil {
		errMsg = "移动失败"
		err = errors.New("获取分类信息失败,Err:" + err.Error())
		return
	}
	updateCol := make([]string, 0)

	//判断上级id是否一致，如果不一致的话，那么需要移动该分类层级
	if edbClassifyInfo.ParentId != parentClassifyId && parentClassifyId != 0 {
		parentEdbClassifyInfo, tmpErr := data_manage.GetEdbClassifyById(parentClassifyId)
		if tmpErr != nil {
			errMsg = "移动失败"
			err = errors.New("获取上级分类信息失败,Err:" + tmpErr.Error())
			return
		}
		edbClassifyInfo.ParentId = parentEdbClassifyInfo.ClassifyId
		edbClassifyInfo.Level = parentEdbClassifyInfo.Level + 1
		edbClassifyInfo.ModifyTime = time.Now()
		updateCol = append(updateCol, "ParentId", "Level", "ModifyTime")
	}

	//如果有传入 上一个兄弟节点分类id
	if prevClassifyId > 0 {
		prevClassify, tmpErr := data_manage.GetEdbClassifyById(prevClassifyId)
		if tmpErr != nil {
			errMsg = "移动失败"
			err = errors.New("获取上一个兄弟节点分类信息失败,Err:" + tmpErr.Error())
			return
		}

		//如果是移动在两个兄弟节点之间
		if nextClassifyId > 0 {
			//下一个兄弟节点
			nextClassify, tmpErr := data_manage.GetEdbClassifyById(nextClassifyId)
			if tmpErr != nil {
				errMsg = "移动失败"
				err = errors.New("获取下一个兄弟节点分类信息失败,Err:" + tmpErr.Error())
				return
			}
			//如果上一个兄弟与下一个兄弟的排序权重是一致的，那么需要将下一个兄弟（以及下个兄弟的同样排序权重）的排序权重+2，自己变成上一个兄弟的排序权重+1
			if prevClassify.Sort == nextClassify.Sort || prevClassify.Sort == edbClassifyInfo.Sort {
				//变更兄弟节点的排序
				updateSortStr := `sort + 2`
				_ = data_manage.UpdateEdbClassifySortByParentId(prevClassify.ParentId, prevClassify.ClassifyId, prevClassify.Sort, updateSortStr, edbClassifyInfo.ClassifyType)
			} else {
				//如果下一个兄弟的排序权重正好是上个兄弟节点的下一层，那么需要再加一层了
				if nextClassify.Sort-prevClassify.Sort == 1 {
					//变更兄弟节点的排序
					updateSortStr := `sort + 1`
					_ = data_manage.UpdateEdbClassifySortByParentId(prevClassify.ParentId, 0, prevClassify.Sort, updateSortStr, edbClassifyInfo.ClassifyType)
				}
			}
		}

		edbClassifyInfo.Sort = prevClassify.Sort + 1
		edbClassifyInfo.ModifyTime = time.Now()
		updateCol = append(updateCol, "Sort", "ModifyTime")
	} else {
		firstClassify, tmpErr := data_manage.GetFirstEdbClassifyByParentId(edbClassifyInfo.ParentId)
		if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
			errMsg = "移动失败"
			err = errors.New("获取获取当前父级分类下的排序第一条的分类信息失败,Err:" + tmpErr.Error())
			return
		}

		//如果该分类下存在其他分类，且第一个其他分类的排序等于0，那么需要调整排序
		if firstClassify != nil && firstClassify.Sort == 0 {
			updateSortStr := ` sort + 1 `
			_ = data_manage.UpdateEdbClassifySortByParentId(firstClassify.ParentId, firstClassify.ClassifyId-1, 0, updateSortStr, edbClassifyInfo.ClassifyType)
		}

		edbClassifyInfo.Sort = 0 //那就是排在第一位
		edbClassifyInfo.ModifyTime = time.Now()
		updateCol = append(updateCol, "Sort", "ModifyTime")
	}

	//更新
	if len(updateCol) > 0 {
		err = edbClassifyInfo.Update(updateCol)
		if err != nil {
			errMsg = "移动失败"
			err = errors.New("修改失败,Err:" + err.Error())
			return
		}
	}
	return
}

// GetEdbOpButton 获取ETA指标的操作权限
func GetEdbOpButton(sysUser *system.Admin, belongUserId, edbType, edbInfoType int) (button data_manage.EdbClassifyItemsButton) {
	//2、用户对于自己添加的分类，有权限编辑、移动和删除该分类；
	//3、ficc管理员和超管对所有分类有编辑、移动和删除权限；
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || sysUser.AdminId == belongUserId || sysUser.EdbPermission == 1 {
		button.AddButton = true
		button.OpButton = true
		button.DeleteButton = true
		button.MoveButton = true

		// ETA指标的基础指标才允许插入值
		if edbInfoType == 0 && edbType == 1 {
			button.InsertNewDataButton = true
		}
	}
	button.ShowEdbRelation = true
	button.ShowChartRelation = true
	return
}

// GetEdbClassifyOpButton 获取ETA指标分类的操作权限
func GetEdbClassifyOpButton(sysUser *system.Admin, belongUserId int) (button data_manage.EdbClassifyItemsButton) {
	//2、用户对于自己添加的分类，有权限编辑、移动和删除该分类；
	//3、ficc管理员和超管对所有分类有编辑、移动和删除权限；
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
		button.AddButton = true
		button.OpButton = true
		button.DeleteButton = true
		button.MoveButton = true
	}
	return
}

// GetPredictEdbOpButton 获取ETA预测指标的操作权限
func GetPredictEdbOpButton(sysUser *system.Admin, belongUserId int) (button data_manage.EdbClassifyItemsButton) {
	//预测指标的添加人对该预测指标有全部操作权限，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
	}
	button.ShowEdbRelation = true
	button.ShowChartRelation = true
	return
}

// GetPredictEdbClassifyOpButton 获取ETA预测指标分类的操作权限
func GetPredictEdbClassifyOpButton(sysUser *system.Admin, belongUserId int) (button data_manage.EdbClassifyItemsButton) {
	//ficc管理员和超管有权限创建和管理分类，可以编辑分类名称（分类名称不允许重复），可以拖动分类，改变分类顺序，可以拖动分类下模型，改变顺序，可以删除分类，若分类下有预测指标，则不允许删除；
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN || sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN {
		button.AddButton = true
		button.OpButton = true
		button.DeleteButton = true
		button.MoveButton = true
	}
	return
}
