package example

import (
	"strconv"

	"kra/internal/biz/example"
	"kra/pkg/response"

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

type FileUploadApi struct{}

// UploadFile
// @Tags      ExaFileUploadAndDownload
// @Summary   上传文件示例
// @Security  ApiKeyAuth
// @accept    multipart/form-data
// @Produce   application/json
// @Param     file  formData  file                                                 true  "上传文件示例"
// @Success   200   {object}  response.Response{data=FileUploadResponse,msg=string}  "上传文件示例,返回包括文件详情"
// @Router    /fileUploadAndDownload/upload [post]
func (api *FileUploadApi) UploadFile(c *gin.Context) {
	noSave := c.DefaultQuery("noSave", "0")
	classIdStr := c.DefaultQuery("classId", "0")
	classId, _ := strconv.Atoi(classIdStr)

	_, header, err := c.Request.FormFile("file")
	if err != nil {
		response.FailWithMessage("接收文件失败", c)
		return
	}

	file, err := fileUploadUsecase.UploadFile(c.Request.Context(), header, noSave, classId)
	if err != nil {
		response.FailWithMessage("上传失败: "+err.Error(), c)
		return
	}

	response.OkWithDetailed(toFileUploadResponse(file), "上传成功", c)
}

// DeleteFile
// @Tags      ExaFileUploadAndDownload
// @Summary   删除文件
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      DeleteFileRequest              true  "传入文件里面id即可"
// @Success   200   {object}  response.Response{msg=string}  "删除文件"
// @Router    /fileUploadAndDownload/deleteFile [post]
func (api *FileUploadApi) DeleteFile(c *gin.Context) {
	var req DeleteFileRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

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

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

// EditFileName
// @Tags      ExaFileUploadAndDownload
// @Summary   编辑文件名或者备注
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      EditFileNameRequest            true  "文件信息"
// @Success   200   {object}  response.Response{msg=string}  "编辑成功"
// @Router    /fileUploadAndDownload/editFileName [post]
func (api *FileUploadApi) EditFileName(c *gin.Context) {
	var req EditFileNameRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if err := fileUploadUsecase.EditFileName(c.Request.Context(), req.ID, req.Name); err != nil {
		response.FailWithMessage("编辑失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("编辑成功", c)
}

// GetFileList
// @Tags      ExaFileUploadAndDownload
// @Summary   分页文件列表
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      GetFileListRequest                                      true  "页码, 每页大小, 分类id"
// @Success   200   {object}  response.Response{data=response.PageResult,msg=string}  "分页文件列表,返回包括列表,总数,页码,每页数量"
// @Router    /fileUploadAndDownload/getFileList [post]
func (api *FileUploadApi) GetFileList(c *gin.Context) {
	var req GetFileListRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	searchReq := &example.FileUploadSearchReq{
		Page:     req.Page,
		PageSize: req.PageSize,
		Keyword:  req.Keyword,
		ClassId:  req.ClassId,
	}

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

	respList := make([]FileUploadResponse, len(list))
	for i, f := range list {
		respList[i] = *toFileUploadResponse(f)
	}

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

// ImportURL
// @Tags      ExaFileUploadAndDownload
// @Summary   导入URL
// @Security  ApiKeyAuth
// @accept    application/json
// @Produce   application/json
// @Param     data  body      []FileUploadResponse           true  "对象"
// @Success   200   {object}  response.Response{msg=string}  "导入URL"
// @Router    /fileUploadAndDownload/importURL [post]
func (api *FileUploadApi) ImportURL(c *gin.Context) {
	var req []FileUploadResponse
	if err := c.ShouldBindJSON(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	files := make([]*example.FileUpload, len(req))
	for i, r := range req {
		files[i] = &example.FileUpload{
			Name:    r.Name,
			ClassId: r.ClassId,
			Url:     r.Url,
			Tag:     r.Tag,
			Key:     r.Key,
		}
	}

	if err := fileUploadUsecase.ImportURL(c.Request.Context(), files); err != nil {
		response.FailWithMessage("导入失败: "+err.Error(), c)
		return
	}

	response.OkWithMessage("导入成功", c)
}

// Request/Response 结构
type DeleteFileRequest struct {
	ID uint `json:"id"`
}

type EditFileNameRequest struct {
	ID   uint   `json:"id"`
	Name string `json:"name"`
}

type GetFileListRequest struct {
	Page     int    `json:"page"`
	PageSize int    `json:"pageSize"`
	Keyword  string `json:"keyword"`
	ClassId  int    `json:"classId"`
}

type FileUploadResponse struct {
	ID      uint   `json:"ID"`
	Name    string `json:"name"`
	ClassId int    `json:"classId"`
	Url     string `json:"url"`
	Tag     string `json:"tag"`
	Key     string `json:"key"`
}

func toFileUploadResponse(f *example.FileUpload) *FileUploadResponse {
	return &FileUploadResponse{
		ID:      f.ID,
		Name:    f.Name,
		ClassId: f.ClassId,
		Url:     f.Url,
		Tag:     f.Tag,
		Key:     f.Key,
	}
}
