package router

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

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

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

// 文件上传
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,
	}))
}
