package data_manage

import (
	"encoding/json"
	"eta/eta_api/controllers"
	"eta/eta_api/models"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/models/data_manage/request"
	"eta/eta_api/models/data_manage/response"
	"eta/eta_api/utils"
	"strconv"
	"time"
)

// ExcelClassifyController ETA表格分类
type ExcelClassifyController struct {
	controllers.BaseAuthController
}

// List
// @Title excel表格分类列表
// @Description excel表格分类列表接口
// @Param   Source   query   int  true       "格来源，1：excel插件的表格，2：自定义表格，3：混合表格，默认：1"
// @Success 200 {object} response.ExcelClassifyListResp
// @router /excel_classify/list [get]
func (this *ExcelClassifyController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	source, _ := this.GetInt("Source")
	if source <= 0 {
		source = utils.EXCEL_DEFAULT
	}

	// 获取一级分类
	rootList, err := data_manage.GetExcelClassifyByParentId(0, source)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	// 获取所有excel表格分类
	allExcelInfo, err := data_manage.GetNoContentExcelInfoAll()
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取表格信息失败，Err:" + err.Error()
		return
	}

	ExcelInfoMap := make(map[int][]*data_manage.ExcelClassifyItems)
	for _, v := range allExcelInfo {
		ExcelInfoMap[v.ExcelClassifyId] = append(ExcelInfoMap[v.ExcelClassifyId], v)
	}
	//rootChildMap := make(map[int][]*data_manage.ExcelClassifyItems)
	//for _, v := range classifyAll {
	//	rootChildMap[v.ParentId] = append(rootChildMap[v.ParentId], v)
	//	if existItems, ok := ExcelInfoMap[v.ExcelClassifyId]; ok {
	//		v.Children = existItems
	//	} else {
	//		items := make([]*data_manage.ExcelClassifyItems, 0)
	//		v.Children = items
	//	}
	//}
	nodeAll := make([]*data_manage.ExcelClassifyItems, 0)
	for _, v := range rootList {
		var items []*data_manage.ExcelClassifyItems
		if tmpItem, ok := ExcelInfoMap[v.ExcelClassifyId]; ok {
			items = tmpItem
		} else {
			items = make([]*data_manage.ExcelClassifyItems, 0)
		}
		v.Children = items
		nodeAll = append(nodeAll, v)
	}
	resp := response.ExcelClassifyListResp{
		AllNodes: nodeAll,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ExcelClassifyItems
// @Title 获取所有excel表格分类接口-不包含表格
// @Description 获取所有excel表格分类接口-不包含表格
// @Param   Source   query   int  true       "格来源，1：excel插件的表格，2：自定义表格，3：混合表格，默认：1"
// @Success 200 {object} response.ExcelClassifyListResp
// @router /excel_classify/items [get]
func (this *ExcelClassifyController) ExcelClassifyItems() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	source, _ := this.GetInt("Source")
	if source <= 0 {
		source = utils.EXCEL_DEFAULT
	}
	rootList, err := data_manage.GetExcelClassifyByParentId(0, source)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	resp := response.ExcelClassifyListResp{
		AllNodes: rootList,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// AddExcelClassify
// @Title 新增excel表格分类
// @Description 新增excel表格分类接口
// @Param	request	body request.AddExcelClassifyReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /excel_classify/add [post]
func (this *ExcelClassifyController) AddExcelClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.AddExcelClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ExcelClassifyName == "" {
		br.Msg = "请输入分类名称"
		br.IsSendEmail = false
		return
	}
	if req.ParentId < 0 {
		br.Msg = "参数错误"
		br.IsSendEmail = false
		return
	}

	source := req.Source
	if source <= 0 {
		source = utils.EXCEL_DEFAULT
	}

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

	// 入库
	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	classify := &data_manage.ExcelClassify{
		//ExcelClassifyId:   0,
		ExcelClassifyName: req.ExcelClassifyName,
		ParentId:          req.ParentId,
		Source:            source,
		SysUserId:         this.SysUser.AdminId,
		SysUserRealName:   this.SysUser.RealName,
		Level:             req.Level + 1,
		UniqueCode:        utils.MD5(utils.EXCEL_DATA_PREFIX + "_" + timestamp),
		Sort:              maxSort + 1,
		CreateTime:        time.Now(),
		ModifyTime:        time.Now(),
	}
	_, err = data_manage.AddExcelClassify(classify)
	if err != nil {
		br.Msg = "保存分类失败"
		br.ErrMsg = "保存分类失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
}

// EditExcelClassify
// @Title 修改excel表格分类
// @Description 修改excel表格分类
// @Param	request	body request.EditExcelClassifyReq true "type json string"
// @Success 200 Ret=200 修改成功
// @router /excel_classify/edit [post]
func (this *ExcelClassifyController) EditExcelClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.EditExcelClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ExcelClassifyName == "" {
		br.Msg = "请输入分类名称"
		br.IsSendEmail = false
		return
	}

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

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

	// 名字一致的话，直接返回成功
	if item.ExcelClassifyName == req.ExcelClassifyName {
		br.Ret = 200
		br.Msg = "保存成功"
		br.Success = true
		return
	}

	// 获取同级分类下存在同名分类的数量
	count, err := data_manage.GetExcelClassifyCount(req.ExcelClassifyName, item.ParentId, item.Source)
	if err != nil {
		br.Msg = "判断名称是否已存在失败"
		br.ErrMsg = "判断名称是否已存在失败，Err:" + err.Error()
		return
	}
	if count > 0 {
		br.Msg = "分类名称已存在，请重新输入"
		br.IsSendEmail = false
		return
	}

	// 修改分类名称
	item.ExcelClassifyName = req.ExcelClassifyName
	err = item.Update([]string{"ExcelClassifyName"})
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Msg = "修改成功"
	br.Success = true
	br.IsAddLog = true
}

// DeleteExcelClassifyCheck
// @Title 删除表格检测接口
// @Description 删除表格检测接口
// @Param	request	body request.ExcelClassifyDeleteCheckReq true "type json string"
// @Success 200 {object} response.ExcelClassifyDeleteCheckResp
// @router /excel_classify/delete/check [post]
func (this *ExcelClassifyController) DeleteExcelClassifyCheck() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.ExcelClassifyDeleteCheckReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ExcelClassifyId < 0 && req.ExcelInfoId <= 0 {
		br.Msg = "参数错误"
		br.IsSendEmail = false
		return
	}
	var deleteStatus int
	var tipsMsg string

	// 校验是否存在该分类
	ExcelClassifyInfo, err := data_manage.GetExcelClassifyById(req.ExcelClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "该分类不存在"
			br.ErrMsg = "该分类不存在"
			return
		}
		br.Msg = "删除失败"
		br.ErrMsg = "查询该分类失败，Err:" + err.Error()
		return
	}
	if ExcelClassifyInfo == nil {
		br.Msg = "该分类不存在"
		br.ErrMsg = "该分类不存在"
		br.IsSendEmail = false
		return
	}
	//删除分类
	if req.ExcelClassifyId > 0 && req.ExcelInfoId == 0 {
		//判断表格分类下，是否含有表格
		count, err := data_manage.GetExcelInfoCountByClassifyId(req.ExcelClassifyId)
		if err != nil {
			br.Msg = "删除失败"
			br.ErrMsg = "分类下是否含有指标失败，Err:" + err.Error()
			return
		}

		if count > 0 {
			deleteStatus = 1
			tipsMsg = "该分类下关联表格不可删除"
		}
	}

	//if deleteStatus != 1 && req.ExcelInfoId == 0 {
	//	classifyCount, err := data_manage.GetExcelClassifyCountByClassifyId(req.ExcelClassifyId)
	//	if err != nil && err.Error() != utils.ErrNoRow() {
	//		br.Msg = "删除失败"
	//		br.ErrMsg = "分类下是否含有表格失败，Err:" + err.Error()
	//		return
	//	}
	//	if classifyCount > 0 {
	//		deleteStatus = 2
	//		tipsMsg = "确认删除当前目录及包含的子目录吗？"
	//	}
	//}

	if deleteStatus == 0 {
		tipsMsg = "可删除，进行删除操作"
	}

	resp := response.ExcelClassifyDeleteCheckResp{
		DeleteStatus: deleteStatus,
		TipsMsg:      tipsMsg,
	}
	br.Ret = 200
	br.Msg = "检测成功"
	br.Success = true
	br.Data = resp
}

// DeleteExcelClassify
// @Title 删除表格分类/表格
// @Description 删除表格分类/表格接口
// @Param	request	body request.DeleteExcelClassifyReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /excel_classify/delete [post]
func (this *ExcelClassifyController) DeleteExcelClassify() {
	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 request.DeleteExcelClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

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

	//删除分类
	if req.ExcelClassifyId > 0 && req.ExcelInfoId == 0 {
		//判断是否含有指标
		count, err := data_manage.GetExcelInfoCountByClassifyId(req.ExcelClassifyId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "删除失败"
			br.ErrMsg = "判断名称是否已存在失败，Err:" + err.Error()
			return
		}

		if count > 0 {
			br.Msg = "该目录下存在关联ETA表格，不可删除"
			br.IsSendEmail = false
			return
		}

		classifyItem, err := data_manage.GetExcelClassifyById(req.ExcelClassifyId)
		if err != nil {
			br.Msg = "删除失败"
			br.ErrMsg = "获取分类失败，Err:" + err.Error()
			if err.Error() == utils.ErrNoRow() {
				br.Msg = "分类不存在"
				br.ErrMsg = "分类不存在"
			}
			return
		}
		classifyItem.IsDelete = 1
		err = classifyItem.Update([]string{"IsDelete"})
		if err != nil {
			br.Msg = "删除失败"
			br.ErrMsg = "删除失败,Err:" + err.Error()
			return
		}
	}

	resp := response.AddExcelInfoResp{}
	//删除表格
	if req.ExcelInfoId > 0 {
		excelInfo, err := data_manage.GetExcelInfoById(req.ExcelInfoId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				br.Msg = "表格已删除，请刷新页面"
				br.ErrMsg = "表格已删除，请刷新页面"
				return
			} else {
				br.Msg = "删除失败"
				br.ErrMsg = "删除失败，获取指标信息失败，Err:" + err.Error()
				return
			}
		}
		if excelInfo == nil {
			br.Msg = "表格已删除，请刷新页面"
			br.IsSendEmail = false
			return
		}
		//删除表格及关联指标
		excelInfo.IsDelete = 1
		err = excelInfo.Update([]string{"IsDelete"})
		if err != nil {
			br.Msg = "删除失败"
			br.ErrMsg = "删除失败，Err:" + err.Error()
			return
		}

		// 返回下一个表格的信息
		{
			var nextItem *data_manage.ExcelInfo
			var condition string
			var pars []interface{}
			condition += " AND excel_classify_id=? "
			pars = append(pars, excelInfo.ExcelClassifyId)

			condition += " AND (sort>? OR (sort=? AND excel_info_id<?) ) "
			pars = append(pars, excelInfo.Sort, excelInfo.Sort, excelInfo.ExcelInfoId)
			nextItem, err = data_manage.GetNextExcelInfoByCondition(condition, pars)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "删除失败"
				br.ErrMsg = "获取下一级表格信息失败，Err:" + err.Error()
				return
			}

			// 如果没找到，那么查找下一个分类的第一个表格
			if nextItem == nil {
				currClassifyInfo, err := data_manage.GetExcelClassifyById(excelInfo.ExcelClassifyId)
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "删除失败"
					br.ErrMsg = "获取当前表格分类信息失败，Err:" + err.Error()
					return
				}

				nextItem, err = data_manage.GetNextExcelInfo(excelInfo.ExcelClassifyId, currClassifyInfo.Sort, currClassifyInfo.Source)
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "删除失败"
					br.ErrMsg = "获取下一级表格信息失败，Err:" + err.Error()
					return
				}
			}

			// 如果找到下一个表格了，那么就返回
			if nextItem != nil {
				resp = response.AddExcelInfoResp{
					ExcelInfoId: nextItem.ExcelInfoId,
					UniqueCode:  nextItem.UniqueCode,
				}
			}
		}

		//新增操作日志
		//{
		//	ExcelLog := new(data_manage.ExcelInfoLog)
		//	ExcelLog.ExcelName = ExcelInfo.ExcelName
		//	ExcelLog.ExcelInfoId = req.ExcelInfoId
		//	ExcelLog.ExcelClassifyId = ExcelInfo.ExcelClassifyId
		//	ExcelLog.SysUserId = sysUser.AdminId
		//	ExcelLog.SysUserRealName = sysUser.RealName
		//	ExcelLog.UniqueCode = ExcelInfo.UniqueCode
		//	ExcelLog.CreateTime = time.Now()
		//	ExcelLog.Content = string(this.Ctx.Input.RequestBody)
		//	ExcelLog.Status = "删除表格"
		//	ExcelLog.Method = this.Ctx.Input.URI()
		//	go data_manage.AddExcelInfoLog(ExcelLog)
		//}
	}
	br.Ret = 200
	br.Msg = "删除成功"
	br.Success = true
	br.Data = resp
	br.IsAddLog = true
}

// ExcelClassifyMove
// @Title 表格分类移动接口
// @Description 表格分类移动接口
// @Success 200 {object} request.MoveExcelClassifyReq
// @router /excel_classify/move [post]
func (this *ExcelClassifyController) ExcelClassifyMove() {
	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 request.MoveExcelClassifyReq
	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"
		br.IsSendEmail = false
		return
	}
	//判断分类是否存在
	ExcelClassifyInfo, err := data_manage.GetExcelClassifyById(req.ClassifyId)
	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "获取分类信息失败,Err:" + err.Error()
		return
	}
	updateCol := make([]string, 0)

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

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

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

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

	} else {
		firstClassify, err := data_manage.GetFirstExcelClassifyByParentId(ExcelClassifyInfo.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 `
			_ = data_manage.UpdateExcelClassifySortByParentId(firstClassify.ParentId, firstClassify.ExcelClassifyId-1, 0, updateSortStr)
		}

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

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