package system

import (
	"strconv"

	"kra/internal/biz/system"

	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/transport/http"
)

// ParamsService 系统参数服务
type ParamsService struct {
	uc *system.ParamsUsecase
}

// NewParamsService 创建系统参数服务
func NewParamsService(uc *system.ParamsUsecase) *ParamsService {
	return &ParamsService{uc: uc}
}

// ParamsInfo 参数信息
type ParamsInfo struct {
	ID        uint   `json:"ID"`
	Name      string `json:"name"`
	Key       string `json:"key"`
	Value     string `json:"value"`
	Desc      string `json:"desc"`
	CreatedAt string `json:"createdAt,omitempty"`
	UpdatedAt string `json:"updatedAt,omitempty"`
}

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

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

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

// RegisterRoutes 注册路由
func (s *ParamsService) RegisterRoutes(rg *RouterGroup) {
	// 写操作（带操作记录）
	rg.PrivateWithRecord.POST("/sysParams/createSysParams", s.handleCreateParams)
	rg.PrivateWithRecord.DELETE("/sysParams/deleteSysParams", s.handleDeleteParams)
	rg.PrivateWithRecord.DELETE("/sysParams/deleteSysParamsByIds", s.handleDeleteParamsByIds)
	rg.PrivateWithRecord.PUT("/sysParams/updateSysParams", s.handleUpdateParams)

	// 读操作（不记录）
	rg.Private.GET("/sysParams/findSysParams", s.handleFindParams)
	rg.Private.GET("/sysParams/getSysParamsList", s.handleGetParamsList)
	rg.Private.GET("/sysParams/getSysParam", s.handleGetParamByKey)
}

// handleCreateParams 创建参数
func (s *ParamsService) handleCreateParams(ctx http.Context) error {
	var req CreateParamsRequest
	if err := ctx.Bind(&req); err != nil {
		return err
	}
	params := &system.Params{
		Name:  req.Name,
		Key:   req.Key,
		Value: req.Value,
		Desc:  req.Desc,
	}
	if err := s.uc.Create(ctx, params); err != nil {
		return errors.BadRequest("CREATE_FAILED", "创建失败:"+err.Error())
	}
	return ctx.Result(200, map[string]any{"code": 0, "msg": "创建成功"})
}

// handleDeleteParams 删除参数
func (s *ParamsService) handleDeleteParams(ctx http.Context) error {
	idStr := ctx.Query().Get("ID")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return errors.BadRequest("INVALID_ID", "无效的ID")
	}
	if err := s.uc.Delete(ctx, uint(id)); err != nil {
		return errors.BadRequest("DELETE_FAILED", "删除失败:"+err.Error())
	}
	return ctx.Result(200, map[string]any{"code": 0, "msg": "删除成功"})
}

// handleDeleteParamsByIds 批量删除参数
func (s *ParamsService) handleDeleteParamsByIds(ctx http.Context) error {
	idsStr := ctx.Query()["IDs[]"]
	if len(idsStr) == 0 {
		return errors.BadRequest("INVALID_IDS", "无效的IDs")
	}
	ids := make([]uint, 0, len(idsStr))
	for _, idStr := range idsStr {
		id, err := strconv.ParseUint(idStr, 10, 64)
		if err != nil {
			continue
		}
		ids = append(ids, uint(id))
	}
	if err := s.uc.DeleteByIds(ctx, ids); err != nil {
		return errors.BadRequest("DELETE_FAILED", "批量删除失败:"+err.Error())
	}
	return ctx.Result(200, map[string]any{"code": 0, "msg": "批量删除成功"})
}

// handleUpdateParams 更新参数
func (s *ParamsService) handleUpdateParams(ctx http.Context) error {
	var req UpdateParamsRequest
	if err := ctx.Bind(&req); err != nil {
		return err
	}
	params := &system.Params{
		ID:    req.ID,
		Name:  req.Name,
		Key:   req.Key,
		Value: req.Value,
		Desc:  req.Desc,
	}
	if err := s.uc.Update(ctx, params); err != nil {
		return errors.BadRequest("UPDATE_FAILED", "更新失败:"+err.Error())
	}
	return ctx.Result(200, map[string]any{"code": 0, "msg": "更新成功"})
}

// handleFindParams 根据ID查询参数
func (s *ParamsService) handleFindParams(ctx http.Context) error {
	idStr := ctx.Query().Get("ID")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		return errors.BadRequest("INVALID_ID", "无效的ID")
	}
	params, err := s.uc.GetByID(ctx, uint(id))
	if err != nil {
		return errors.NotFound("NOT_FOUND", "查询失败:"+err.Error())
	}
	return ctx.Result(200, map[string]any{"code": 0, "msg": "查询成功", "data": toParamsInfo(params)})
}

// handleGetParamsList 分页获取参数列表
func (s *ParamsService) handleGetParamsList(ctx http.Context) error {
	var req GetParamsListRequest
	if err := ctx.BindQuery(&req); err != nil {
		return err
	}
	if req.Page <= 0 {
		req.Page = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}
	filters := make(map[string]interface{})
	if req.Name != "" {
		filters["name"] = req.Name
	}
	if req.Key != "" {
		filters["key"] = req.Key
	}
	list, total, err := s.uc.GetList(ctx, req.Page, req.PageSize, filters)
	if err != nil {
		return errors.InternalServer("LIST_ERROR", "获取失败:"+err.Error())
	}
	result := make([]ParamsInfo, len(list))
	for i, p := range list {
		result[i] = toParamsInfo(p)
	}
	return ctx.Result(200, map[string]any{
		"code": 0,
		"msg":  "获取成功",
		"data": map[string]any{
			"list":     result,
			"total":    total,
			"page":     req.Page,
			"pageSize": req.PageSize,
		},
	})
}

// handleGetParamByKey 根据key获取参数
func (s *ParamsService) handleGetParamByKey(ctx http.Context) error {
	key := ctx.Query().Get("key")
	if key == "" {
		return errors.BadRequest("INVALID_KEY", "无效的key")
	}
	params, err := s.uc.GetByKey(ctx, key)
	if err != nil {
		return errors.NotFound("NOT_FOUND", "获取失败:"+err.Error())
	}
	return ctx.Result(200, map[string]any{"code": 0, "msg": "获取成功", "data": toParamsInfo(params)})
}

// toParamsInfo 转换为ParamsInfo
func toParamsInfo(p *system.Params) ParamsInfo {
	info := ParamsInfo{
		ID:    p.ID,
		Name:  p.Name,
		Key:   p.Key,
		Value: p.Value,
		Desc:  p.Desc,
	}
	if !p.CreatedAt.IsZero() {
		info.CreatedAt = p.CreatedAt.Format("2006-01-02 15:04:05")
	}
	if !p.UpdatedAt.IsZero() {
		info.UpdatedAt = p.UpdatedAt.Format("2006-01-02 15:04:05")
	}
	return info
}
