package system

import (
	"strconv"

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

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

type DictionaryDetailApi struct{}

// DictionaryDetailRequest 字典详情请求
type DictionaryDetailRequest struct {
	ID              uint   `json:"id"`
	Label           string `json:"label"`
	Value           string `json:"value"`
	Extend          string `json:"extend"`
	Status          *bool  `json:"status"`
	Sort            int    `json:"sort"`
	SysDictionaryID uint   `json:"sysDictionaryID"`
	ParentID        *uint  `json:"parentId"`
}

// DictionaryDetailSearchRequest 字典详情搜索请求
type DictionaryDetailSearchRequest struct {
	Page            int    `json:"page" form:"page"`
	PageSize        int    `json:"pageSize" form:"pageSize"`
	Label           string `json:"label" form:"label"`
	Value           string `json:"value" form:"value"`
	Status          *bool  `json:"status" form:"status"`
	SysDictionaryID uint   `json:"sysDictionaryID" form:"sysDictionaryID"`
	ParentID        *uint  `json:"parentId" form:"parentId"`
	Level           *int   `json:"level" form:"level"`
}

// GetDictionaryDetailsByParentRequest 根据父级获取字典详情请求
type GetDictionaryDetailsByParentRequest struct {
	SysDictionaryID uint  `json:"sysDictionaryID" form:"sysDictionaryID" binding:"required"`
	ParentID        *uint `json:"parentId" form:"parentId"`
	IncludeChildren bool  `json:"includeChildren" form:"includeChildren"`
}

// CreateSysDictionaryDetail
// @Tags      SysDictionaryDetail
// @Summary   创建SysDictionaryDetail
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      DictionaryDetailRequest        true  "SysDictionaryDetail模型"
// @Success   200   {object}  response.Response{msg=string}  "创建SysDictionaryDetail"
// @Router    /sysDictionaryDetail/createSysDictionaryDetail [post]
func (d *DictionaryDetailApi) CreateSysDictionaryDetail(c *gin.Context) {
	var req DictionaryDetailRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	detail := &system.DictionaryDetail{
		Label:           req.Label,
		Value:           req.Value,
		Extend:          req.Extend,
		Status:          req.Status,
		Sort:            req.Sort,
		SysDictionaryID: req.SysDictionaryID,
		ParentID:        req.ParentID,
	}

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

// DeleteSysDictionaryDetail
// @Tags      SysDictionaryDetail
// @Summary   删除SysDictionaryDetail
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      DictionaryDetailRequest        true  "SysDictionaryDetail模型"
// @Success   200   {object}  response.Response{msg=string}  "删除SysDictionaryDetail"
// @Router    /sysDictionaryDetail/deleteSysDictionaryDetail [delete]
func (d *DictionaryDetailApi) DeleteSysDictionaryDetail(c *gin.Context) {
	var req DictionaryDetailRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

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

// UpdateSysDictionaryDetail
// @Tags      SysDictionaryDetail
// @Summary   更新SysDictionaryDetail
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      DictionaryDetailRequest        true  "更新SysDictionaryDetail"
// @Success   200   {object}  response.Response{msg=string}  "更新SysDictionaryDetail"
// @Router    /sysDictionaryDetail/updateSysDictionaryDetail [put]
func (d *DictionaryDetailApi) UpdateSysDictionaryDetail(c *gin.Context) {
	var req DictionaryDetailRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	detail := &system.DictionaryDetail{
		ID:              req.ID,
		Label:           req.Label,
		Value:           req.Value,
		Extend:          req.Extend,
		Status:          req.Status,
		Sort:            req.Sort,
		SysDictionaryID: req.SysDictionaryID,
		ParentID:        req.ParentID,
	}

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

// FindSysDictionaryDetail
// @Tags      SysDictionaryDetail
// @Summary   用id查询SysDictionaryDetail
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     ID    query     string                                                     true  "用id查询SysDictionaryDetail"
// @Success   200   {object}  response.Response{data=map[string]interface{},msg=string}  "用id查询SysDictionaryDetail"
// @Router    /sysDictionaryDetail/findSysDictionaryDetail [get]
func (d *DictionaryDetailApi) FindSysDictionaryDetail(c *gin.Context) {
	idStr := c.Query("ID")
	if idStr == "" {
		response.FailWithMessage("缺少参数: ID", c)
		return
	}
	id, _ := strconv.ParseUint(idStr, 10, 32)

	detail, err := dictionaryUsecase.GetDictionaryDetail(c.Request.Context(), uint(id))
	if err != nil {
		response.FailWithMessage("查询失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(gin.H{"reSysDictionaryDetail": toDictionaryDetailResponse(detail)}, "查询成功", c)
}

// GetSysDictionaryDetailList
// @Tags      SysDictionaryDetail
// @Summary   分页获取SysDictionaryDetail列表
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  query     DictionaryDetailSearchRequest                           true  "页码, 每页大小, 搜索条件"
// @Success   200   {object}  response.Response{data=response.PageResult,msg=string}  "分页获取SysDictionaryDetail列表,返回包括列表,总数,页码,每页数量"
// @Router    /sysDictionaryDetail/getSysDictionaryDetailList [get]
func (d *DictionaryDetailApi) GetSysDictionaryDetailList(c *gin.Context) {
	var req DictionaryDetailSearchRequest
	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
	}

	filters := make(map[string]interface{})
	if req.Label != "" {
		filters["label"] = req.Label
	}
	if req.Value != "" {
		filters["value"] = req.Value
	}
	if req.Status != nil {
		filters["status"] = req.Status
	}
	if req.SysDictionaryID != 0 {
		filters["sysDictionaryID"] = req.SysDictionaryID
	}
	if req.ParentID != nil {
		filters["parentId"] = req.ParentID
	}
	if req.Level != nil {
		filters["level"] = req.Level
	}

	list, total, err := dictionaryUsecase.GetDictionaryDetailList(c.Request.Context(), req.Page, req.PageSize, filters)
	if err != nil {
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}

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

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

// GetDictionaryTreeList
// @Tags      SysDictionaryDetail
// @Summary   获取字典详情树形结构
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     sysDictionaryID  query     int                                                              true  "字典ID"
// @Success   200              {object}  response.Response{data=map[string]interface{},msg=string}        "获取字典详情树形结构"
// @Router    /sysDictionaryDetail/getDictionaryTreeList [get]
func (d *DictionaryDetailApi) GetDictionaryTreeList(c *gin.Context) {
	sysDictionaryID := c.Query("sysDictionaryID")
	if sysDictionaryID == "" {
		response.FailWithMessage("字典ID不能为空", c)
		return
	}

	id, err := strconv.ParseUint(sysDictionaryID, 10, 32)
	if err != nil {
		response.FailWithMessage("字典ID格式错误", c)
		return
	}

	list, err := dictionaryUsecase.GetDictionaryTreeList(c.Request.Context(), uint(id))
	if err != nil {
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(gin.H{"list": toDictionaryDetailTreeResponse(list)}, "获取成功", c)
}

// GetDictionaryTreeListByType
// @Tags      SysDictionaryDetail
// @Summary   根据字典类型获取字典详情树形结构
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     type  query     string                                                     true  "字典类型"
// @Success   200   {object}  response.Response{data=map[string]interface{},msg=string}  "获取字典详情树形结构"
// @Router    /sysDictionaryDetail/getDictionaryTreeListByType [get]
func (d *DictionaryDetailApi) GetDictionaryTreeListByType(c *gin.Context) {
	dictType := c.Query("type")
	if dictType == "" {
		response.FailWithMessage("字典类型不能为空", c)
		return
	}

	list, err := dictionaryUsecase.GetDictionaryTreeListByType(c.Request.Context(), dictType)
	if err != nil {
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(gin.H{"list": toDictionaryDetailTreeResponse(list)}, "获取成功", c)
}

// GetDictionaryDetailsByParent
// @Tags      SysDictionaryDetail
// @Summary   根据父级ID获取字典详情
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  query     GetDictionaryDetailsByParentRequest                        true  "查询参数"
// @Success   200   {object}  response.Response{data=map[string]interface{},msg=string}  "获取字典详情列表"
// @Router    /sysDictionaryDetail/getDictionaryDetailsByParent [get]
func (d *DictionaryDetailApi) GetDictionaryDetailsByParent(c *gin.Context) {
	var req GetDictionaryDetailsByParentRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	list, err := dictionaryUsecase.GetDictionaryDetailsByParent(c.Request.Context(), req.SysDictionaryID, req.ParentID, req.IncludeChildren)
	if err != nil {
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(gin.H{"list": toDictionaryDetailTreeResponse(list)}, "获取成功", c)
}

// GetDictionaryPath
// @Tags      SysDictionaryDetail
// @Summary   获取字典详情的完整路径
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     id    query     uint                                                       true  "字典详情ID"
// @Success   200   {object}  response.Response{data=map[string]interface{},msg=string}  "获取字典详情路径"
// @Router    /sysDictionaryDetail/getDictionaryPath [get]
func (d *DictionaryDetailApi) GetDictionaryPath(c *gin.Context) {
	idStr := c.Query("id")
	if idStr == "" {
		response.FailWithMessage("字典详情ID不能为空", c)
		return
	}

	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		response.FailWithMessage("字典详情ID格式错误", c)
		return
	}

	path, err := dictionaryUsecase.GetDictionaryPath(c.Request.Context(), uint(id))
	if err != nil {
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}

	result := make([]map[string]interface{}, len(path))
	for i, item := range path {
		result[i] = toDictionaryDetailResponse(item)
	}
	response.OkWithDetailed(gin.H{"path": result}, "获取成功", c)
}

func toDictionaryDetailResponse(d *system.DictionaryDetail) map[string]interface{} {
	return map[string]interface{}{
		"id":              d.ID,
		"label":           d.Label,
		"value":           d.Value,
		"extend":          d.Extend,
		"status":          d.Status,
		"sort":            d.Sort,
		"sysDictionaryID": d.SysDictionaryID,
		"parentId":        d.ParentID,
		"level":           d.Level,
		"path":            d.Path,
		"disabled":        d.Disabled,
	}
}

func toDictionaryDetailTreeResponse(list []*system.DictionaryDetail) []map[string]interface{} {
	result := make([]map[string]interface{}, len(list))
	for i, item := range list {
		resp := toDictionaryDetailResponse(item)
		if len(item.Children) > 0 {
			resp["children"] = toDictionaryDetailTreeResponse(item.Children)
		}
		result[i] = resp
	}
	return result
}
