package app

import (
	"io"
	"strconv"

	"git.echol.cn/loser/st/server/model/app/request"
	"git.echol.cn/loser/st/server/model/app/response"
	"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"
)

type PresetApi struct{}

// CreatePreset 创建预设
// @Summary 创建预设
// @Tags Preset
// @Accept JSON
// @Produce JSON
// @Param data body request.CreatePresetRequest true "预设信息"
// @Success 200 {object} response.PresetResponse
// @Router /app/preset [post]
func (a *PresetApi) CreatePreset(c *gin.Context) {
	var req request.CreatePresetRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	userID := common.GetAppUserID(c)
	preset, err := service.ServiceGroupApp.AppServiceGroup.PresetService.CreatePreset(userID, &req)
	if err != nil {
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	resp := response.ToPresetResponse(preset)
	commonResponse.OkWithData(resp, c)
}

// GetPresetList 获取预设列表
// @Summary 获取预设列表
// @Tags Preset
// @Accept JSON
// @Produce JSON
// @Param page query int false "页码"
// @Param pageSize query int false "每页数量"
// @Param keyword query string false "关键词"
// @Param isPublic query bool false "是否公开"
// @Success 200 {object} response.PresetListResponse
// @Router /app/preset [get]
func (a *PresetApi) GetPresetList(c *gin.Context) {
	var req request.GetPresetListRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	// 设置默认值
	if req.Page == 0 {
		req.Page = 1
	}
	if req.PageSize == 0 {
		req.PageSize = 20
	}

	userID := common.GetAppUserID(c)
	presets, total, err := service.ServiceGroupApp.AppServiceGroup.PresetService.GetPresetList(userID, &req)
	if err != nil {
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	// 转换为响应格式
	list := make([]response.PresetResponse, 0, len(presets))
	for _, preset := range presets {
		list = append(list, response.ToPresetResponse(&preset))
	}

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

// GetPresetByID 根据ID获取预设
// @Summary 根据ID获取预设
// @Tags Preset
// @Accept JSON
// @Produce JSON
// @Param id path int true "预设ID"
// @Success 200 {object} response.PresetResponse
// @Router /app/preset/:id [get]
func (a *PresetApi) GetPresetByID(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		commonResponse.FailWithMessage("无效的预设ID", c)
		return
	}

	userID := common.GetAppUserID(c)
	preset, err := service.ServiceGroupApp.AppServiceGroup.PresetService.GetPresetByID(userID, uint(id))
	if err != nil {
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	resp := response.ToPresetResponse(preset)
	commonResponse.OkWithData(resp, c)
}

// UpdatePreset 更新预设
// @Summary 更新预设
// @Tags Preset
// @Accept JSON
// @Produce JSON
// @Param id path int true "预设ID"
// @Param data body request.UpdatePresetRequest true "预设信息"
// @Success 200 {string} string "更新成功"
// @Router /app/preset/:id [put]
func (a *PresetApi) UpdatePreset(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		commonResponse.FailWithMessage("无效的预设ID", c)
		return
	}

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

	userID := common.GetAppUserID(c)
	if err := service.ServiceGroupApp.AppServiceGroup.PresetService.UpdatePreset(userID, uint(id), &req); err != nil {
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

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

// DeletePreset 删除预设
// @Summary 删除预设
// @Tags Preset
// @Accept JSON
// @Produce JSON
// @Param id path int true "预设ID"
// @Success 200 {string} string "删除成功"
// @Router /app/preset/:id [delete]
func (a *PresetApi) DeletePreset(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		commonResponse.FailWithMessage("无效的预设ID", c)
		return
	}

	userID := common.GetAppUserID(c)
	if err := service.ServiceGroupApp.AppServiceGroup.PresetService.DeletePreset(userID, uint(id)); err != nil {
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

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

// SetDefaultPreset 设置默认预设
// @Summary 设置默认预设
// @Tags Preset
// @Accept JSON
// @Produce JSON
// @Param id path int true "预设ID"
// @Success 200 {string} string "设置成功"
// @Router /app/preset/:id/default [post]
func (a *PresetApi) SetDefaultPreset(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		commonResponse.FailWithMessage("无效的预设ID", c)
		return
	}

	userID := common.GetAppUserID(c)
	if err := service.ServiceGroupApp.AppServiceGroup.PresetService.SetDefaultPreset(userID, uint(id)); err != nil {
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	commonResponse.OkWithMessage("设置成功", c)
}

// ImportPreset 导入预设
// @Summary 导入预设
// @Tags Preset
// @Accept multipart/form-data
// @Produce JSON
// @Param file formData file true "预设JSON文件"
// @Success 200 {object} response.PresetResponse
// @Router /app/preset/import [post]
func (a *PresetApi) ImportPreset(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		commonResponse.FailWithMessage("请上传文件", c)
		return
	}

	// 读取文件内容
	f, err := file.Open()
	if err != nil {
		commonResponse.FailWithMessage("读取文件失败", c)
		return
	}
	defer f.Close()

	jsonData, err := io.ReadAll(f)
	if err != nil {
		commonResponse.FailWithMessage("读取文件内容失败", c)
		return
	}

	userID := common.GetAppUserID(c)
	preset, err := service.ServiceGroupApp.AppServiceGroup.PresetService.ImportPresetFromJSON(userID, jsonData, file.Filename)
	if err != nil {
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

	resp := response.ToPresetResponse(preset)
	commonResponse.OkWithData(resp, c)
}

// ExportPreset 导出预设
// @Summary 导出预设
// @Tags Preset
// @Accept JSON
// @Produce JSON
// @Param id path int true "预设ID"
// @Success 200 {file} file "预设JSON文件"
// @Router /app/preset/:id/export [get]
func (a *PresetApi) ExportPreset(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		commonResponse.FailWithMessage("无效的预设ID", c)
		return
	}

	userID := common.GetAppUserID(c)
	jsonData, err := service.ServiceGroupApp.AppServiceGroup.PresetService.ExportPresetToJSON(userID, uint(id))
	if err != nil {
		commonResponse.FailWithMessage(err.Error(), c)
		return
	}

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

	// 返回JSON数据
	c.Data(200, "application/json", jsonData)
}
