package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/logic"
	"hongze/hongze_yb/services"
	"hongze/hongze_yb/utils"
	"os"
	"path"
	"time"
)

// GetApplyVarietyList
// @Tags 公共模块
// @Summary  获取所有可以申请的品种权限列表
// @Description 获取所有可以申请的品种权限列表
// @Security ApiKeyAuth
// @securityDefinitions.basic BasicAuth
// @Param Authorization	header string true "微信登录后获取到的token"
// @Accept  json
// @Product json
// @Success 200 {object} []logic.ApplyVariety "获取成功"
// @failure 400 {string} string "获取失败"
// @Router /public/get_apply_variety_list [get]
func GetApplyVarietyList(c *gin.Context) {
	list := logic.GetApplyVarietyList()
	response.OkData("获取成功", list, c)
}

// Upload
// @Tags 公共模块
// @Summary  文件上传
// @Description 文件上传
// @Security ApiKeyAuth
// @securityDefinitions.basic BasicAuth
// @Param Authorization	header string true "微信登录后获取到的token"
// @Param file formData file false "操作描述"
// @Accept  multipart/form-data
// @Product json
// @Success 200 {object} string "上传成功"
// @failure 400 {string} string "上传失败，存储目录创建失败"
// @Router /public/upload [post]
func Upload(c *gin.Context) {
	// 单文件
	file, err := c.FormFile("file")
	fmt.Println("file", file)
	if err != nil {
		response.FailData("获取资源失败", "获取资源失败，Err:"+err.Error(), c)
		return
	}

	ext := path.Ext(file.Filename)
	dateDir := time.Now().Format("20060102")
	uploadDir := global.CONFIG.Serve.StaticDir + "hongze/" + dateDir
	err = os.MkdirAll(uploadDir, 0766)
	if err != nil {
		response.FailData("存储目录创建失败", "存储目录创建失败，Err:"+err.Error(), c)
		return
	}
	randStr := utils.GetRandStringNoSpecialChar(28)
	fileName := randStr + ext
	fpath := uploadDir + "/" + fileName

	// 上传文件至指定目录
	err = c.SaveUploadedFile(file, fpath)
	if err != nil {
		response.FailData("文件上传失败", "文件上传失败，Err:"+err.Error(), c)
		return
	}
	defer func() {
		os.Remove(fpath)
	}()

	//上传到阿里云
	resourceUrl, err := services.UploadAliyun(fileName, fpath)
	if err != nil {
		response.FailData("文件上传失败", "文件上传失败，Err:"+err.Error(), c)
		return
	}
	response.OkData("文件上传成功", resourceUrl, c)

}
