package config

import (
	"cicv-data-closedloop/common/config/c_log"
	"cicv-data-closedloop/common/util"
	"encoding/json"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"os"
	"sync"
)

type OssConnectInfoStruct struct {
	Endpoint        string `json:"endpoint"`
	AccessKeyId     string `json:"accessKeyId"`
	AccessKeySecret string `json:"accessKeySecret"`
	BucketName      string `json:"bucketName"`
}

var (
	OssClient *oss.Client
	OssBucket *oss.Bucket
	OssMutex  sync.Mutex
)

func InitOssConfig() {
	c_log.GlobalLogger.Info("初始化OSS客户端对象 - 开始。")
	// 1 访问 HTTP 服务获取 OSS 配置
	get, err := util.HttpGet(LocalConfig.UrlGetOssConfig)
	if err != nil {
		c_log.GlobalLogger.Error("http获取oss配置时出错:", err)
		os.Exit(-1)
	}
	var ossConnectInfo OssConnectInfoStruct
	err = json.Unmarshal([]byte(get), &ossConnectInfo)
	if err != nil {
		c_log.GlobalLogger.Error("解析json时出错:", err)
		os.Exit(-1)
	}
	c_log.GlobalLogger.Infof("oss 配置信息为：%v", ossConnectInfo)

	OssClient, err = oss.New(ossConnectInfo.Endpoint, ossConnectInfo.AccessKeyId, ossConnectInfo.AccessKeySecret, oss.UseCname(true))
	if err != nil {
		c_log.GlobalLogger.Error("无法创建阿里云client:", err)
		os.Exit(-1)
	}
	OssBucket, err = OssClient.Bucket(ossConnectInfo.BucketName)
	if err != nil {
		c_log.GlobalLogger.Error("无法创建阿里云bucket:", err)
		os.Exit(-1)
	}
	c_log.GlobalLogger.Info("初始化OSS客户端对象 - 成功。")
}
