package utils

import (
	"exhibitionCentre/config"
	"exhibitionCentre/logging"
	"fmt"
	"strings"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

var AliyunStsClient *sts.Client
var AliyunOssClient *oss.Client
var AliyunOssBucket *oss.Bucket

type AliyunStsResponse struct {
	Region          string `json:"region"`
	Endpoint        string `json:"endpoint"`
	AccessKeyId     string `json:"access_key_id"`
	AccessKeySecret string `json:"access_key_secret"`
	StsToken        string `json:"sts_token"`
	Bucket          string `json:"bucket"`
}

func init() {
	initStsClient()
	initOssClient()
}

func initStsClient() bool {
	client, err := sts.NewClientWithAccessKey(config.Config.AliyunOss.RegionId, config.Config.AliyunOss.AccessKeyId, config.Config.AliyunOss.AccessKeySecret)
	if err != nil {
		logging.Log.Panicf("阿里云sts客户端创建失败, err: %v\n", err.Error())
		return false
	}
	AliyunStsClient = client
	logging.Log.Info("阿里云sts客户端创建完成")
	return true
}

func initOssClient() bool {
	client, err := oss.New(config.Config.AliyunOss.Endpoint, config.Config.AliyunOss.AccessKeyId, config.Config.AliyunOss.AccessKeySecret)
	if err != nil {
		logging.Log.Panicf("阿里云oss客户端创建失败, err: %v\n", err.Error())
		return false
	}
	AliyunOssClient = client
	logging.Log.Info("阿里云oss客户端创建完成")

	// 创建bucket
	bucket, err := AliyunOssClient.Bucket(config.Config.AliyunOss.Bucket)
	if err != nil {
		logging.Log.Panicf("阿里云oss bucket创建失败, err: %v\n", err.Error())
		return false
	}
	AliyunOssBucket = bucket
	logging.Log.Info("阿里云oss bucket创建完成")
	return true
}

func GenerateStsToken(sessionName string) *AliyunStsResponse {
	if AliyunStsClient == nil {
		return nil
	}
	request := sts.CreateAssumeRoleRequest()
	request.Scheme = "https"
	request.RoleArn = config.Config.AliyunOss.Arn
	request.RoleSessionName = sessionName

	response, err := AliyunStsClient.AssumeRole(request)
	if err != nil {
		logging.Log.Errorf("获取阿里云sts令牌失败, err: %v\n", err.Error())
		return nil
	}
	stsResponse := AliyunStsResponse{
		Region:          config.Config.AliyunOss.RegionId,
		Endpoint:        config.Config.AliyunOss.Endpoint,
		AccessKeyId:     response.Credentials.AccessKeyId,
		AccessKeySecret: response.Credentials.AccessKeySecret,
		StsToken:        response.Credentials.SecurityToken,
		Bucket:          config.Config.AliyunOss.Bucket,
	}
	return &stsResponse
}

/*********************************** oss操作 ***********************************/
func DeleteAliOssFile(fileurl string) bool {
	endpoint := fmt.Sprintf("%s/", config.Config.AliyunOss.Endpoint)
	index := strings.Index(fileurl, endpoint)
	if index < 0 {
		return false
	}
	index += len(endpoint)
	if index >= len(fileurl) {
		return false
	}
	err := AliyunOssBucket.DeleteObject(fileurl[index:])
	if err != nil {
		logging.Log.Warningf("oss删除文件(%v)失败, err:%v\n", fileurl, err.Error())
		return false
	}
	return true
}
