package sms

import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	smsutil "github.com/alibabacloud-go/tea-utils/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/goccy/go-json"
	"os"
)

var client *dysmsapi20170525.Client

// InitOSSClient 初始化OSS鉴权客户端
func Init() error {
	var _client *dysmsapi20170525.Client

	var config = new(openapi.Config)
	key := os.Getenv("SMS_ACCESS_KEY_ID")
	config.AccessKeyId = &key
	secret := os.Getenv("SMS_ACCESS_KEY_SECRET")
	config.AccessKeySecret = &secret

	// 访问的域名
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_client = &dysmsapi20170525.Client{}
	_client, err := dysmsapi20170525.NewClient(config)
	if err != nil {
		panic("阿里云sms初始化失败。。。。")
	}
	client = _client
	return nil
}

// Put 将文件流保存到指定目录
func Send(phoneNum string, code string, prefix string) (response *dysmsapi20170525.SendSmsResponse, err error) {
	var params = make(map[string]interface{})
	params["code"] = code
	paramStr, _ := json.Marshal(params)

	var sendSmsRequest = new(dysmsapi20170525.SendSmsRequest)
	if prefix == "" || prefix == "86" {
		sendSmsRequest.PhoneNumbers = tea.String(phoneNum)
		sendSmsRequest.SignName = tea.String("八点八数字")
		sendSmsRequest.TemplateCode = tea.String("SMS_243775044")
		sendSmsRequest.TemplateParam = tea.String(string(paramStr))
	} else {
		sendSmsRequest.PhoneNumbers = tea.String(prefix + phoneNum)
		sendSmsRequest.SignName = tea.String("XMEN")
		sendSmsRequest.TemplateCode = tea.String("SMS_244595512")
		sendSmsRequest.TemplateParam = tea.String(string(paramStr))
	}

	runtime := &smsutil.RuntimeOptions{}
	return client.SendSmsWithOptions(sendSmsRequest, runtime)

}
