package help_doc

import (
	"encoding/json"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/help_doc"
	"hongze/hz_crm_api/services/data"
	"hongze/hz_crm_api/utils"
	"time"
)

// HelpDocClassifyController 帮助文档分类
type HelpDocClassifyController struct {
	controllers.BaseAuthController
}

// ListClassify
// @Title 获取分类列表
// @Description 获取分类列表
// @Param   KeyWord   query   string  true       "检索关键词"
// @Success 200 {object} models.HelpDocClassifyListResp
// @router /classify/list [get]
func (this *HelpDocClassifyController) ListClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	keyWord := this.GetString("KeyWord")

	resp := new(help_doc.HelpDocClassifyListResp)

	rootList, err := help_doc.GetHelpDocClassifyByParentId(0, "")
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	docAll, err := help_doc.GetAllHelpDoc()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	classifyMap := make(map[int]int,0)
	for _, v := range docAll {
		classifyMap[v.ClassifyId] = 1
	}

	classifyAll := make([]*help_doc.HelpDocClassifyItems, 0)
	newClassifyAll := make([]*help_doc.HelpDocClassifyItems, 0)
	newRootList := make([]help_doc.HelpDocClassifyItems, 0)
	//parentMap := make(map[int]int)
	classifyAllMap := make(map[int]*help_doc.HelpDocClassifyItems, 0)
	classifyKeyMap := make(map[int]*help_doc.HelpDocClassifyItems, 0)
	rootMap := make(map[*help_doc.HelpDocClassifyItems]int, 0)
	if keyWord != "" {
		classifyAll, err = help_doc.GetAllHelpDocClassifyByKeyword("")
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}

		for _, v := range classifyAll {
			classifyAllMap[v.ClassifyId] = v
		}

		keywordClassify, err := help_doc.GetAllHelpDocClassifyByKeyword(keyWord)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		for _, v := range keywordClassify {
			if v.Level == 3 {
				ppid := classifyAllMap[v.ParentId].ParentId
				//newRootList = append(newRootList, *classifyAllMap[ppid])
				rootMap[classifyAllMap[ppid]] = 1
				classifyKeyMap[v.ClassifyId] = v
				classifyKeyMap[v.ParentId] = classifyAllMap[v.ParentId]
			} else if v.Level == 2{
				pid := classifyAllMap[v.ParentId].ClassifyId
				//newRootList = append(newRootList, *classifyAllMap[pid])
				rootMap[classifyAllMap[pid]] = 1
				classifyKeyMap[v.ClassifyId] = v
			} else if v.Level == 1 {
				//newRootList = append(newRootList, *v)
				rootMap[v] = 1
			}
		}
		// 重新组合 newRootList
		//for _, v := range rootList {
		//	if root,ok := rootMap[v.ClassifyId]; ok{
		//		newRootList = append(newRootList, *root)
		//	}
		//}
		for v, _ := range rootMap {
			newRootList = append(newRootList, *v)
		}
		// 重新组合 newClassifyAll
		for _, v := range classifyKeyMap {
			if v.Level != 1 {
				newClassifyAll = append(newClassifyAll, v)
			}
		}
	} else {
		classifyAll, err = help_doc.GetHelpDocClassifyAll("")
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		newRootList = rootList
		newClassifyAll = classifyAll
	}

	for k := range newClassifyAll {
		_,ok := classifyMap[newClassifyAll[k].ClassifyId]
		newClassifyAll[k].Disabled = ok
	}

	//rootListAll := make([]help_doc.HelpDocClassifyItems, 0)
	//rootListAll = rootList
	nodeAll := make([]*help_doc.HelpDocClassifyItems, 0)
	for k := range newRootList {
		rootNode := newRootList[k]
		data.HelpDocClassifyItemsMakeTree(newClassifyAll, &rootNode)
		nodeAll = append(nodeAll, &rootNode)
	}

	//添加分类用，只有一二级目录
	classifyLevel, err := help_doc.GetHelpDocClassifyLevel()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	for k := range classifyLevel {
		_,ok := classifyMap[classifyLevel[k].ClassifyId]
		classifyLevel[k].Disabled = ok
	}

	//rootListLevel := make([]help_doc.HelpDocClassifyItems, 0)
	//rootListLevel = rootList
	nodeAllTwoLevel := make([]*help_doc.HelpDocClassifyItems, 0)
	for k := range rootList {
		rootNode := rootList[k]
		data.HelpDocClassifyItemsMakeTree(classifyLevel, &rootNode)
		nodeAllTwoLevel = append(nodeAllTwoLevel, &rootNode)
	}

	resp.AllNodes = nodeAll
	resp.TwoLevelNodes = nodeAllTwoLevel
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 新增分类
// @Description 新增分类接口
// @Param   ClassifyName   int  true       "分类名称"
// @Param   ParentId   query   int  true       "父级Id 添加父级时为0"
// @Param   Sort   query   string  false       "排序"
// @Success 200 新增成功
// @router /classify/add [post]
func (this *HelpDocClassifyController) AddClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req help_doc.AddHelpDocClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.HelpDocClassifyName == "" {
		br.Msg = "请输入分类名称"
		br.IsSendEmail = false
		return
	}
	if req.ParentId < 0 {
		br.Msg = "参数错误"
		br.IsSendEmail = false
		return
	}

	count, err := help_doc.GetHelpDocClassifyCount(req.HelpDocClassifyName, req.ParentId)
	if err != nil {
		br.Msg = "判断名称是否已存在失败"
		br.ErrMsg = "判断名称是否已存在失败，Err:" + err.Error()
		return
	}
	if count > 0 {
		br.Msg = "分类名称已存在，请重新输入"
		br.IsSendEmail = false
		return
	}
	//获取该层级下最大的排序数
	maxSort, err := help_doc.GetHelpDocClassifyMaxSort(req.ParentId)

	classify := new(help_doc.HelpDocClassify)
	classify.ParentId = req.ParentId
	classify.ClassifyName = req.HelpDocClassifyName
	classify.CreateTime = time.Now()
	classify.ModifyTime = time.Now()
	classify.SysUserId = this.SysUser.AdminId
	classify.SysUserRealName = this.SysUser.RealName
	classify.Level = req.Level + 1
	classify.Sort = maxSort + 1

	_, err = help_doc.AddHelpDocClassify(classify)
	if err != nil {
		br.Msg = "保存分类失败"
		br.ErrMsg = "保存分类失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
}

// @Title 编辑分类
// @Description 编辑分类接口
// @Param   ClassifyId   int  true       "分类Id"
// @Param   ClassifyName   string  true       "分类名称"
// @Param   ParentId   query   int  true       "父级Id 添加父级时为0"
// @Param   Sort   query   string  false       "排序"
// @Success 200 保存成功
// @router /classify/edit [post]
func (this *HelpDocClassifyController) EditClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req help_doc.EditHelpDocClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.HelpDocClassifyName == "" {
		br.Msg = "请输入分类名称"
		br.IsSendEmail = false
		return
	}

	if req.HelpDocClassifyId <= 0 {
		br.Msg = "参数错误"
		br.IsSendEmail = false
		return
	}

	item, err := help_doc.GetHelpDocClassifyById(req.HelpDocClassifyId)
	if err != nil {
		br.Msg = "保存失败"
		br.Msg = "获取分类信息失败,Err:" + err.Error()
		return
	}

	if item.ClassifyName != req.HelpDocClassifyName {
		count, err := help_doc.GetHelpDocClassifyCount(req.HelpDocClassifyName, item.ParentId)
		if err != nil {
			br.Msg = "判断名称是否已存在失败"
			br.ErrMsg = "判断名称是否已存在失败，Err:" + err.Error()
			return
		}
		if count > 0 {
			br.Msg = "分类名称已存在，请重新输入"
			br.IsSendEmail = false
			return
		}

		err = help_doc.EditHelpDocClassify(req.HelpDocClassifyId, req.HelpDocClassifyName)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "保存失败,Err:" + err.Error()
			return
		}
	}
	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
	br.IsAddLog = true
}

// @Title 删除分类列表
// @Description 删除分类列表
// @Param   ClassifyId   int  true       "分类名称"
// @Success 200 删除成功
// @router /classify/delete [get]
func (this *HelpDocClassifyController) DelClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	classifyId, _ := this.GetInt("ClassifyId")

	_, err := help_doc.GetHelpDocClassifyById(classifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "当前分类不存在"
			br.ErrMsg = "当前分类不存在"
			return
		}
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取分类信息失败，Err:" + err.Error()
		return
	}

	count, err := help_doc.GetHelpDocClassifyChildCounts(classifyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	if count > 0 {
		br.Msg = "请先删除该分类下关联分类"
		br.Ret = 403
		return
	}

	reportCount, e := help_doc.GetHelpDocCounts(classifyId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取失败，Err:" + e.Error()
		return
	}

	if reportCount > 0 {
		br.Msg = "该分类已关联文章，不允许删除！"
		br.Ret = 403
		return
	}

	if err = help_doc.DeleteHelpDocClassify(classifyId); err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除分类失败, Err: " + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}

// ChartClassifyMove
// @Title 分类移动接口
// @Description 分类移动接口
// @Success 200 {object} data_manage.MoveChartClassifyReq
// @router /classify/move [post]
func (this *HelpDocClassifyController) ClassifyMove() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req help_doc.MoveClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ClassifyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "分类id小于等于0"
		return
	}
	//判断分类是否存在
	classifyInfo, err := help_doc.GetHelpDocClassifyById(req.ClassifyId)
	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "获取分类信息失败,Err:" + err.Error()
		return
	}
	updateCol := make([]string, 0)

	//判断上级id是否一致，如果不一致的话，那么需要移动该分类层级
	if classifyInfo.ParentId != req.ParentClassifyId && req.ParentClassifyId != 0 {
		parentClassifyInfo, err := help_doc.GetHelpDocClassifyById(req.ParentClassifyId)
		if err != nil {
			br.Msg = "移动失败"
			br.ErrMsg = "获取上级分类信息失败,Err:" + err.Error()
			return
		}
		classifyInfo.ParentId = parentClassifyInfo.ClassifyId
		classifyInfo.Level = parentClassifyInfo.Level + 1
		classifyInfo.ModifyTime = time.Now()
		updateCol = append(updateCol, "ParentId", "Level", "ModifyTime")
	}

	//如果有传入 上一个兄弟节点分类id
	if req.PrevClassifyId > 0 {
		//上一个兄弟节点
		prevClassify, err := help_doc.GetHelpDocClassifyById(req.PrevClassifyId)
		if err != nil {
			br.Msg = "移动失败"
			br.ErrMsg = "获取上一个兄弟节点分类信息失败,Err:" + err.Error()
			return
		}

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

		classifyInfo.Sort = prevClassify.Sort + 1
		classifyInfo.ModifyTime = time.Now()
		updateCol = append(updateCol, "Sort", "ModifyTime")

	} else {
		firstClassify, err := help_doc.GetFirstHelpDocClassifyByParentId(classifyInfo.ParentId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "移动失败"
			br.ErrMsg = "获取获取当前父级分类下的排序第一条的分类信息失败,Err:" + err.Error()
			return
		}

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

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

	//更新
	if len(updateCol) > 0 {
		err = classifyInfo.Update(updateCol)
		if err != nil {
			br.Msg = "移动失败"
			br.ErrMsg = "修改失败,Err:" + err.Error()
			return
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "移动成功"
}

// @Title 编辑分类可见权限
// @Description 编辑分类可见权限接口
// @Param   ClassifyId   int  true       "分类Id"
// @Param   ClassifyName   string  true       "分类名称"
// @Param   ParentId   query   int  true       "父级Id 添加父级时为0"
// @Param   Sort   query   string  false       "排序"
// @Success 200 保存成功
// @router /classify/visible/edit [post]
func (this *HelpDocClassifyController) EditClassifyVisible() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req help_doc.EditHelpDocClassifyVisibleReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.HelpDocClassifyId <= 0 {
		br.Msg = "参数错误"
		br.IsSendEmail = false
		return
	}

	//item, err := help_doc.GetHelpDocClassifyById(req.HelpDocClassifyId)
	//if err != nil {
	//	br.Msg = "保存失败"
	//	br.Msg = "获取分类信息失败,Err:" + err.Error()
	//	return
	//}

	err = help_doc.EditHelpDocClassifyVisible(req.HelpDocClassifyId, req.VisibleBusinessIds)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
	br.IsAddLog = true
}
