package controllers

import (
	"eta/eta_api/models"
	"eta/eta_api/services"
	"eta/eta_api/utils"
	"github.com/h2non/filetype"
	"io/ioutil"
	"os"
	"path"
	"time"
)

// banner
type BannerController struct {
	BaseAuthController
}

// @Title 图片上传
// @Description 图片上传接口
// @Param   File   query   file  true       "文件"
// @Success 200 新增成功
// @router /upload [post]
func (this *BannerController) Upload() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	f, h, err := this.GetFile("file")
	if err != nil {
		br.Msg = "获取资源信息失败"
		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
		return
	}
	defer f.Close() //关闭上传文件

	// 不依赖于文件扩展名检查文件格式
	fileData, e := ioutil.ReadAll(f)
	if e != nil {
		br.Msg = "上传失败"
		br.ErrMsg = "读取文件失败, Err: " + e.Error()
		return
	}
	pass := filetype.IsImage(fileData)
	if !pass {
		br.Msg = "文件格式有误"
		br.ErrMsg = "文件格式有误"
		return
	}

	ext := path.Ext(h.Filename)
	dateDir := time.Now().Format("20060102")
	uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
	err = os.MkdirAll(uploadDir, utils.DIR_MOD)
	if err != nil {
		br.Msg = "存储目录创建失败"
		br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
		return
	}
	randStr := utils.GetRandStringNoSpecialChar(28)
	fileName := randStr + ext
	fpath := uploadDir + "/" + fileName
	err = this.SaveToFile("file", fpath)
	if err != nil {
		br.Msg = "文件上传失败"
		br.ErrMsg = "文件上传失败，Err:" + err.Error()
		return
	}
	defer func() {
		os.Remove(fpath)
	}()

	// 上传文件
	resourceUrl := ``
	ossClient := services.NewOssClient()
	if ossClient == nil {
		br.Msg = "上传失败"
		br.ErrMsg = "初始化OSS服务失败"
		return
	}
	resourceUrl, err = ossClient.UploadFile(fileName, fpath, "")
	if err != nil {
		br.Msg = "文件上传失败"
		br.ErrMsg = "文件上传失败，Err:" + err.Error()
		return
	}

	item := new(models.Resource)
	item.ResourceUrl = resourceUrl
	item.ResourceType = 1
	item.CreateTime = time.Now()
	newId, err := models.AddResource(item)
	if err != nil {
		br.Msg = "资源上传失败"
		br.ErrMsg = "资源上传失败,Err:" + err.Error()
		return
	}
	resp := new(models.ResourceResp)
	resp.Id = newId
	resp.ResourceUrl = resourceUrl

	br.Msg = "上传成功"
	br.Ret = 200
	br.Success = true
	br.Data = resp
	return
}
