package svc

import (
	"fmt"
	"git.i2edu.net/i2/i2-bill-api/internal/utils"
	"git.i2edu.net/i2/i2-bill-api/model"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"io"
	"mime/multipart"
	"path"
	"strings"
	"time"
)

var AliYunOss *AliYunOssUpDownloader

type AliYunOssUpDownloader struct {
	bucket *oss.Bucket
}

func GetAliYunOssInstance() (*AliYunOssUpDownloader, error) {
	var err error
	if AliYunOss == nil {
		AliYunOss, err = newAliYunOssUpDownloader()
	}
	return AliYunOss, err
}

func newAliYunOssUpDownloader() (*AliYunOssUpDownloader, error) {
	// 创建OSSClient实例。
	client, err := oss.New(ServiceConfig.AliYunOss.EndPoint, ServiceConfig.AliYunOss.KeyId, ServiceConfig.AliYunOss.Secret)
	if err != nil {
		fmt.Println("Error:", err)
		return nil, err
	}

	// 获取存储空间。
	aliYunBucket, err := client.Bucket(ServiceConfig.AliYunOss.Bucket)
	if err != nil {
		fmt.Println("Error:", err)
		return nil, err
	}
	return &AliYunOssUpDownloader{bucket: aliYunBucket}, nil
}

/**
 * @brief: 附件上传接口
 * @param1 file: post 多媒体file
 * @return1: 附件信息，主要包括id，url， hash和大小。其他字段会自动设置
 * @return4: 错误信息
 */
func (aoud *AliYunOssUpDownloader) Upload(file multipart.File, header *multipart.FileHeader) (*model.I2billSysAttachment, error) {
	attachId := utils.GetUUID()
	dateStr := time.Now().Format("2006/01/02")

	ext := strings.TrimSpace(path.Ext(header.Filename)) // 扩展名
	objectKey := ""
	if ext == "" {
		objectKey = fmt.Sprintf("customer/files/att/%s/%s", dateStr, attachId)
	} else {
		objectKey = fmt.Sprintf("customer/files/att/%s/%s%s", dateStr, attachId, ext)
	}

	err := aoud.bucket.PutObject(objectKey, file)
	if err != nil {
		fmt.Println("aoud.bucket.PutObject err", err.Error())
		return nil, err
	}

	attach := &model.I2billSysAttachment{}
	attach.Id = attachId
	attach.Url = objectKey
	attach.Hash = ""
	attach.Ext = ext
	attach.Name = header.Filename
	attach.Size = header.Size

	return attach, nil

}

func (aoud *AliYunOssUpDownloader) UploadRead(file io.Reader, ext string) (*model.I2billSysAttachment, error) {
	attachId := utils.GetUUID()
	dateStr := time.Now().Format("2006/01/02")

	objectKey := ""
	if ext == "" {
		objectKey = fmt.Sprintf("customer/files/att/%s/%s", dateStr, attachId)
	} else {
		objectKey = fmt.Sprintf("customer/files/att/%s/%s%s", dateStr, attachId, ext)
	}

	err := aoud.bucket.PutObject(objectKey, file)
	if err != nil {
		fmt.Println("aoud.bucket.PutObject err", err.Error())
		return nil, err
	}

	attach := &model.I2billSysAttachment{}
	attach.Id = attachId
	attach.Url = objectKey
	attach.Hash = ""
	attach.Ext = ext
	attach.Name = attachId
	attach.CreateTime = time.Now()
	return attach, nil

}

func (aoud *AliYunOssUpDownloader) Download(attach *model.I2billSysAttachment) (io.ReadCloser, error) {
	objectKey := attach.Url
	r, err := aoud.bucket.GetObject(objectKey)
	if err != nil {
		fmt.Println("aoud.bucket.GetObject 错误", err.Error())
		return r, err
	}
	defer r.Close()

	return r, nil
}
