package data_manage

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/services/data"
	"eta/eta_api/utils"
	"fmt"
	"sort"
	"strconv"
	"strings"
	"time"
)

// ClassifyList
// @Title 分类列表-含指标
// @Description 分类列表-含指标
// @Param   ParentId  query  int  false  "父级ID"
// @Success 200 {object} data_manage.ThsHfSearchEdbResp
// @router /ths_hf/classify/list [get]
func (this *BaseFromThsHfController) ClassifyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	parentId, _ := this.GetInt("ParentId")

	resp := make([]*data_manage.BaseFromThsHfClassifyListItem, 0)
	// 查询分类
	classifyOb := new(data_manage.BaseFromThsHfClassify)
	{
		cond := fmt.Sprintf(" AND %s = ?", classifyOb.Cols().ParentId)
		pars := make([]interface{}, 0)
		pars = append(pars, parentId)
		list, e := classifyOb.GetItemsByCondition(cond, pars, []string{}, fmt.Sprintf("%s ASC", classifyOb.Cols().Sort))
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = fmt.Sprintf("获取子分类失败, %v", e)
			return
		}
		for _, v := range list {
			resp = append(resp, &data_manage.BaseFromThsHfClassifyListItem{
				ClassifyId:     v.BaseFromThsHfClassifyId,
				ClassifyName:   v.ClassifyName,
				ClassifyNameEn: v.ClassifyNameEn,
				ParentId:       v.ParentId,
				Level:          v.Level,
				Sort:           v.Sort,
				UniqueCode:     v.UniqueCode,
			})
		}
	}

	// 查询指标
	indexOb := new(data_manage.BaseFromThsHfIndex)
	{
		cond := fmt.Sprintf(" AND %s = ?", indexOb.Cols().BaseFromThsHfClassifyId)
		pars := make([]interface{}, 0)
		pars = append(pars, parentId)
		list, e := indexOb.GetItemsByCondition(cond, pars, []string{}, fmt.Sprintf("%s ASC", indexOb.Cols().Sort))
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = fmt.Sprintf("获取分类下指标失败, %v", e)
			return
		}
		for _, v := range list {
			resp = append(resp, &data_manage.BaseFromThsHfClassifyListItem{
				ItemType:   1,
				IndexId:    v.BaseFromThsHfIndexId,
				IndexCode:  v.IndexCode,
				IndexName:  v.IndexName,
				ParentId:   parentId,
				Sort:       v.Sort,
				UniqueCode: v.IndexCode,
			})
		}
	}
	sort.Slice(resp, func(i, j int) bool {
		return resp[i].Sort < resp[j].Sort
	})

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

// ClassifyTree
// @Title 分类树
// @Description 分类树
// @Success 200 {object} data_manage.ThsHfSearchEdbResp
// @router /ths_hf/classify/tree [get]
func (this *BaseFromThsHfController) ClassifyTree() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}

	// 获取所有分类
	classifyOb := new(data_manage.BaseFromThsHfClassify)
	list, e := classifyOb.GetItemsByCondition(``, make([]interface{}, 0), []string{}, fmt.Sprintf("%s ASC, %s ASC", classifyOb.Cols().ParentId, classifyOb.Cols().Sort))
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = fmt.Sprintf("获取分类列表失败, %v", e)
		return
	}
	items := make([]*data_manage.BaseFromThsHfClassifyItem, 0)
	for _, v := range list {
		items = append(items, v.Format2Item())
	}
	tree := data.GetThsHfClassifyTreeRecursive(items, 0)

	br.Data = tree
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// ClassifyAdd
// @Title 新增分类
// @Description 新增分类
// @Param	request	body data_manage.ThsHfClassifyAddReq true "type json string"
// @Success 200 string "操作成功"
// @router /ths_hf/classify/add [post]
func (this *BaseFromThsHfController) ClassifyAdd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 data_manage.ThsHfClassifyAddReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常"
		br.ErrMsg = fmt.Sprintf("参数解析异常, %v", e)
		return
	}
	req.ClassifyName = strings.TrimSpace(req.ClassifyName)
	if req.ClassifyName == "" {
		br.Msg = "请输入分类名称"
		return
	}
	if req.ParentId < 0 {
		br.Msg = "请选择上级分类"
		return
	}
	if req.Level > 6 {
		br.Msg = "目前只支持6级目录"
		return
	}

	// 校验分类名称
	classifyOb := new(data_manage.BaseFromThsHfClassify)
	{
		cond := fmt.Sprintf(" AND %s = ?", classifyOb.Cols().ParentId)
		if this.Lang == utils.EnLangVersion {
			cond += fmt.Sprintf(" AND %s = ?", classifyOb.Cols().ClassifyNameEn)
		} else {
			cond += fmt.Sprintf(" AND %s = ?", classifyOb.Cols().ClassifyName)
		}
		pars := make([]interface{}, 0)
		pars = append(pars, req.ParentId, req.ClassifyName)
		count, e := classifyOb.GetCountByCondition(cond, pars)
		if e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = fmt.Sprintf("获取分类名称重复数失败, %v", e)
			return
		}
		if count > 0 {
			br.Msg = "分类名称已存在"
			return
		}
	}

	// 层级路径
	var levelPath string
	var rootId int
	if req.ParentId > 0 {
		parent, e := classifyOb.GetItemById(req.ParentId)
		if e != nil {
			br.Msg = "上级分类有误"
			br.ErrMsg = fmt.Sprintf("获取上级分类失败, %v", e)
			return
		}
		levelPath = parent.LevelPath
		rootId = parent.RootId
	}

	sortMax, e := classifyOb.GetSortMax(req.ParentId)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = fmt.Sprintf("获取分类最大排序失败, %v", e)
		return
	}
	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	classifyOb.ParentId = req.ParentId
	classifyOb.ClassifyName = req.ClassifyName
	classifyOb.ClassifyNameEn = req.ClassifyName
	classifyOb.Level = req.Level + 1
	classifyOb.Sort = sortMax + 1
	classifyOb.SysUserId = sysUser.AdminId
	classifyOb.SysUserRealName = sysUser.RealName
	classifyOb.UniqueCode = utils.MD5(classifyOb.TableName() + "_" + timestamp)
	classifyOb.CreateTime = time.Now().Local()
	classifyOb.ModifyTime = time.Now().Local()
	if e = classifyOb.Create(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = fmt.Sprintf("新增分类失败, %v", e)
		return
	}
	if req.ParentId > 0 {
		// 用英文逗号拼接方便查询
		classifyOb.LevelPath = fmt.Sprintf("%s,%d", levelPath, classifyOb.BaseFromThsHfClassifyId)
		classifyOb.RootId = rootId
	} else {
		classifyOb.LevelPath = fmt.Sprint(classifyOb.BaseFromThsHfClassifyId)
		classifyOb.RootId = classifyOb.BaseFromThsHfClassifyId
	}
	if e = classifyOb.Update([]string{classifyOb.Cols().LevelPath, classifyOb.Cols().RootId}); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = fmt.Sprintf("更新分类失败, %v", e)
		return
	}

	br.Data = classifyOb.BaseFromThsHfClassifyId
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// ClassifyEdit
// @Title 编辑分类
// @Description 编辑分类
// @Param	request	body data_manage.ThsHfClassifyEditReq true "type json string"
// @Success 200 string "操作成功"
// @router /ths_hf/classify/edit [post]
func (this *BaseFromThsHfController) ClassifyEdit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 data_manage.ThsHfClassifyEditReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常"
		br.ErrMsg = fmt.Sprintf("参数解析异常, %v", e)
		return
	}
	if req.ClassifyId < 0 {
		br.Msg = "请选择分类"
		return
	}
	req.ClassifyName = strings.TrimSpace(req.ClassifyName)
	if req.ClassifyName == "" {
		br.Msg = "请输入分类名称"
		return
	}

	classifyOb := new(data_manage.BaseFromThsHfClassify)
	classifyItem, e := classifyOb.GetItemById(req.ClassifyId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = fmt.Sprintf("获取分类失败, %v", e)
		return
	}

	// 校验分类名称
	{
		cond := fmt.Sprintf(" AND %s <> ?", classifyOb.Cols().PrimaryId)
		if this.Lang == utils.EnLangVersion {
			cond += fmt.Sprintf(" AND %s = ?", classifyOb.Cols().ClassifyNameEn)
		} else {
			cond += fmt.Sprintf(" AND %s = ?", classifyOb.Cols().ClassifyName)
		}
		pars := make([]interface{}, 0)
		pars = append(pars, req.ClassifyId, req.ClassifyName)
		count, e := classifyOb.GetCountByCondition(cond, pars)
		if e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = fmt.Sprintf("获取分类名称重复数失败, %v", e)
			return
		}
		if count > 0 {
			br.Msg = "分类名称已存在"
			return
		}
	}
	classifyItem.ClassifyName = req.ClassifyName
	classifyItem.ClassifyNameEn = req.ClassifyName
	classifyItem.ModifyTime = time.Now().Local()
	updateCols := []string{classifyOb.Cols().ClassifyName, classifyOb.Cols().ClassifyNameEn, classifyOb.Cols().ModifyTime}
	if e = classifyItem.Update(updateCols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = fmt.Sprintf("更新分类失败, %v", e)
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// ClassifyRemove
// @Title 删除分类
// @Description 删除分类
// @Param	request	body data_manage.ThsHfClassifyRemoveReq true "type json string"
// @Success 200 string "操作成功"
// @router /ths_hf/classify/remove [post]
func (this *BaseFromThsHfController) ClassifyRemove() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 data_manage.ThsHfClassifyRemoveReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常"
		br.ErrMsg = fmt.Sprintf("参数解析异常, %v", e)
		return
	}
	if req.ClassifyId < 0 {
		br.Msg = "请选择分类"
		return
	}

	classifyOb := new(data_manage.BaseFromThsHfClassify)
	classifyItem, e := classifyOb.GetItemById(req.ClassifyId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Ret = 200
			br.Success = true
			br.Msg = "获取成功"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = fmt.Sprintf("获取分类失败, %v", e)
		return
	}

	// 查询子分类
	{
		cond := fmt.Sprintf(" AND %s = ?", classifyOb.Cols().ParentId)
		pars := make([]interface{}, 0)
		pars = append(pars, req.ClassifyId)
		count, e := classifyOb.GetCountByCondition(cond, pars)
		if e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = fmt.Sprintf("获取子分类数失败, %v", e)
			return
		}
		if count > 0 {
			br.Msg = "该分类下含有子分类, 不允许删除"
			return
		}
	}

	// 查询指标
	indexOb := new(data_manage.BaseFromThsHfIndex)
	{
		cond := fmt.Sprintf(" AND %s = ?", indexOb.Cols().BaseFromThsHfClassifyId)
		pars := make([]interface{}, 0)
		pars = append(pars, req.ClassifyId)
		count, e := indexOb.GetCountByCondition(cond, pars)
		if e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = fmt.Sprintf("获取分类下指标数失败, %v", e)
			return
		}
		if count > 0 {
			br.Msg = "该分类下含有指标, 不允许删除"
			return
		}
	}

	if e := classifyItem.Remove(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = fmt.Sprintf("删除分类失败, %v", e)
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// ClassifyMove
// @Title 移动分类
// @Description 移动分类
// @Param	request	body data_manage.BaseFromThsHfClassifyMoveReq true "type json string"
// @Success 200 string "操作成功"
// @router /ths_hf/classify/move [post]
func (this *BaseFromThsHfController) ClassifyMove() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		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 data_manage.BaseFromThsHfClassifyMoveReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常"
		br.ErrMsg = fmt.Sprintf("参数解析异常, %v", e)
		return
	}
	if req.ClassifyId <= 0 && req.ItemId <= 0 {
		br.Msg = "请选择分类或指标"
		return
	}

	err, errMsg := data.ThsHfMoveClassify(req, sysUser)
	if errMsg != `` {
		br.Msg = errMsg
		br.ErrMsg = errMsg
		if err != nil {
			br.ErrMsg = err.Error()
		} else {
			br.IsSendEmail = false
		}
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}