package sms

import (
	"bytes"
	"eta/eta_mini_ht_api/common/component/config"
	"eta/eta_mini_ht_api/common/component/database"
	"eta/eta_mini_ht_api/common/component/database/dialector"
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/common/exception"
	"eta/eta_mini_ht_api/common/utils/sms"
	stringUtils "eta/eta_mini_ht_api/common/utils/string"
	emasSmsService "eta/eta_mini_ht_api/domian/sms"
	"gorm.io/gorm"
	"os"
	"text/template"
)

const (
	emasDriver = "mysql"
)

type EMASSmsSender struct {
	Url               string
	Template          string
	TemplateGenerator *template.Template
	SmsExpireMinute   int
}

func initDBClient(url string) *gorm.DB {
	open, err := gorm.Open(dialector.GetGormDial(emasDriver).GetDial(url), &gorm.Config{})
	if err != nil {
		logger.Error("初始化亿美短信数据库失败:%v", err)
		os.Exit(0)
	}
	logger.Info("初始化亿美短信数据库成功")
	return open
}
func (emas *EMASSmsSender) InitSender(config *config.SMSConfig) {
	emas.Template = config.GetEMASTemplate()
	emas.Url = config.GetEMASUrl()
	emas.SmsExpireMinute = config.GetEMASExpireMinute()
	emas.TemplateGenerator = template.Must(template.New("smsTemplate").Parse(emas.Template))
	if stringUtils.IsEmptyOrNil(emas.Url) {
		panic("亿美短信平台初始化失败,数据库url不能为空")
	}
	database.Register(database.EMAS, initDBClient(emas.Url))
}
func (emas *EMASSmsSender) GetExpireMinute() int {
	return emas.SmsExpireMinute
}

type EMASResp struct {
	Reason    string `json:"reason"`
	Result    Result `json:"result"`
	ErrorCode int
}
type emasTemplate struct {
	ExpireMinute int
	Code         string
}

func (emas *EMASSmsSender) SendSms(mobile string, code string, smId int) (result string, err error) {
	var content bytes.Buffer
	if err = emas.TemplateGenerator.Execute(&content, &emasTemplate{emas.SmsExpireMinute, code}); err != nil {
		// 处理错误，例如记录日志或返回错误给调用者
		logger.Warn("[短信发送]生成短信内容失败:%v", err)
		return SendFail, exception.New(exception.SendingSMSFailed)
	}
	msg := emasSmsService.Msg{SMId: smId, Mobile: mobile, Content: content.String()}
	err = emasSmsService.SendSms(msg)
	if err != nil {
		logger.Warn("[短信发送]发送短信失败:%v", err)
		return SendFail, exception.New(exception.SendingSMSFailed)
	}
	return SendSuccess, nil
}
func NewEMASClient() sms.SMSClient {
	return &EMASSmsSender{}
}
func init() {
	sms.Register(sms.Emas, NewEMASClient)
}
