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"
)

// 实例化控制层 SysConfigController 结构体
var NewSysConfig = &SysConfigController{
	sysConfigService: service.NewSysConfig,
}

// 参数配置信息
//
// PATH /system/config
type SysConfigController struct {
	// 参数配置服务
	sysConfigService *service.SysConfig // 参数配置服务
}

// 参数配置列表
//
// GET /list
//
//	@Tags			system/config
//	@Accept			json
//	@Produce		json
//	@Param			configName	query		string	false	"configName"
//	@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		Config Information List
//	@Description	Config Information List
//	@Router			/system/config/list [get]
func (s *SysConfigController) List(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	query := reqctx.QueryMap(c)
	// 多语言值转key查询
	if v, ok := query["configName"]; ok && v != "" {
		query["configName"] = i18n.TFindKeyPrefix(language, "config", v)
	}

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

	// 闭包函数处理多语言
	converI18n := func(language string, arr *[]model.SysConfig) {
		for i := range *arr {
			(*arr)[i].ConfigName = i18n.TKey(language, (*arr)[i].ConfigName)
			(*arr)[i].ConfigValue = i18n.TKey(language, (*arr)[i].ConfigValue)
			(*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 /:configId
func (s *SysConfigController) Info(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	configId := parse.Number(c.Param("configId"))
	if configId <= 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: configId is empty"))
		return
	}

	data := s.sysConfigService.FindById(configId)
	if data.ConfigId == configId {
		// 处理多语言
		data.ConfigName = i18n.TKey(language, data.ConfigName)
		data.ConfigValue = i18n.TKey(language, data.ConfigValue)
		data.Remark = i18n.TKey(language, data.Remark)
		c.JSON(200, resp.OkData(data))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 参数配置新增
//
// POST /
func (s *SysConfigController) Add(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body model.SysConfig
	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.ConfigId > 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: configId not is empty"))
		return
	}

	// 检查属性值唯一
	uniqueConfigKey := s.sysConfigService.CheckUniqueByKey(body.ConfigKey, 0)
	if !uniqueConfigKey {
		// msg := fmt.Sprintf("参数配置新增【%s】失败，参数键名已存在", body.ConfigKey)
		msg := i18n.TTemplate(language, "config.errKeyExists", map[string]any{"name": body.ConfigKey})
		c.JSON(200, resp.ErrMsg(msg))
		return
	}

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

// 参数配置修改
//
// PUT /
func (s *SysConfigController) Edit(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body model.SysConfig
	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.ConfigId <= 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: configId is empty"))
		return
	}

	// 检查是否存在
	configInfo := s.sysConfigService.FindById(body.ConfigId)
	if configInfo.ConfigId != body.ConfigId {
		// c.JSON(200, resp.ErrMsg("没有权限访问参数配置数据！"))
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "config.noData")))
		return
	}

	// 检查属性值唯一
	uniqueConfigKey := s.sysConfigService.CheckUniqueByKey(body.ConfigKey, body.ConfigId)
	if !uniqueConfigKey {
		// msg := fmt.Sprintf("参数配置修改【%s】失败，参数键名已存在", body.ConfigKey)
		msg := i18n.TTemplate(language, "config.errKeyExists", map[string]any{"name": body.ConfigKey})
		c.JSON(200, resp.ErrMsg(msg))
		return
	}

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

	configInfo.ConfigType = body.ConfigType
	configInfo.ConfigName = body.ConfigName
	configInfo.ConfigKey = body.ConfigKey
	configInfo.ConfigValue = body.ConfigValue
	configInfo.Remark = body.Remark
	configInfo.UpdateBy = reqctx.LoginUserToUserName(c)
	rows := s.sysConfigService.Update(configInfo)
	if rows > 0 {
		c.JSON(200, resp.Ok(nil))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// Remove 参数配置删除
//
// DELETE /:configId
func (s SysConfigController) Remove(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	configId := c.Param("configId")
	if configId == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: configId is empty"))
		return
	}

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

	rows, err := s.sysConfigService.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 SysConfigController) Refresh(c *gin.Context) {
	s.sysConfigService.CacheClean("*")
	s.sysConfigService.CacheLoad("*")
	c.JSON(200, resp.Ok(nil))
}

// ConfigKey 参数配置根据参数键名
//
// GET /config-key/:configKey
func (s SysConfigController) ConfigKey(c *gin.Context) {
	configKey := c.Param("configKey")
	if configKey == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: configKey is empty"))
		return
	}
	key := s.sysConfigService.FindValueByKey(configKey)
	if key != "" {
		c.JSON(200, resp.OkData(key))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// Export 导出参数配置信息
//
// GET /export
func (s SysConfigController) Export(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	query := reqctx.QueryMap(c)
	rows, total := s.sysConfigService.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.SysConfig) {
		for i := range *arr {
			(*arr)[i].ConfigName = i18n.TKey(language, (*arr)[i].ConfigName)
			(*arr)[i].ConfigValue = i18n.TKey(language, (*arr)[i].ConfigValue)
			(*arr)[i].Remark = i18n.TKey(language, (*arr)[i].Remark)
		}
	}
	converI18n(language, &rows)

	// 导出文件名称
	fileName := fmt.Sprintf("config_export_%d_%d.xlsx", len(rows), time.Now().UnixMilli())
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": i18n.TKey(language, "config..export.id"),
		"B1": i18n.TKey(language, "config..export.name"),
		"C1": i18n.TKey(language, "config..export.key"),
		"D1": i18n.TKey(language, "config..export.value"),
		"E1": i18n.TKey(language, "config..export.type"),
		"F1": i18n.TKey(language, "config..export.remark"),
	}
	// 从第二行开始的数据
	dataCells := make([]map[string]any, 0)
	for i, row := range rows {
		idx := strconv.Itoa(i + 2)
		typeValue := i18n.TKey(language, "dictData.no")
		if row.ConfigType == "Y" {
			typeValue = i18n.TKey(language, "dictData.yes")
		}
		dataCells = append(dataCells, map[string]any{
			"A" + idx: row.ConfigId,
			"B" + idx: row.ConfigName,
			"C" + idx: row.ConfigKey,
			"D" + idx: row.ConfigValue,
			"E" + idx: typeValue,
			"F" + idx: row.Remark,
		})
	}

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

	c.FileAttachment(saveFilePath, fileName)
}

// 参数配置修改配置参数
//
// PUT /change-value
func (s *SysConfigController) ConfigValue(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body struct {
		Key   string `json:"key" binding:"required"`
		Value string `json:"value" binding:"required"`
	}
	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
	}

	// 检查是否存在
	info := s.sysConfigService.FindByKey(body.Key)
	if info.ConfigKey != body.Key {
		// 无效 key
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "config.errKey")))
		return
	}

	// 与旧值相等 不变更
	i18nValue := i18n.TKey(language, info.ConfigValue)
	if i18nValue == body.Value {
		// 变更状态与旧值相等！
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "config.errValueEq")))
		return
	}

	// 多语言非原始值
	if i18nValue != info.ConfigValue {
		service.NewSysI18n.UpdateKeyValue(language, info.ConfigValue, body.Value)
	} else {
		info.ConfigValue = body.Value
	}

	info.UpdateBy = reqctx.LoginUserToUserName(c)
	rows := s.sysConfigService.Update(info)
	if rows > 0 {
		c.JSON(200, resp.Ok(nil))
		return
	}
	c.JSON(200, resp.Err(nil))
}
