package services

import (
	"errors"
	"eta/eta_api/models"
	"eta/eta_api/utils"
	"fmt"
	"io"
	"mime/multipart"
	"os"
	"time"
)

// UploadToOssAndFileName 上传到oss并使用这个名称
func UploadToOssAndFileName(fileMulti multipart.File, newFileName string) (resourceUrl string, err error) {
	dateDir := time.Now().Format("20060102")
	uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
	err = os.MkdirAll(uploadDir, utils.DIR_MOD)
	if err != nil {
		err = errors.New("存储目录创建失败,Err:" + err.Error())
		return
	}

	//本地地址
	fpath := uploadDir + "/" + newFileName
	err = saveToFile(fileMulti, fpath)
	if err != nil {
		err = errors.New("文件上传失败，Err:" + err.Error())
		return
	}

	//上传到阿里云 和 minio
	//if utils.ObjectStorageClient == "minio" {
	//	resourceUrl, err = UploadImgToMinIo(newFileName, fpath)
	//	if err != nil {
	//		err = errors.New("文件上传失败，Err:" + err.Error())
	//		return
	//	}
	//} else {
	//	resourceUrl, err = UploadAliyunV2(newFileName, fpath)
	//	if err != nil {
	//		err = errors.New("文件上传失败，Err:" + err.Error())
	//		return
	//	}
	//}
	ossClient := NewOssClient()
	if ossClient == nil {
		err = fmt.Errorf("初始化OSS服务失败")
		return
	}
	resourceUrl, err = ossClient.UploadFile(newFileName, fpath, "")
	if err != nil {
		err = fmt.Errorf("文件上传失败, Err: %s", err.Error())
		return
	}

	defer func() {
		os.Remove(fpath)
	}()

	item := new(models.Resource)
	item.ResourceUrl = resourceUrl
	item.ResourceType = 1
	item.CreateTime = time.Now()
	_, err = models.AddResource(item)
	if err != nil {
		err = errors.New("资源上传失败,Err:" + err.Error())
		return
	}
	return
}

// saveToFile 保存到本地文件
func saveToFile(fileMulti multipart.File, tofile string) error {
	f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		return err
	}
	defer f.Close()
	io.Copy(f, fileMulti)
	return nil
}
