package oss

import (
	"bytes"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"io/ioutil"
	"mime/multipart"
	"openapi/pkg/constant"
	protocol "openapi/pkg/domain"
	"openapi/pkg/infrastructure/aliyun"
	"openapi/pkg/infrastructure/log"
	"openapi/pkg/infrastructure/utils"
	"path/filepath"
)

type BuckObject struct {
	DefaultHost string `json:"host"`
	Key         string `json:"key"`
	Path        string `json:"path"`
	FileName    string `json:"fileName"`
}

// 创建视频上传凭证
func CreateOssUpload(header *protocol.RequestHeader, MultipartForm *multipart.Form) (rsp interface{}, err error) {
	var objects []aliyun.Object
	var listPath []BuckObject
	var bucket *oss.Bucket
	bucket, err = aliyun.DefaultBucket()
	if err != nil {
		log.Error(err.Error())
		return
	}
	for k, _ := range MultipartForm.File {
		v := MultipartForm.File[k]
		for i := range v {
			if v[i].Size > 1024*1024*200 {
				continue
			}
			f, _ := v[i].Open()
			data, _ := ioutil.ReadAll(f)
			f.Close()
			reader := bytes.NewBuffer(data)
			fileBase := filepath.Base(v[i].Filename)
			key := utils.GetFileName(header.AppProject, aliyun.FileObject, fileBase)
			objects = append(objects, aliyun.Object{
				Key:   key,
				Value: reader,
			})
			listPath = append(listPath, BuckObject{
				DefaultHost: fmt.Sprintf("https://%v.%v", constant.BuckName, constant.OssEndPoint),
				Path:        fmt.Sprintf("https://%v.%v/%v", constant.BuckName, constant.OssEndPoint, key),
				Key:         key,
				FileName:    fileBase,
			})
		}
	}
	if len(objects) == 0 {
		return
	}
	err = aliyun.CreateObjects(bucket, objects...)
	if err != nil {
		log.Error(err.Error())
		return
	}
	rsp = listPath
	return
}

// 创建视频上传凭证
func CreateStsAuth(header *protocol.RequestHeader, files []string) (rsp interface{}, err error) {
	access, e := aliyun.DefaultSts()
	if e != nil {
		err = e
		log.Error(e.Error())
	}
	var listPath []BuckObject
	for _, v := range files {
		fileBase := filepath.Base(v)
		key := utils.GetFileName(header.AppProject, aliyun.FileObject, fileBase)
		listPath = append(listPath, BuckObject{
			DefaultHost: fmt.Sprintf("https://%v.%v", constant.BuckName, constant.OssEndPoint),
			Path:        fmt.Sprintf("https://%v.%v/%v", constant.BuckName, constant.OssEndPoint, key),
			Key:         key,
			FileName:    fileBase,
		})
	}
	return map[string]interface{}{"certificate": access, "files": listPath}, nil
}