package data

import (
	"errors"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/models/system"
	"eta/eta_api/utils"
	"time"
)

// AddSciClassify 添加SCI分类
func AddSciClassify(classifyName string, parentId, sysUserId int, sysUserName, lang string) (classifyInfo *data_manage.BaseFromSciClassify, err error, errMsg string) {
	// 校验分类名称相同的数量
	{
		var count int
		switch lang {
		case utils.EnLangVersion:
			count, err = data_manage.GetBaseFromSciClassifyEnCount(classifyName, parentId)
		default:
			count, err = data_manage.GetBaseFromSciClassifyCount(classifyName, parentId)
		}
		if err != nil {
			errMsg = `判断名称是否已存在失败`
			return
		}
		if count > 0 {
			errMsg = `分类名称已存在,请重新输入`
			err = errors.New(errMsg)
			return
		}
	}
	level := 1
	if parentId > 0 {
		parentClassify, e := data_manage.GetBaseFromSciClassifyById(parentId)
		if e != nil {
			if e.Error() == utils.ErrNoRow() {
				err = e
				errMsg = `一级分类不存在`
				return
			}
			err = e
			errMsg = `查询一级分类失败`
			return
		}
		level = parentClassify.Level + 1
	}
	classifyInfo = &data_manage.BaseFromSciClassify{
		ClassifyName:    classifyName,
		ClassifyNameEn:  classifyName,
		ParentId:        parentId,
		SysUserId:       sysUserId,
		SysUserRealName: sysUserName,
		Sort:            0,
		Level:           level,
		ModifyTime:      time.Now(),
		CreateTime:      time.Now(),
	}
	classifyId, err := data_manage.AddBaseFromSciClassify(classifyInfo)
	if err != nil {
		errMsg = "保存分类失败"
		return
	}
	classifyInfo.ClassifyId = int(classifyId)
	//更新sort为classifyId
	err = data_manage.UpdateBaseFromSciClassifySort(int(classifyId))
	return
}

// EditSciClassify 编辑Sci分类
func EditSciClassify(classifyId int, classifyName, lang string, sysUser *system.Admin) (err error, errMsg string) {
	item, err := data_manage.GetBaseFromSciClassifyById(classifyId)
	if err != nil {
		errMsg = `保存失败`
		return
	}
	switch lang {
	case utils.EnLangVersion:
		// 名字相同,那么就直接返回
		if item.ClassifyNameEn == classifyName {
			return
		}

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

		// 修改数据
		err = data_manage.EditBaseFromSciClassifyEn(classifyId, classifyName)
		if err != nil {
			errMsg = "保存失败"
		}
	default:
		// 名字相同,那么就直接返回
		if item.ClassifyName == classifyName {
			return
		}

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

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

	return
}

// MoveSciClassify 移动Sci分类
func MoveSciClassify(classifyId, parentClassifyId, prevClassifyId, nextClassifyId int) (err error, errMsg string) {
	//判断分类是否存在
	classifyInfo, err := data_manage.GetBaseFromSciClassifyById(classifyId)
	if err != nil {
		errMsg = "移动失败"
		err = errors.New("获取分类信息失败,Err:" + err.Error())
		return
	}

	updateCol := make([]string, 0)

	//判断上级id是否一致,如果不一致的话,那么需要移动该分类层级
	if classifyInfo.ParentId != parentClassifyId && parentClassifyId != 0 {
		parentClassifyInfo, tmpErr := data_manage.GetBaseFromSciClassifyById(parentClassifyId)
		if tmpErr != nil {
			errMsg = "移动失败"
			err = errors.New("获取上级分类信息失败,Err:" + tmpErr.Error())
			return
		}
		classifyInfo.ParentId = parentClassifyInfo.ClassifyId
		classifyInfo.Level = parentClassifyInfo.Level + 1
		updateCol = append(updateCol, "ParentId", "Level")
	}
	var currentSort, prevSort, nextSort int
	currentSort = classifyInfo.Sort

	var prevClassify *data_manage.BaseFromSciClassify
	var nextClassify *data_manage.BaseFromSciClassify
	//如果有传入 上一个兄弟节点分类id
	if prevClassifyId > 0 {
		prevClassify, err = data_manage.GetBaseFromSciClassifyById(prevClassifyId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				errMsg = "移动失败"
				err = errors.New("上一个兄弟节点分类信息不存在" + err.Error())
				return
			}
			errMsg = "移动失败"
			err = errors.New("获取上一个兄弟节点分类信息失败,Err:" + err.Error())
			return
		}
		prevSort = prevClassify.Sort
	}
	if nextClassifyId > 0 {
		//下一个兄弟节点
		nextClassify, err = data_manage.GetBaseFromSciClassifyById(nextClassifyId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				errMsg = "移动失败"
				err = errors.New("下一个兄弟节点分类信息不存在" + err.Error())
				return
			}
			errMsg = "移动失败"
			err = errors.New("获取下一个兄弟节点分类信息失败,Err:" + err.Error())
			return
		}
		nextSort = nextClassify.Sort
	}
	// 修改历史数据中的排序为0的情况
	if prevSort == 0 && nextSort == 0 { //目标是让当前分类处于目录的最顶部
		//更新为0排序的数据为当前最小排序
		if nextClassify != nil {
			minSort, e := data_manage.GetSciIndexClassifyMinSort(parentClassifyId)
			if e != nil {
				errMsg = "移动失败"
				err = errors.New("获取下一个兄弟节点分类信息失败,Err:" + e.Error())
				return
			}
			if minSort > 1 {
				minSort -= 1
			}
			nextClassify.Sort = minSort
			err = nextClassify.Update([]string{"Sort"})
			if err != nil {
				errMsg = "移动失败"
				err = errors.New("更新下一个兄弟节点分类信息失败,Err:" + err.Error())
				return
			}
			nextSort = minSort
		}
	}
	//移到两个排序值中间操作
	if prevSort >= currentSort {
		//往下移动
		err = data_manage.MoveDownSciIndexClassifyBySort(parentClassifyId, prevSort, currentSort)
		if err != nil {
			err = errors.New("向下移动出错:" + err.Error())
			return
		}
		classifyInfo.Sort = prevSort
	} else if nextSort <= currentSort && nextSort != 0 {
		//往上移动
		err = data_manage.MoveUpSciIndexClassifyBySort(parentClassifyId, nextSort, currentSort)
		if err != nil {
			err = errors.New("向上移动出错:" + err.Error())
			return
		}
		classifyInfo.Sort = nextSort
	}
	classifyInfo.ModifyTime = time.Now()
	updateCol = append(updateCol, "Sort", "ModifyTime")
	err = classifyInfo.Update(updateCol)
	if err != nil {
		errMsg = "移动失败"
		err = errors.New("修改失败,Err:" + err.Error())
		return
	}
	return
}

// DelSciClassify 删除SCI分类
func DelSciClassify(classifyId int, sysUser *system.Admin) (err error, errMsg string) {
	//判断分类是否存在
	classifyInfo, err := data_manage.GetBaseFromSciClassifyById(classifyId)
	if err != nil {
		errMsg = "删除失败"
		err = errors.New("获取分类信息失败,Err:" + err.Error())
		return
	}

	// 需要删除的分类id集合
	classifyIdList := make([]int, 0)
	classifyIdList = append(classifyIdList, classifyId)
	// 查找所有的子集id
	if classifyInfo.ParentId <= 0 {
		childrenClassifyInfoList, tmpErr := data_manage.GetBaseFromSciClassifyByParentId(classifyId)
		if tmpErr != nil {
			errMsg = "删除失败"
			err = errors.New("获取分类信息失败,Err:" + tmpErr.Error())
			return
		}
		for _, v := range childrenClassifyInfoList {
			classifyIdList = append(classifyIdList, v.ClassifyId)
		}
	}

	// 获取分类下的所有指标
	count, err := data_manage.GetBaseFromSciIndexCountByClassifyIds(classifyIdList)
	if err != nil {
		errMsg = "删除失败"
		err = errors.New("获取分类下的指标信息失败,Err:" + err.Error())
		return
	}

	if count > 0 {
		errMsg = "该分类下有指标,不可删除"
		err = errors.New("该分类下有指标,不可删除")
		return
	}

	// 删除对应的分类
	err = data_manage.DeleteSciClassifyByClassifyId(classifyIdList)
	if err != nil {
		return
	}
	return
}

// MoveSciData 移动SCI指标
func MoveSciData(indexId, classifyId, prevIndexId, nextIndexId int) (err error, errMsg string) {
	//分类信息
	sciIndex, err := data_manage.GetBaseFromSciIndexByIndexId(indexId)
	if err != nil {
		errMsg = `获取数据失败`
		if err.Error() == utils.ErrNoRow() {
			errMsg = `该指标未入库`
			err = nil
		}
		return
	}

	//判断分类是否存在
	if classifyId > 0 {
		_, err = data_manage.GetBaseFromSciClassifyById(classifyId)
		if err != nil {
			errMsg = "移动失败"
			err = errors.New("获取分类信息失败,Err:" + err.Error())
			if err.Error() == utils.ErrNoRow() {
				errMsg = "找不到该分类"
				err = nil
			}
			return
		}
	}

	//如果改变了分类,那么移动该图表数据
	if sciIndex.ClassifyId != classifyId {
		tmpErr := data_manage.MoveBaseFromSciIndex(indexId, classifyId)
		if tmpErr != nil {
			errMsg = "移动失败"
			err = errors.New("移动失败,Err:" + tmpErr.Error())
			return
		}
	}

	//移动排序
	updateCol := make([]string, 0)
	//如果有传入 上一个兄弟节点分类id
	if prevIndexId > 0 {
		prevIndex, tmpErr := data_manage.GetBaseFromSciIndexByIndexId(prevIndexId)
		if tmpErr != nil {
			errMsg = "移动失败"
			err = errors.New("获取上一个兄弟节点指标信息失败,Err:" + tmpErr.Error())
			return
		}

		//如果是移动在两个兄弟节点之间
		if nextIndexId > 0 {
			//下一个兄弟节点
			nextIndex, tmpErr := data_manage.GetBaseFromSciIndexByIndexId(nextIndexId)
			if tmpErr != nil {
				errMsg = "移动失败"
				err = errors.New("获取下一个兄弟节点指标信息失败,Err:" + tmpErr.Error())
				return
			}
			//如果上一个兄弟与下一个兄弟的排序权重是一致的,那么需要将下一个兄弟(以及下个兄弟的同样排序权重)的排序权重+2,自己变成上一个兄弟的排序权重+1
			if prevIndex.Sort == nextIndex.Sort || prevIndex.Sort == sciIndex.Sort {
				//变更兄弟节点的排序
				updateSortStr := `sort + 2`
				err = data_manage.UpdateBaseFromSciIndexByClassifyId(prevIndex.ClassifyId, prevIndex.Sort, prevIndex.BaseFromSciIndexId, updateSortStr)
				if err != nil {
					errMsg = "移动失败"
					err = errors.New("变更兄弟节点排序指标信息失败,Err:" + err.Error())
					return
				}
			} else {
				//如果下一个兄弟的排序权重正好是上个兄弟节点的下一层,那么需要再加一层了
				if nextIndex.Sort-prevIndex.Sort == 1 {
					//变更兄弟节点的排序
					updateSortStr := `sort + 1`
					err = data_manage.UpdateBaseFromSciIndexByClassifyId(prevIndex.ClassifyId, prevIndex.Sort, prevIndex.BaseFromSciIndexId, updateSortStr)
					if err != nil {
						errMsg = "移动失败"
						err = errors.New("变更兄弟节点排序指标信息失败,Err:" + err.Error())
						return
					}
				}
			}
		}

		sciIndex.Sort = prevIndex.Sort + 1
		sciIndex.ModifyTime = time.Now()
		updateCol = append(updateCol, "Sort", "ModifyTime")

	} else {
		firstClassify, tmpErr := data_manage.GetFirstBaseFromSciIndexByClassifyId(classifyId)
		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.UpdateBaseFromSciIndexByClassifyId(firstClassify.ClassifyId, 0, firstClassify.BaseFromSciIndexId-1, updateSortStr)
		}

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

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

	return
}

// MoveSciData2 移动SCI指标
func MoveSciData2(indexId, classifyId, prevIndexId, nextIndexId int) (err error, errMsg string) {
	//分类信息
	sciIndex, err := data_manage.GetBaseFromSciIndexByIndexId(indexId)
	if err != nil {
		errMsg = `获取数据失败`
		if err.Error() == utils.ErrNoRow() {
			errMsg = `该指标未入库`
			err = nil
		}
		return
	}

	//判断分类是否存在
	if classifyId > 0 {
		_, err = data_manage.GetBaseFromSciClassifyById(classifyId)
		if err != nil {
			errMsg = "移动失败"
			err = errors.New("获取分类信息失败,Err:" + err.Error())
			if err.Error() == utils.ErrNoRow() {
				errMsg = "找不到该分类"
				err = nil
			}
			return
		}
	}

	//如果改变了分类,那么移动该图表数据
	if sciIndex.ClassifyId != classifyId {
		tmpErr := data_manage.MoveBaseFromSciIndex(indexId, classifyId)
		if tmpErr != nil {
			errMsg = "移动失败"
			err = errors.New("移动失败,Err:" + tmpErr.Error())
			return
		}
	}

	//移动排序
	updateCol := make([]string, 0)
	var currentSort, prevSort, nextSort int
	currentSort = sciIndex.Sort
	//如果有传入 上一个兄弟节点分类id
	var prevIndex *data_manage.BaseFromSciIndex
	var nextIndex *data_manage.BaseFromSciIndex
	if prevIndexId > 0 {
		prevIndex, err = data_manage.GetBaseFromSciIndexByIndexId(prevIndexId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				errMsg = "移动失败"
				err = errors.New("上一个兄弟节点指标信息不存在" + err.Error())
				return
			}
			errMsg = "移动失败"
			err = errors.New("获取上一个兄弟节点指标信息失败,Err:" + err.Error())
			return
		}
		prevSort = prevIndex.Sort
	}

	if nextIndexId > 0 {
		//下一个兄弟节点
		nextIndex, err = data_manage.GetBaseFromSciIndexByIndexId(nextIndexId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				errMsg = "移动失败"
				err = errors.New("下一个兄弟节点指标信息不存在" + err.Error())
				return
			}
			errMsg = "移动失败"
			err = errors.New("获取下一个兄弟节点指标信息失败,Err:" + err.Error())
			return
		}
		nextSort = nextIndex.Sort
	}

	// 修改历史数据中的排序为0的情况
	if prevSort == 0 && nextSort == 0 { //目标是让当前分类处于目录的最顶部, 但是历史数据里下个节点的sort为0的情况
		//更新为0排序的数据为当前最小排序
		if nextIndex != nil {
			minSort, e := data_manage.GetBaseFromSciIndexMinSortByClassifyId(classifyId)
			if e != nil {
				errMsg = "移动失败"
				err = errors.New("获取下一个兄弟节点分类信息失败,Err:" + e.Error())
				return
			}
			if minSort > 1 {
				minSort -= 1
			}
			nextIndex.Sort = minSort
			err = nextIndex.Update([]string{"Sort"})
			if err != nil {
				errMsg = "移动失败"
				err = errors.New("更新下一个兄弟节点分类信息失败,Err:" + err.Error())
				return
			}
			nextSort = minSort
		}
	}
	//移到两个排序值中间操作
	if prevSort >= currentSort {
		//往下移动
		err = data_manage.MoveDownSciIndexBySort(classifyId, prevSort, currentSort)
		if err != nil {
			err = errors.New("向下移动出错:" + err.Error())
			return
		}
		sciIndex.Sort = prevSort
	} else if nextSort <= currentSort && nextSort != 0 {
		//往上移动
		err = data_manage.MoveUpSciIndexBySort(classifyId, nextSort, currentSort)
		if err != nil {
			err = errors.New("向上移动出错:" + err.Error())
			return
		}
		sciIndex.Sort = nextSort
	}

	//更新
	sciIndex.ModifyTime = time.Now()
	updateCol = append(updateCol, "Sort", "ModifyTime")
	err = sciIndex.Update(updateCol)
	if err != nil {
		errMsg = "移动失败"
		err = errors.New("修改失败,Err:" + err.Error())
		return
	}
	return
}

// EditSciIndex 编辑SCI指标
func EditSciIndex(indexId, classifyId int, sysUser *system.Admin) (baseFromSciIndex *data_manage.BaseFromSciIndex, err error, errMsg string) {
	baseFromSciIndex, err = data_manage.GetBaseFromSciIndexByIndexId(indexId)
	if err != nil {
		errMsg = `获取数据失败`
		if err.Error() == utils.ErrNoRow() {
			errMsg = `该指标未入库`
			err = nil
		}
		return
	}

	baseFromSciIndex.ClassifyId = classifyId
	baseFromSciIndex.ModifyTime = time.Now()
	err = baseFromSciIndex.Update([]string{"ClassifyId", "ModifyTime"})
	if err != nil {
		errMsg = "保存分类失败"
	}

	return
}

func InitBaseFromSciClassify() (err error) {
	//查询历史数据所有分类
	typeList, err := data_manage.GetBaseFromSciIndexType()
	if err != nil {
		return
	}
	classifyList := make([]*data_manage.BaseFromSciClassify, 0)
	classifyMap := make(map[string][]string, 0)
	parentClassifyMap := make(map[string]struct{}, 0)
	now := time.Now()
	for _, v := range typeList {
		if _, ok := parentClassifyMap[v.Type2]; !ok {
			parentClassifyMap[v.Type2] = struct{}{}
			tmp := new(data_manage.BaseFromSciClassify)
			tmp.ClassifyName = v.Type2
			tmp.Level = 1
			tmp.ModifyTime = now
			tmp.CreateTime = now
			classifyList = append(classifyList, tmp)
		}
		classifyMap[v.Type2] = append(classifyMap[v.Type2], v.Type3)
	}
	//添加一级分类
	err = data_manage.AddSciClassifyMulti(classifyList)
	if err != nil {
		err = errors.New("新增分类出错:" + err.Error())
		return
	}
	//查询分类表的所有父级
	rootList, err := data_manage.GetBaseFromSciClassifyByParentId(0)
	if err != nil {
		return
	}
	classifyIdMap := make(map[string]int)
	for _, v := range rootList {
		classifyIdMap[v.ClassifyName] = v.ClassifyId
	}
	classifyList2 := make([]*data_manage.BaseFromSciClassify, 0)
	for _, v := range typeList {
		if parentId, ok := classifyIdMap[v.Type2]; ok {
			tmp := new(data_manage.BaseFromSciClassify)
			tmp.ParentId = parentId
			tmp.ClassifyName = v.Type3
			tmp.Level = 2
			tmp.ModifyTime = now
			tmp.CreateTime = now
			classifyList2 = append(classifyList2, tmp)
		}
	}
	//添加二级分类
	err = data_manage.AddSciClassifyMulti(classifyList2)
	if err != nil {
		err = errors.New("新增二级分类出错:" + err.Error())
		return
	}
	//初始化sort字段
	err = data_manage.InitSciClassifySort()
	if err != nil {
		return
	}
	//更新index表里的分类id
	err = data_manage.InitSciIndexClassifyId()
	return
}

// DelSciData 删除SCI指标
func DelSciData(indexId int) (err error, errMsg string) {
	baseFromSciIndex, err := data_manage.GetBaseFromSciIndexByIndexId(indexId)
	if err != nil {
		errMsg = `获取数据失败`
		if err.Error() == utils.ErrNoRow() {
			errMsg = `该指标未入库`
			err = nil
		}
		return
	}

	// 获取已经加入到EDB指标库的Sci指标
	edbInfo, err := data_manage.GetEdbInfoByEdbCode(utils.DATA_SOURCE_SCI, baseFromSciIndex.IndexCode)
	if err != nil && err.Error() != utils.ErrNoRow() {
		errMsg = "删除失败"
		err = errors.New("获取分类下的指标信息失败,Err:" + err.Error())
		return
	}
	if edbInfo != nil {
		errMsg = "当前指标已被引用,不可删除"
		err = nil
		return
	}

	// 删除对应的分类和指标
	err = data_manage.DeleteBaseFromSciIndexById(indexId)
	if err != nil {
		return
	}

	return
}

// ResetSciData 指标数据清除分类接口
func ResetSciData(indexId int) (err error, errMsg string) {
	sciIndex, err := data_manage.GetBaseFromSciIndexByIndexId(indexId)
	if err != nil {
		errMsg = `获取数据失败`
		if err.Error() == utils.ErrNoRow() {
			errMsg = `该指标未入库`
			err = nil
		}
		return
	}

	// 更新指标在未分类下的排序,永远排在未分类的最后一个
	//移动排序
	classifyId := 0
	updateCol := make([]string, 0)
	var currentSort, prevSort int
	currentSort = sciIndex.Sort
	//未分类的最大的sort值
	prevSort, err = data_manage.GetBaseFromSciIndexMaxSortByClassifyId(classifyId)
	if err != nil {
		errMsg = "移动失败"
		err = errors.New("获取上一个兄弟节点指标信息失败,Err:" + err.Error())
		return
	}

	//如果前面一个节点的sort值比当前大,则当前节点往下移动
	if prevSort >= currentSort {
		//往下移动
		err = data_manage.MoveDownSciIndexBySort(classifyId, prevSort, currentSort)
		if err != nil {
			err = errors.New("向下移动出错:" + err.Error())
			return
		}
		sciIndex.Sort = prevSort
	}

	//更新
	sciIndex.ModifyTime = time.Now()
	sciIndex.ClassifyId = classifyId
	updateCol = append(updateCol, "Sort", "ModifyTime", "ClassifyId")
	err = sciIndex.Update(updateCol)
	if err != nil {
		errMsg = "移动失败"
		err = errors.New("修改失败,Err:" + err.Error())
		return
	}
	return
}