package handlers

import (
	"easydo-echo_win7/models"
	"easydo-echo_win7/services"
	"easydo-echo_win7/utils"
	"fmt"
	"net/http"
	"path/filepath"

	// "strings"

	"easydo-echo_win7/middleware"

	"github.com/google/uuid"
	"github.com/labstack/echo/v4"
)

func Add_minio_to_routes(e *echo.Echo) {
	group := e.Group("/file")
	group.Use(middleware.AuthMiddleware)
	group.POST("/upload", fileUpload)
	group.POST("/remove", fileRemove)

}

// 响应结构体
type UploadResponse struct {
	Code    int                    `json:"code"`
	Message string                 `json:"message"`
	Expands map[string]interface{} `json:"expands,omitempty"`
}

// UploadHandler 是您的主要处理函数
func fileUpload(c echo.Context) error {
	// 1. 从form-data中获取文件
	file, err := c.FormFile("file")
	if err != nil {
		return c.JSON(http.StatusBadRequest, utils.ErrorResponse("无法获取上传的文件，请检查字段名是否为'file'", ""))
	}

	// 2. 打开上传的文件
	src, err := file.Open()
	if err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("无法打开上传的文件", ""))
	}
	defer src.Close()

	// 3. 生成唯一对象名并上传到MinIO
	objectName := generateUUIDFileName(file.Filename)

	// 上传到MinIO[citation:2]
	filePath, err := services.MinioClient.UploadFile(services.BucketName, src, objectName)
	if err != nil {
		return c.JSON(http.StatusInternalServerError, utils.ErrorResponse(fmt.Sprintf("上传到MinIO失败: %v", err), ""))
	}

	// 构建成功响应
	return c.JSON(http.StatusOK, UploadResponse{
		Code:    200,
		Message: "success",
		Expands: map[string]interface{}{
			"file": filePath,
		},
	})
}

// 生成UUID的辅助函数
func generateUUIDFileName(filename string) string {
	fullExt := filepath.Ext(filename)
	uuid := uuid.New()
	return uuid.String() + fullExt
}

func fileRemove(c echo.Context) error {
	file := new(models.MinioFile)
	if err := c.Bind(file); err != nil {
		return c.JSON(http.StatusOK, nil)
	}
	// file_path := *file.Path
	// bucketName := strings.Split(file_path[1:], "/")[0]
	// objectName := file_path[1+len(bucketName)+1:]
	// services.MinioClient.RemoveFile(bucketName,objectName)

	if file.ID != nil {
		err := services.JdbcClient.JdbcRemoveById(file)
		if err != nil {
			utils.PrintSqlErr(err)
			return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
		}
	}
	return c.JSON(http.StatusOK, file)
}
