package controller

import (
	"fmt"
	"strconv"
	"time"

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/reqctx"
	"be.ems/src/framework/resp"
	"be.ems/src/framework/utils/file"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/modules/system/model"
	"be.ems/src/modules/system/service"

	"github.com/gin-gonic/gin"
)

// 实例化控制层 SysDictTypeController 结构体
var NewSysDictType = &SysDictTypeController{
	sysDictTypeService: service.NewSysDictType,
}

// 字典类型信息
//
// PATH /system/dict/type
type SysDictTypeController struct {
	sysDictTypeService *service.SysDictType // 字典类型服务
}

// 字典类型列表
//
// GET /list
//
//	@Tags			system/dict/type
//	@Accept			json
//	@Produce		json
//	@Param			dictName	query		string	false	"dictName"
//	@Param			pageNum		query		number	true	"pageNum"	default(1)
//	@Param			pageSize	query		number	true	"pageSize"	default(10)
//	@Success		200			{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		Dictionary Type List
//	@Description	Dictionary Type List
//	@Router			/system/dict/type/list [get]
func (s *SysDictTypeController) List(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	query := reqctx.QueryMap(c)

	// 多语言值转key查询
	if v, ok := query["dictName"]; ok && v != "" {
		query["dictName"] = i18n.TFindKeyPrefix(language, "dictType", v)
	}

	rows, total := s.sysDictTypeService.FindByPage(query)

	// 闭包函数处理多语言
	converI18n := func(language string, arr *[]model.SysDictType) {
		for i := range *arr {
			(*arr)[i].DictName = i18n.TKey(language, (*arr)[i].DictName)
			(*arr)[i].Remark = i18n.TKey(language, (*arr)[i].Remark)
		}
	}
	converI18n(language, &rows)

	c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}

// 字典类型信息
//
// GET /:dictId
func (s *SysDictTypeController) Info(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	dictId := parse.Number(c.Param("dictId"))
	if dictId <= 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: dictId is empty"))
		return
	}
	data := s.sysDictTypeService.FindById(dictId)
	if data.DictId == dictId {
		// 处理多语言
		data.DictName = i18n.TKey(language, data.DictName)
		data.Remark = i18n.TKey(language, data.Remark)
		c.JSON(200, resp.OkData(data))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 字典类型新增
//
// POST /
func (s *SysDictTypeController) Add(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body model.SysDictType
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	if body.DictId > 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: dictId not is empty"))
		return
	}

	// 检查字典名称唯一
	uniqueName := s.sysDictTypeService.CheckUniqueByName(body.DictName, 0)
	if !uniqueName {
		// msg := fmt.Sprintf("字典新增【%s】失败，字典名称已存在", body.DictName)
		msg := i18n.TTemplate(language, "dictType.errNameExists", map[string]any{"name": body.DictName})
		c.JSON(200, resp.ErrMsg(msg))
		return
	}

	// 检查字典类型唯一
	uniqueType := s.sysDictTypeService.CheckUniqueByType(body.DictType, 0)
	if !uniqueType {
		// msg := fmt.Sprintf("字典新增【%s】失败，字典类型已存在", body.DictName)
		msg := i18n.TTemplate(language, "dictType.errTypeExists", map[string]any{"name": body.DictName})
		c.JSON(200, resp.ErrMsg(msg))
		return
	}

	body.CreateBy = reqctx.LoginUserToUserName(c)
	insertId := s.sysDictTypeService.Insert(body)
	if insertId > 0 {
		c.JSON(200, resp.OkData(insertId))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 字典类型修改
//
// PUT /
func (s *SysDictTypeController) Edit(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body model.SysDictType
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	if body.DictId <= 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: dictId is empty"))
		return
	}

	// 检查数据是否存在
	dictTypeInfo := s.sysDictTypeService.FindById(body.DictId)
	if dictTypeInfo.DictId != body.DictId {
		// c.JSON(200, resp.ErrMsg("没有权限访问字典类型数据！"))
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "dictType.noData")))
		return
	}

	// 检查字典名称唯一
	uniqueName := s.sysDictTypeService.CheckUniqueByName(body.DictName, body.DictId)
	if !uniqueName {
		// msg := fmt.Sprintf("字典修改【%s】失败，字典名称已存在", body.DictName)
		msg := i18n.TTemplate(language, "dictType.errNameExists", map[string]any{"name": body.DictName})
		c.JSON(200, resp.ErrMsg(msg))
		return
	}

	// 检查字典类型唯一
	uniqueType := s.sysDictTypeService.CheckUniqueByType(body.DictType, body.DictId)
	if !uniqueType {
		// msg := fmt.Sprintf("字典修改【%s】失败，字典类型已存在", body.DictName)
		msg := i18n.TTemplate(language, "dictType.errTypeExists", map[string]any{"name": body.DictName})
		c.JSON(200, resp.ErrMsg(msg))
		return
	}

	// 多语言非原始值
	i18nValue := i18n.TKey(language, dictTypeInfo.DictName)
	if i18nValue != dictTypeInfo.DictName {
		service.NewSysI18n.UpdateKeyValue(language, dictTypeInfo.DictName, body.DictName)
		body.DictName = dictTypeInfo.DictName
	}
	// 多语言非原始值
	i18nValue2 := i18n.TKey(language, dictTypeInfo.Remark)
	if i18nValue2 != dictTypeInfo.Remark {
		service.NewSysI18n.UpdateKeyValue(language, dictTypeInfo.Remark, body.Remark)
		body.Remark = dictTypeInfo.Remark
	}

	dictTypeInfo.DictName = body.DictName
	dictTypeInfo.DictType = body.DictType
	dictTypeInfo.StatusFlag = body.StatusFlag
	dictTypeInfo.Remark = body.Remark
	dictTypeInfo.UpdateBy = reqctx.LoginUserToUserName(c)
	rows := s.sysDictTypeService.Update(dictTypeInfo)
	if rows > 0 {
		c.JSON(200, resp.Ok(nil))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// Remove 字典类型删除
//
// DELETE /:dictId
func (s SysDictTypeController) Remove(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	dictId := c.Param("dictId")
	if dictId == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: dictId is empty"))
		return
	}

	// 处理字符转id数组后去重
	uniqueIDs := parse.RemoveDuplicatesToArray(dictId, ",")
	// 转换成int64数组类型
	ids := make([]int64, 0)
	for _, v := range uniqueIDs {
		ids = append(ids, parse.Number(v))
	}

	rows, err := s.sysDictTypeService.DeleteByIds(ids)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	// msg := fmt.Sprintf("删除成功：%d", rows)
	msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
	c.JSON(200, resp.OkMsg(msg))
}

// Refresh 字典类型刷新缓存
//
// PUT /refresh
func (s SysDictTypeController) Refresh(c *gin.Context) {
	// 重新加载-字典数据
	s.sysDictTypeService.CacheClean("*")
	s.sysDictTypeService.CacheLoad("*")
	// 重新加载-多语言
	service.NewSysI18n.CacheClean("*")
	service.NewSysI18n.CacheLoad("*")
	c.JSON(200, resp.Ok(nil))
}

// 字典类型选择框列表
//
// GET /options
func (s *SysDictTypeController) Options(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	data := s.sysDictTypeService.Find(model.SysDictType{})

	type labelValue struct {
		Label string `json:"label"`
		Value string `json:"value"`
	}

	// 数据组
	arr := make([]labelValue, 0)
	for _, v := range data {
		arr = append(arr, labelValue{
			Label: i18n.TKey(language, v.DictName),
			Value: v.DictType,
		})
	}
	c.JSON(200, resp.OkData(arr))
}

// Export 字典类型列表导出
//
// GET /export
func (s SysDictTypeController) Export(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	query := reqctx.QueryMap(c)
	rows, total := s.sysDictTypeService.FindByPage(query)
	if total == 0 {
		// c.JSON(200, resp.CodeMsg(40016, "export data record as empty"))
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}

	// 闭包函数处理多语言
	converI18n := func(language string, arr *[]model.SysDictType) {
		for i := range *arr {
			(*arr)[i].DictName = i18n.TKey(language, (*arr)[i].DictName)
			(*arr)[i].Remark = i18n.TKey(language, (*arr)[i].Remark)
		}
	}
	converI18n(language, &rows)

	// 导出文件名称
	fileName := fmt.Sprintf("dict_type_export_%d_%d.xlsx", len(rows), time.Now().UnixMilli())
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": i18n.TKey(language, "dictType.export.id"),
		"B1": i18n.TKey(language, "dictType.export.name"),
		"C1": i18n.TKey(language, "dictType.export.type"),
		"D1": i18n.TKey(language, "dictType.export.status"),
	}
	// 从第二行开始的数据
	dataCells := make([]map[string]any, 0)
	for i, row := range rows {
		idx := strconv.Itoa(i + 2)
		statusValue := i18n.TKey(language, "dictData.disable")
		if row.StatusFlag == "1" {
			statusValue = i18n.TKey(language, "dictData.normal")
		}
		dataCells = append(dataCells, map[string]any{
			"A" + idx: row.DictId,
			"B" + idx: row.DictName,
			"C" + idx: row.DictType,
			"D" + idx: statusValue,
		})
	}

	// 导出数据表格
	saveFilePath, err := file.WriteSheet(headerCells, dataCells, fileName, "")
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

	c.FileAttachment(saveFilePath, fileName)
}
