package my_chart

import (
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/models/request"
	responseModel "hongze/hongze_yb/models/response"
	"hongze/hongze_yb/models/tables/yb_my_chart"
	"hongze/hongze_yb/models/tables/yb_my_chart_classify"
	userService "hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"time"
)

// MyChartClassifyController 用户-我的图表分类
type MyChartClassifyController struct{}

func (this *MyChartClassifyController) List(c *gin.Context) {
	userInfo := userService.GetInfoByClaims(c)
	userId := int(userInfo.UserID)
	if userId <= 0 {
		response.Fail("请登录后查看", c)
		return
	}

	cond := `user_id = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, userId)
	ob := new(yb_my_chart_classify.YbMyChartClassify)
	list, e := ob.List(cond, pars)
	if e != nil {
		response.FailMsg("获取失败", "获取用户图表分类失败, Err: "+e.Error(), c)
		return
	}
	respList := make([]*responseModel.MyChartClassifyItem, 0)
	// 新增一个默认分类
	respList = append(respList, &responseModel.MyChartClassifyItem{
		MyChartClassifyID:   -1,
		MyChartClassifyName: "未分类",
		Sort:                -1,
		UserID:              userId,
		CreateTime:          utils.TimeTransferString(utils.FormatDateTime, time.Now().Local()),
	})
	for i := range list {
		respList = append(respList, &responseModel.MyChartClassifyItem{
			MyChartClassifyID:   list[i].MyChartClassifyID,
			MyChartClassifyName: list[i].MyChartClassifyName,
			Sort:                list[i].Sort,
			UserID:              list[i].UserID,
			CreateTime:          utils.TimeTransferString(utils.FormatDateTime, list[i].CreateTime),
		})
	}
	response.OkData("获取成功", respList, c)
}

func (this *MyChartClassifyController) Add(c *gin.Context) {
	userInfo := userService.GetInfoByClaims(c)
	userId := int(userInfo.UserID)
	if userId <= 0 {
		response.Fail("请登录后操作", c)
		return
	}
	var req request.MyChartClassifyAddReq
	if c.ShouldBind(&req) != nil {
		response.Fail("参数有误", c)
		return
	}
	if req.ClassifyName == "" {
		response.Fail("请输入分类名称", c)
		return
	}
	if len([]rune(req.ClassifyName)) > 10 {
		response.Fail("分类名称不可超过10个字符", c)
		return
	}

	cond := `my_chart_classify_name = ? AND user_id = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, req.ClassifyName, userId)
	ob := new(yb_my_chart_classify.YbMyChartClassify)
	exists, e := ob.FetchByCondition(cond, pars)
	if e != nil && e != utils.ErrNoRow {
		response.FailMsg("操作失败", "获取用户同名图表分类失败, Err: "+e.Error(), c)
		return
	}
	if exists != nil && exists.MyChartClassifyID > 0 {
		response.Fail("分类名称已存在", c)
		return
	}

	nowTime := time.Now().Local()
	ob.MyChartClassifyName = req.ClassifyName
	ob.UserID = userId
	ob.CreateTime = nowTime
	ob.ModifyTime = nowTime
	if e = ob.Create(); e != nil {
		response.FailMsg("操作失败", "新增用户图表分类失败, Err: "+e.Error(), c)
		return
	}
	response.Ok("操作成功", c)
}

func (this *MyChartClassifyController) Edit(c *gin.Context) {
	userInfo := userService.GetInfoByClaims(c)
	userId := int(userInfo.UserID)
	if userId <= 0 {
		response.Fail("请登录后操作", c)
		return
	}
	var req request.MyChartClassifyEditReq
	if c.ShouldBind(&req) != nil {
		response.Fail("参数有误", c)
		return
	}
	if req.ClassifyId <= 0 {
		response.Fail("请选择分类", c)
		return
	}
	if req.ClassifyName == "" {
		response.Fail("请输入分类名称", c)
		return
	}
	if len([]rune(req.ClassifyName)) > 10 {
		response.Fail("分类名称不可超过10个字符", c)
		return
	}

	cond := `my_chart_classify_name = ? AND user_id = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, req.ClassifyName, userId)
	ob := new(yb_my_chart_classify.YbMyChartClassify)
	exists, e := ob.FetchByCondition(cond, pars)
	if e != nil && e != utils.ErrNoRow {
		response.FailMsg("操作失败", "获取用户同名图表分类失败, Err: "+e.Error(), c)
		return
	}
	if exists != nil && exists.MyChartClassifyID > 0 && exists.MyChartClassifyID != req.ClassifyId {
		response.Fail("分类名称已存在", c)
		return
	}

	item, e := ob.Fetch(req.ClassifyId)
	if e != nil {
		response.FailMsg("信息有误", "获取用户图表分类失败, Err: "+e.Error(), c)
		return
	}
	item.MyChartClassifyName = req.ClassifyName
	item.ModifyTime = time.Now().Local()
	if e = item.Update([]string{"MyChartClassifyName", "ModifyTime"}); e != nil {
		response.FailMsg("操作失败", "编辑用户图表分类失败, Err: "+e.Error(), c)
		return
	}
	response.Ok("操作成功", c)
}

func (this *MyChartClassifyController) Del(c *gin.Context) {
	userInfo := userService.GetInfoByClaims(c)
	userId := int(userInfo.UserID)
	if userId <= 0 {
		response.Fail("请登录后操作", c)
		return
	}
	var req request.MyChartClassifyDelReq
	if c.ShouldBind(&req) != nil {
		response.Fail("参数有误", c)
		return
	}
	if req.ClassifyId <= 0 {
		response.Fail("请选择分类", c)
		return
	}

	ob := new(yb_my_chart_classify.YbMyChartClassify)
	item, e := ob.Fetch(req.ClassifyId)
	if e != nil {
		response.FailMsg("分类不存在或已被删除", "获取用户图表分类失败, Err: "+e.Error(), c)
		return
	}
	if item.UserID != userId {
		response.Fail("无权操作", c)
		return
	}
	// 是否存在关联图表
	condRelate := `my_chart_classify_id = ?`
	parsRelate := make([]interface{}, 0)
	parsRelate = append(parsRelate, req.ClassifyId)
	chartOB := new(yb_my_chart.YbMyChart)
	count, e := chartOB.Count(condRelate, parsRelate)
	if e != nil {
		response.FailMsg("操作失败", "获取用户图表分类关联数失败, Err: "+e.Error(), c)
		return
	}
	if count > 0 {
		response.SpecificFail("", "删除失败, 该分类下有图表", c)
		return
	}
	if e = item.Delete(); e != nil {
		response.FailMsg("操作失败", "删除分类失败, Err: "+e.Error(), c)
		return
	}
	response.Ok("操作成功", c)
}

func (this *MyChartClassifyController) Sort(c *gin.Context) {
	userInfo := userService.GetInfoByClaims(c)
	userId := int(userInfo.UserID)
	if userId <= 0 {
		response.Fail("请登录后操作", c)
		return
	}
	var req []request.MyChartClassifySortReq
	if c.ShouldBind(&req) != nil {
		response.Fail("参数有误", c)
		return
	}
	if len(req) == 0 {
		response.Fail("请选择排序分类", c)
		return
	}
	sortMap := make(map[int]int)
	classifyIds := make([]int, 0)
	for i := range req {
		classifyIds = append(classifyIds, req[i].ClassifyId)
		sortMap[req[i].ClassifyId] = req[i].Sort
	}

	cond := `my_chart_classify_id IN ?`
	pars := make([]interface{}, 0)
	pars = append(pars, classifyIds)
	ob := new(yb_my_chart_classify.YbMyChartClassify)
	list, e := ob.List(cond, pars)
	if e != nil {
		response.FailMsg("操作失败", "获取用户分类列表失败, Err: "+e.Error(), c)
		return
	}
	nowTime := time.Now().Local()
	updateCols := []string{"Sort", "ModifyTime"}
	for i := range list {
		list[i].Sort = sortMap[list[i].MyChartClassifyID]
		list[i].ModifyTime = nowTime
		if e = list[i].Update(updateCols); e != nil {
			response.FailMsg("操作失败", "更新用户分类排序失败, Err: "+e.Error(), c)
			return
		}
	}
	response.Ok("操作成功", c)
}
