package controllers

import (
	"errors"
	"spaceofcheng/services/utils"
	"strconv"
	"time"

	"net/http"
)

// FileUpload 文件上传
func (c *BaseController) FileUpload() {
	file, err := c.uploadFileToOSS("file")
	if err != nil {
		c.ResponseError(err, http.StatusInternalServerError)
	}

	c.ResponseJSON(map[string]interface{}{
		"url": file,
	})
}

func (c *BaseController) uploadFileToOSS(field string) (string, error) {
	aliConf, ok := c.Configer[AliYunConf]
	if !ok {
		return "", errors.New("没有找到阿里云相关配置")
	}

	endpoint := aliConf.String("oss::Endpoint")
	accessKeyID := aliConf.String("oss::AccessKeyId")
	accessKeySecret := aliConf.String("oss::AccessKeySecret")
	bucket := aliConf.String("oss::Bucket")

	aliCli, err := utils.GetOssClient(endpoint, accessKeyID, accessKeySecret)
	if err != nil {
		return "", err
	}

	fNameExtra := strconv.FormatInt(time.Now().Unix(), 10)

	fileURL, err := utils.UploadFileToBucket(aliCli, c.Ctx.Request, bucket, field, fNameExtra)
	if err != nil {
		return "", err
	}

	return fileURL, nil
}
