package router

import (
	"demo/share"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"os"
	"time"
)

var (
	uploadFileKey = "upload.bat-key"
	filepath      = "./file/resources/"
)

func FileRouter(engine *gin.RouterGroup) {
	//文件静态资源，可以直接访问静态资源文件
	user := engine.Group("/file")
	{
		//文章上传
		//user.POST("/upload", uploadHandler)
		PushRouter(user, "POST", "/upload", uploadHandler)
		PushRouter(user, "DELETE", "", DeleteFile)
	}
}

// 文件上传
func uploadHandler(c *gin.Context) {
	header, err := c.FormFile("file")
	fmt.Println("header", header.Size)
	if err != nil {
		c.JSON(200, CreateResultError(400, "上传错误"))
		return
	}
	fmt.Println("header", header.Size)
	//dst := header.Filename
	// gin 简单做了封装,拷贝了文件流
	//if err := c.SaveUploadedFile(header, dst); err != nil {
	//	c.JSON(200, CreateResultError(400, "上传错误"))
	//	return
	//}
	//上传到的路径
	//path := 'resource/public/uploads/20060102150405test.xlsx'
	header.Filename = fmt.Sprintf("%s%s", time.Now().Format("20060102150405"), header.Filename) // 文件名格式 自己可以改 建议保证唯一性
	path := filepath + header.Filename                                                          //路径+文件名上传

	// 上传文件到指定的目录
	err = c.SaveUploadedFile(header, path)
	if err != nil {
		err = errors.New(fmt.Sprintf("上传失败，%v", err))
		return
	}
	c.JSON(200, CreateResultData(map[string]interface{}{
		"url": "/api/static/" + header.Filename,
	}))
}

// DeleteFile 文件上传
func DeleteFile(c *gin.Context) {
	data := share.GetJsonAnyParam(c)
	fileUrl, _ := data("fileUrl")
	s, err := os.Stat(cast.ToString(fileUrl))
	if os.IsNotExist(err) {
		c.JSON(200, CreateResultError(400, "文件不存在"))
		return
	}
	if s.IsDir() {
		c.JSON(200, CreateResultError(400, "路径不存在"))
		return
	}
	err = os.Remove(cast.ToString(fileUrl))
	if err != nil {
		c.JSON(200, CreateResultError(400, "删除失败"))
		return
	}
	c.JSON(200, CreateResult())
}
