package system

import (
	"time"

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

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

type ErrorApi struct{}

// SysErrorRequest 错误日志请求
type SysErrorRequest struct {
	ID       int64  `json:"id"`
	Form     string `json:"form" binding:"required"`
	Info     string `json:"info"`
	Level    string `json:"level"`
	Solution string `json:"solution"`
	Status   string `json:"status"`
}

// SysErrorSearchRequest 错误日志搜索请求
type SysErrorSearchRequest struct {
	Page           int         `json:"page" form:"page"`
	PageSize       int         `json:"pageSize" form:"pageSize"`
	Form           *string     `json:"form" form:"form"`
	Info           *string     `json:"info" form:"info"`
	CreatedAtRange []time.Time `json:"createdAtRange" form:"createdAtRange[]"`
}

// CreateSysError
// @Tags      SysError
// @Summary   创建错误日志
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      SysErrorRequest                true  "错误日志模型"
// @Success   200   {object}  response.Response{msg=string}  "创建错误日志"
// @Router    /sysError/createSysError [post]
func (e *ErrorApi) CreateSysError(c *gin.Context) {
	var req SysErrorRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	sysError := &system.SysError{
		Form:   req.Form,
		Info:   req.Info,
		Level:  req.Level,
		Status: "未处理",
	}

	if err := errorUsecase.CreateSysError(c.Request.Context(), sysError); err != nil {
		response.FailWithMessage("创建失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("创建成功", c)
}

// DeleteSysError
// @Tags      SysError
// @Summary   删除错误日志
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     ID    query     string                         true  "错误日志ID"
// @Success   200   {object}  response.Response{msg=string}  "删除错误日志"
// @Router    /sysError/deleteSysError [delete]
func (e *ErrorApi) DeleteSysError(c *gin.Context) {
	id := c.Query("ID")
	if id == "" {
		response.FailWithMessage("缺少参数: ID", c)
		return
	}

	if err := errorUsecase.DeleteSysError(c.Request.Context(), id); err != nil {
		response.FailWithMessage("删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("删除成功", c)
}

// DeleteSysErrorByIds
// @Tags      SysError
// @Summary   批量删除错误日志
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     IDs[]  query     []string                       true  "错误日志ID列表"
// @Success   200    {object}  response.Response{msg=string}  "批量删除错误日志"
// @Router    /sysError/deleteSysErrorByIds [delete]
func (e *ErrorApi) DeleteSysErrorByIds(c *gin.Context) {
	ids := c.QueryArray("IDs[]")
	if len(ids) == 0 {
		response.FailWithMessage("缺少参数: IDs", c)
		return
	}

	if err := errorUsecase.DeleteSysErrorByIds(c.Request.Context(), ids); err != nil {
		response.FailWithMessage("批量删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("批量删除成功", c)
}

// UpdateSysError
// @Tags      SysError
// @Summary   更新错误日志
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      SysErrorRequest                true  "错误日志模型"
// @Success   200   {object}  response.Response{msg=string}  "更新错误日志"
// @Router    /sysError/updateSysError [put]
func (e *ErrorApi) UpdateSysError(c *gin.Context) {
	var req SysErrorRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	sysError := &system.SysError{
		ID:       req.ID,
		Form:     req.Form,
		Info:     req.Info,
		Level:    req.Level,
		Solution: req.Solution,
		Status:   req.Status,
	}

	if err := errorUsecase.UpdateSysError(c.Request.Context(), sysError); err != nil {
		response.FailWithMessage("更新失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("更新成功", c)
}

// FindSysError
// @Tags      SysError
// @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    /sysError/findSysError [get]
func (e *ErrorApi) FindSysError(c *gin.Context) {
	id := c.Query("ID")
	if id == "" {
		response.FailWithMessage("缺少参数: ID", c)
		return
	}

	sysError, err := errorUsecase.GetSysError(c.Request.Context(), id)
	if err != nil {
		response.FailWithMessage("查询失败:"+err.Error(), c)
		return
	}
	response.OkWithData(toErrorResponse(sysError), c)
}

// GetSysErrorList
// @Tags      SysError
// @Summary   分页获取错误日志列表
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  query     SysErrorSearchRequest                                   true  "页码, 每页大小, 搜索条件"
// @Success   200   {object}  response.Response{data=response.PageResult,msg=string}  "分页获取错误日志列表,返回包括列表,总数,页码,每页数量"
// @Router    /sysError/getSysErrorList [get]
func (e *ErrorApi) GetSysErrorList(c *gin.Context) {
	var req SysErrorSearchRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

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

	searchReq := &system.ErrorSearchReq{
		Page:           req.Page,
		PageSize:       req.PageSize,
		Form:           req.Form,
		Info:           req.Info,
		CreatedAtRange: req.CreatedAtRange,
	}

	list, total, err := errorUsecase.GetSysErrorInfoList(c.Request.Context(), searchReq)
	if err != nil {
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}

	result := make([]map[string]interface{}, len(list))
	for i, item := range list {
		result[i] = toErrorResponse(item)
	}

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

// GetSysErrorSolution
// @Tags      SysError
// @Summary   触发AI处理错误日志
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     id    query     string                         true  "错误日志ID"
// @Success   200   {object}  response.Response{msg=string}  "已提交至AI处理"
// @Router    /sysError/getSysErrorSolution [get]
func (e *ErrorApi) GetSysErrorSolution(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		response.FailWithMessage("缺少参数: id", c)
		return
	}

	if err := errorUsecase.GetSysErrorSolution(c.Request.Context(), id); err != nil {
		response.FailWithMessage("处理触发失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("已提交至AI处理", c)
}

// toErrorResponse 转换错误日志响应
func toErrorResponse(e *system.SysError) map[string]interface{} {
	return map[string]interface{}{
		"id":        e.ID,
		"form":      e.Form,
		"info":      e.Info,
		"level":     e.Level,
		"solution":  e.Solution,
		"status":    e.Status,
		"createdAt": e.CreatedAt,
		"updatedAt": e.UpdatedAt,
	}
}
