package app

import (
	"encoding/json"
	"strconv"

	"git.echol.cn/loser/st/server/global"
	"git.echol.cn/loser/st/server/model/app/request"
	"git.echol.cn/loser/st/server/model/common"
	commonResponse "git.echol.cn/loser/st/server/model/common/response"
	"git.echol.cn/loser/st/server/service"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type CharacterApi struct{}

// CreateCharacter
// @Tags     AppCharacter
// @Summary  创建角色卡
// @Produce  application/json
// @Param    data  body      request.CreateCharacterRequest                          true  "角色卡信息"
// @Success  200   {object}  commonResponse.Response{data=response.CharacterResponse}  "创建成功"
// @Router   /app/character [post]
// @Security ApiKeyAuth
func (a *CharacterApi) CreateCharacter(c *gin.Context) {
	userID := common.GetAppUserID(c)

	var req request.CreateCharacterRequest
	err := c.ShouldBindJSON(&req)
	if err != nil {
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	resp, err := service.ServiceGroupApp.AppServiceGroup.CharacterService.CreateCharacter(userID, &req)
	if err != nil {
		global.GVA_LOG.Error("创建角色卡失败", zap.Error(err))
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	commonResponse.OkWithData(resp, c)
}

// GetCharacterList
// @Tags     AppCharacter
// @Summary  获取角色卡列表
// @Produce  application/json
// @Param    page      query     int     false  "页码"
// @Param    pageSize  query     int     false  "每页数量"
// @Param    keyword   query     string  false  "关键词"
// @Param    tag       query     string  false  "标签"
// @Param    isPublic  query     bool    false  "是否公开"
// @Success  200       {object}  commonResponse.Response{data=response.CharacterListResponse}  "获取成功"
// @Router   /app/character [get]
// @Security ApiKeyAuth
func (a *CharacterApi) GetCharacterList(c *gin.Context) {
	userID := common.GetAppUserID(c)

	var req request.GetCharacterListRequest
	req.Page, _ = strconv.Atoi(c.DefaultQuery("page", "1"))
	req.PageSize, _ = strconv.Atoi(c.DefaultQuery("pageSize", "20"))
	req.Keyword = c.Query("keyword")
	req.Tag = c.Query("tag")

	if isPublicStr := c.Query("isPublic"); isPublicStr != "" {
		isPublic := isPublicStr == "true"
		req.IsPublic = &isPublic
	}

	// 参数验证
	if req.Page < 1 {
		req.Page = 1
	}
	if req.PageSize < 1 || req.PageSize > 100 {
		req.PageSize = 20
	}

	resp, err := service.ServiceGroupApp.AppServiceGroup.CharacterService.GetCharacterList(userID, &req)
	if err != nil {
		global.GVA_LOG.Error("获取角色卡列表失败", zap.Error(err))
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	commonResponse.OkWithDetailed(commonResponse.PageResult{
		List:     resp.List,
		Total:    resp.Total,
		Page:     resp.Page,
		PageSize: resp.PageSize,
	}, "获取成功", c)
}

// GetCharacterByID
// @Tags     AppCharacter
// @Summary  获取角色卡详情
// @Produce  application/json
// @Param    id   path      int  true  "角色卡ID"
// @Success  200  {object}  commonResponse.Response{data=response.CharacterResponse}  "获取成功"
// @Router   /app/character/:id [get]
// @Security ApiKeyAuth
func (a *CharacterApi) GetCharacterByID(c *gin.Context) {
	userID := common.GetAppUserID(c)
	characterID, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		commonResponse.FailWithMessage("无效的角色卡ID", c)
		return
	}

	resp, err := service.ServiceGroupApp.AppServiceGroup.CharacterService.GetCharacterByID(userID, uint(characterID))
	if err != nil {
		global.GVA_LOG.Error("获取角色卡详情失败", zap.Error(err))
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	commonResponse.OkWithData(resp, c)
}

// UpdateCharacter
// @Tags     AppCharacter
// @Summary  更新角色卡
// @Produce  application/json
// @Param    id    path      int                             true  "角色卡ID"
// @Param    data  body      request.UpdateCharacterRequest  true  "角色卡信息"
// @Success  200   {object}  commonResponse.Response{msg=string}  "更新成功"
// @Router   /app/character/:id [put]
// @Security ApiKeyAuth
func (a *CharacterApi) UpdateCharacter(c *gin.Context) {
	userID := common.GetAppUserID(c)
	characterID, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		commonResponse.FailWithMessage("无效的角色卡ID", c)
		return
	}

	var req request.UpdateCharacterRequest
	err = c.ShouldBindJSON(&req)
	if err != nil {
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	err = service.ServiceGroupApp.AppServiceGroup.CharacterService.UpdateCharacter(userID, uint(characterID), &req)
	if err != nil {
		global.GVA_LOG.Error("更新角色卡失败", zap.Error(err))
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

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

// DeleteCharacter
// @Tags     AppCharacter
// @Summary  删除角色卡
// @Produce  application/json
// @Param    id   path      int  true  "角色卡ID"
// @Success  200  {object}  commonResponse.Response{msg=string}  "删除成功"
// @Router   /app/character/:id [delete]
// @Security ApiKeyAuth
func (a *CharacterApi) DeleteCharacter(c *gin.Context) {
	userID := common.GetAppUserID(c)
	characterID, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		commonResponse.FailWithMessage("无效的角色卡ID", c)
		return
	}

	err = service.ServiceGroupApp.AppServiceGroup.CharacterService.DeleteCharacter(userID, uint(characterID))
	if err != nil {
		global.GVA_LOG.Error("删除角色卡失败", zap.Error(err))
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

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

// UploadCharacter
// @Tags     AppCharacter
// @Summary  上传角色卡文件（PNG/JSON）
// @Accept   multipart/form-data
// @Produce  application/json
// @Param    file  formData  file  true  "角色卡文件"
// @Success  200   {object}  commonResponse.Response{data=response.CharacterResponse}  "上传成功"
// @Router   /app/character/upload [post]
// @Security ApiKeyAuth
func (a *CharacterApi) UploadCharacter(c *gin.Context) {
	userID := common.GetAppUserID(c)

	file, err := c.FormFile("file")
	if err != nil {
		commonResponse.FailWithMessage("请选择文件", c)
		return
	}

	// 根据文件类型选择导入方式
	contentType := file.Header.Get("Content-Type")
	var resp interface{}

	if contentType == "image/png" || contentType == "image/x-png" {
		resp, err = service.ServiceGroupApp.AppServiceGroup.CharacterService.ImportCharacterFromPNG(userID, file)
	} else if contentType == "application/json" {
		resp, err = service.ServiceGroupApp.AppServiceGroup.CharacterService.ImportCharacterFromJSON(userID, file)
	} else {
		commonResponse.FailWithMessage("不支持的文件类型，仅支持 PNG 和 JSON", c)
		return
	}

	if err != nil {
		global.GVA_LOG.Error("上传角色卡失败", zap.Error(err))
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	commonResponse.OkWithData(resp, c)
}

// ExportCharacter
// @Tags     AppCharacter
// @Summary  导出角色卡为 JSON
// @Produce  application/json
// @Param    id   path      int  true  "角色卡ID"
// @Success  200  {object}  utils.CharacterCardV2  "导出成功"
// @Router   /app/character/:id/export [get]
// @Security ApiKeyAuth
func (a *CharacterApi) ExportCharacter(c *gin.Context) {
	userID := common.GetAppUserID(c)
	characterID, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		commonResponse.FailWithMessage("无效的角色卡ID", c)
		return
	}

	card, err := service.ServiceGroupApp.AppServiceGroup.CharacterService.ExportCharacterToJSON(userID, uint(characterID))
	if err != nil {
		global.GVA_LOG.Error("导出角色卡失败", zap.Error(err))
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	// 设置下载响应头
	c.Header("Content-Type", "application/json")
	c.Header("Content-Disposition", "attachment; filename=character_"+c.Param("id")+".json")

	// 直接返回 JSON
	jsonData, _ := json.MarshalIndent(card, "", "  ")
	c.Data(200, "application/json", jsonData)
}
