package controller

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"ems.agt/src/framework/utils/ctx"
	"ems.agt/src/framework/utils/file"
	"ems.agt/src/framework/utils/parse"
	"ems.agt/src/framework/vo/result"
	"ems.agt/src/modules/system/model"
	"ems.agt/src/modules/system/service"

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

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

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

// 参数配置列表
//
// GET /list
func (s *SysConfigController) List(c *gin.Context) {
	querys := ctx.QueryMap(c)
	data := s.sysConfigService.SelectConfigPage(querys)
	c.JSON(200, result.Ok(data))
}

// 参数配置信息
//
// GET /:configId
func (s *SysConfigController) Info(c *gin.Context) {
	configId := c.Param("configId")
	if configId == "" {
		c.JSON(400, result.CodeMsg(400, "parameter error"))
		return
	}
	data := s.sysConfigService.SelectConfigById(configId)
	if data.ConfigID == configId {
		c.JSON(200, result.OkData(data))
		return
	}
	c.JSON(200, result.Err(nil))
}

// 参数配置新增
//
// POST /
func (s *SysConfigController) Add(c *gin.Context) {
	var body model.SysConfig
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil || body.ConfigID != "" {
		c.JSON(400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查属性值唯一
	uniqueConfigKey := s.sysConfigService.CheckUniqueConfigKey(body.ConfigKey, "")
	if !uniqueConfigKey {
		// 参数配置新增【%s】失败，参数键名已存在
		msg := fmt.Sprintf("Parameter configuration add [%s] failed, parameter key name already exists", body.ConfigKey)
		c.JSON(200, result.ErrMsg(msg))
		return
	}

	body.CreateBy = ctx.LoginUserToUserName(c)
	insertId := s.sysConfigService.InsertConfig(body)
	if insertId != "" {
		c.JSON(200, result.Ok(nil))
		return
	}
	c.JSON(200, result.Err(nil))
}

// 参数配置修改
//
// PUT /
func (s *SysConfigController) Edit(c *gin.Context) {
	var body model.SysConfig
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil || body.ConfigID == "" {
		c.JSON(400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查属性值唯一
	uniqueConfigKey := s.sysConfigService.CheckUniqueConfigKey(body.ConfigKey, body.ConfigID)
	if !uniqueConfigKey {
		// 参数配置修改【%s】失败，参数键名已存在
		msg := fmt.Sprintf("Parameter configuration modification [%s] failed, parameter key name already exists", body.ConfigKey)
		c.JSON(200, result.ErrMsg(msg))
		return
	}

	// 检查是否存在
	config := s.sysConfigService.SelectConfigById(body.ConfigID)
	if config.ConfigID != body.ConfigID {
		// 没有可访问参数配置数据！
		c.JSON(200, result.ErrMsg("There is no accessible parameter configuration data!"))
		return
	}

	body.UpdateBy = ctx.LoginUserToUserName(c)
	rows := s.sysConfigService.UpdateConfig(body)
	if rows > 0 {
		c.JSON(200, result.Ok(nil))
		return
	}
	c.JSON(200, result.Err(nil))
}

// 参数配置删除
//
// DELETE /:configIds
func (s *SysConfigController) Remove(c *gin.Context) {
	configIds := c.Param("configIds")
	if configIds == "" {
		c.JSON(400, result.CodeMsg(400, "parameter error"))
		return
	}
	// 处理字符转id数组后去重
	ids := strings.Split(configIds, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		c.JSON(200, result.Err(nil))
		return
	}
	rows, err := s.sysConfigService.DeleteConfigByIds(uniqueIDs)
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}
	msg := fmt.Sprintf("Deleted successfully: %d", rows)
	c.JSON(200, result.OkMsg(msg))
}

// 参数配置刷新缓存
//
// PUT /refreshCache
func (s *SysConfigController) RefreshCache(c *gin.Context) {
	s.sysConfigService.ResetConfigCache()
	c.JSON(200, result.Ok(nil))
}

// 参数配置根据参数键名
//
// GET /configKey/:configKey
func (s *SysConfigController) ConfigKey(c *gin.Context) {
	configKey := c.Param("configKey")
	if configKey == "" {
		c.JSON(400, result.CodeMsg(400, "parameter error"))
		return
	}
	key := s.sysConfigService.SelectConfigValueByKey(configKey)
	if key != "" {
		c.JSON(200, result.OkData(key))
		return
	}
	c.JSON(200, result.Err(nil))
}

// 导出参数配置信息
//
// POST /export
func (s *SysConfigController) Export(c *gin.Context) {
	// 查询结果，根据查询条件结果，单页最大值限制
	querys := ctx.BodyJSONMap(c)
	data := s.sysConfigService.SelectConfigPage(querys)
	if data["total"].(int64) == 0 {
		// 导出数据记录为空
		c.JSON(200, result.ErrMsg("Export data record is empty"))
		return
	}
	rows := data["rows"].([]model.SysConfig)

	// 导出文件名称
	fileName := fmt.Sprintf("config_export_%d_%d.xlsx", len(rows), time.Now().UnixMilli())
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": "ConfigID",
		"B1": "ConfigName",
		"C1": "ConfigKey",
		"D1": "ConfigValue",
		"E1": "Type",
	}
	// 从第二行开始的数据
	dataCells := make([]map[string]any, 0)
	for i, row := range rows {
		idx := strconv.Itoa(i + 2)
		typeValue := "clogged"
		if row.ConfigType == "Y" {
			typeValue = "be"
		}
		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,
		})
	}

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

	c.FileAttachment(saveFilePath, fileName)
}

// 参数配置修改配置参数
//
// PUT /changeConfigValue
func (s *SysConfigController) ConfigValue(c *gin.Context) {
	var body struct {
		Key   string `json:"key" binding:"required"`
		Value string `json:"value" binding:"required"`
	}
	if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
		c.JSON(400, result.CodeMsg(400, "parameter error"))
		return
	}

	// 检查是否存在
	info := s.sysConfigService.SelectConfigByKey(body.Key)
	if info.ConfigKey != body.Key {
		// 无效 key
		c.JSON(200, result.ErrMsg("Invalid key"))
		return
	}

	// 与旧值相等不变更
	if info.ConfigValue == body.Value {
		// 变更状态与旧值相等！
		c.JSON(200, result.ErrMsg("The change status is equal to the old value!"))
		return
	}
	info.ConfigValue = body.Value
	info.UpdateBy = ctx.LoginUserToUserName(c)
	rows := s.sysConfigService.UpdateConfig(info)
	if rows > 0 {
		c.JSON(200, result.Ok(nil))
		return
	}
	c.JSON(200, result.Err(nil))
}
