package system

import (
	"kra/internal/biz/system"
	"kra/pkg/response"

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

type ParamsApi struct{}

// CreateParamsRequest 创建参数请求
type CreateParamsRequest struct {
	Key   string `json:"key" binding:"required"`
	Value string `json:"value" binding:"required"`
	Name  string `json:"name"`
	Desc  string `json:"desc"`
}

// UpdateParamsRequest 更新参数请求
type UpdateParamsRequest struct {
	ID    uint   `json:"ID" binding:"required"`
	Key   string `json:"key" binding:"required"`
	Value string `json:"value" binding:"required"`
	Name  string `json:"name"`
	Desc  string `json:"desc"`
}

// DeleteParamsRequest 删除参数请求
type DeleteParamsRequest struct {
	ID uint `json:"ID" binding:"required"`
}

// GetParamsListRequest 获取参数列表请求
type GetParamsListRequest struct {
	Page     int    `json:"page"`
	PageSize int    `json:"pageSize"`
	Key      string `json:"key"`
	Name     string `json:"name"`
}

// CreateSysParams
// @Tags      SysParams
// @Summary   创建参数
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      CreateParamsRequest            true  "参数模型"
// @Success   200   {object}  response.Response{msg=string}  "创建参数"
// @Router    /sysParams/createSysParams [post]
func (p *ParamsApi) CreateSysParams(c *gin.Context) {
	var req CreateParamsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	params := &system.Params{
		Key:   req.Key,
		Value: req.Value,
		Name:  req.Name,
		Desc:  req.Desc,
	}

	if err := paramsUsecase.Create(c, params); err != nil {
		response.FailWithMessage("创建失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("创建成功", c)
}

// DeleteSysParams
// @Tags      SysParams
// @Summary   删除参数
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     ID    query     string                         true  "参数ID"
// @Success   200   {object}  response.Response{msg=string}  "删除参数"
// @Router    /sysParams/deleteSysParams [delete]
func (p *ParamsApi) DeleteSysParams(c *gin.Context) {
	ID := c.Query("ID")
	if ID == "" {
		response.FailWithMessage("参数错误", c)
		return
	}

	var id uint
	for _, ch := range ID {
		if ch >= '0' && ch <= '9' {
			id = id*10 + uint(ch-'0')
		}
	}

	if err := paramsUsecase.Delete(c, id); err != nil {
		response.FailWithMessage("删除失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("删除成功", c)
}

// DeleteSysParamsByIds
// @Tags      SysParams
// @Summary   批量删除参数
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     IDs[]  query     []string                       true  "参数ID列表"
// @Success   200    {object}  response.Response{msg=string}  "批量删除参数"
// @Router    /sysParams/deleteSysParamsByIds [delete]
func (p *ParamsApi) DeleteSysParamsByIds(c *gin.Context) {
	IDStrs := c.QueryArray("IDs[]")
	if len(IDStrs) == 0 {
		response.FailWithMessage("参数错误", c)
		return
	}

	// 转换字符串ID为uint
	ids := make([]uint, 0, len(IDStrs))
	for _, idStr := range IDStrs {
		var id uint
		for _, ch := range idStr {
			if ch >= '0' && ch <= '9' {
				id = id*10 + uint(ch-'0')
			}
		}
		if id > 0 {
			ids = append(ids, id)
		}
	}

	if err := paramsUsecase.DeleteByIds(c, ids); err != nil {
		response.FailWithMessage("批量删除失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("批量删除成功", c)
}

// UpdateSysParams
// @Tags      SysParams
// @Summary   更新参数
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      UpdateParamsRequest            true  "参数模型"
// @Success   200   {object}  response.Response{msg=string}  "更新参数"
// @Router    /sysParams/updateSysParams [put]
func (p *ParamsApi) UpdateSysParams(c *gin.Context) {
	var req UpdateParamsRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	params := &system.Params{
		ID:    req.ID,
		Key:   req.Key,
		Value: req.Value,
		Name:  req.Name,
		Desc:  req.Desc,
	}

	if err := paramsUsecase.Update(c, params); err != nil {
		response.FailWithMessage("更新失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("更新成功", c)
}

// GetSysParams
// @Tags      SysParams
// @Summary   根据Key获取参数
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     key   query     string                                                     true  "参数Key"
// @Success   200   {object}  response.Response{data=map[string]interface{},msg=string}  "获取参数"
// @Router    /sysParams/getSysParams [get]
func (p *ParamsApi) GetSysParams(c *gin.Context) {
	key := c.Query("key")
	if key == "" {
		response.FailWithMessage("参数错误", c)
		return
	}

	params, err := paramsUsecase.GetByKey(c, key)
	if err != nil {
		response.FailWithMessage("获取失败: "+err.Error(), c)
		return
	}

	response.OkWithDetailed(params, "获取成功", c)
}

// FindSysParams
// @Tags      SysParams
// @Summary   根据ID获取参数
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     ID    query     string                                                     true  "参数ID"
// @Success   200   {object}  response.Response{data=map[string]interface{},msg=string}  "获取参数"
// @Router    /sysParams/findSysParams [get]
func (p *ParamsApi) FindSysParams(c *gin.Context) {
	idStr := c.Query("ID")
	if idStr == "" {
		response.FailWithMessage("参数错误", c)
		return
	}

	var id uint
	for _, ch := range idStr {
		if ch >= '0' && ch <= '9' {
			id = id*10 + uint(ch-'0')
		}
	}

	params, err := paramsUsecase.GetByID(c, id)
	if err != nil {
		response.FailWithMessage("查询失败: "+err.Error(), c)
		return
	}

	response.OkWithData(params, c)
}

// GetSysParamsList
// @Tags      SysParams
// @Summary   分页获取参数列表
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      GetParamsListRequest                                    true  "页码, 每页大小, 搜索条件"
// @Success   200   {object}  response.Response{data=response.PageResult,msg=string}  "分页获取参数列表,返回包括列表,总数,页码,每页数量"
// @Router    /sysParams/getSysParamsList [post]
func (p *ParamsApi) GetSysParamsList(c *gin.Context) {
	var req GetParamsListRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		// GET请求使用默认值
		req.Page = 1
		req.PageSize = 10
	}

	if req.Page == 0 {
		req.Page = 1
	}
	if req.PageSize == 0 {
		req.PageSize = 10
	}

	filters := make(map[string]interface{})
	if req.Key != "" {
		filters["key"] = req.Key
	}
	if req.Name != "" {
		filters["name"] = req.Name
	}

	list, total, err := paramsUsecase.GetList(c, req.Page, req.PageSize, filters)
	if err != nil {
		response.FailWithMessage("获取失败", c)
		return
	}

	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     req.Page,
		PageSize: req.PageSize,
	}, "获取成功", c)
}
