package services

import (
	"encoding/json"
	"errors"
	"eta/eta_api/utils"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	tencentErr "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	ses "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ses/v20201002"
	"time"
)

// TencentEmail 腾讯云邮件
type TencentEmail struct {
	Client *ses.Client
}

// NewClient
func (te *TencentEmail) NewClient() (err error) {
	if utils.TencentSDKSecretId == `` {
		err = errors.New("腾讯云邮箱未配置")
		return
	}
	// 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
	// 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
	credential := common.NewCredential(
		utils.TencentSDKSecretId,
		utils.TencentSDKSecretKey,
	)
	// 实例化一个client选项，可选的，没有特殊需求可以跳过
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "ses.tencentcloudapi.com"
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, _err := ses.NewClient(credential, "ap-hongkong", cpf)
	te.Client = client
	err = _err
	return
}

// TencentEmailTemplateData 邮箱模板替换数据
type TencentEmailTemplateData struct {
	REPORT_TITLE      string `description:"报告标题"`
	REPORT_ABSTRACT   string `description:"报告摘要"`
	REPORT_CONTENT    string `description:"报告内容"`
	REPORT_SHARE_LINK string `description:"报告分享链接"`
	REPORT_TIME       string `description:"报告时间"`
}

// TencentEmailResult 邮件推送响应体
type TencentEmailResult struct {
	Code      string `description:"错误码"`
	Message   string `description:"响应信息"`
	RequestId string `description:"请求成功-请求ID"`
}

// SendEmail 推送模板邮件
func (te *TencentEmail) SendEmail(req *EnglishReportSendEmailRequest) (ok bool, result string, err error) {
	if te.Client == nil {
		if e := te.NewClient(); e != nil {
			err = e
			return
		}
	}
	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := ses.NewSendEmailRequest()

	// 模板数据替换
	tmpData := &TencentEmailTemplateData{
		REPORT_TITLE:      req.ReportTitle,
		REPORT_ABSTRACT:   req.ReportAbstract,
		REPORT_CONTENT:    req.ReportContent,
		REPORT_SHARE_LINK: req.ReportShareLink,
		REPORT_TIME:       req.ReportTime,
	}
	tmpDataByte, e := json.Marshal(tmpData)
	if e != nil {
		err = e
		return
	}
	tmpDataStr := string(tmpDataByte)
	request.Template = &ses.Template{
		TemplateID:   common.Uint64Ptr(utils.TencentEmailTemplateID),
		TemplateData: common.StringPtr(tmpDataStr),
	}
	request.FromEmailAddress = common.StringPtr(utils.TencentEmailFromEmailAddress)
	request.Destination = common.StringPtrs([]string{req.Email})
	request.Subject = common.StringPtr(req.Subject)

	// 返回的resp是一个SendEmailResponse的实例，与请求对象对应
	response, e := te.Client.SendEmail(request)
	if _, o := e.(*tencentErr.TencentCloudSDKError); o {
		errByte, _ := json.Marshal(e)
		result = string(errByte)
		return
	}
	if e != nil {
		err = e
		return
	}
	ok = true
	result = response.ToJsonString()
	return
}

// BatchSendEmail 批量推送邮件
func (te *TencentEmail) BatchSendEmail(list []*EnglishReportSendEmailRequest) (results []*EnglishReportSendEmailResult, err error) {
	results = make([]*EnglishReportSendEmailResult, 0)
	if len(list) == 0 {
		return
	}
	if e := te.NewClient(); e != nil {
		err = e
		return
	}

	// SendEmail接口有QPS20的限制, 保险起见每秒只请求10次接口
	max := 10
	c := 0
	for i := range list {
		if c >= max {
			time.Sleep(time.Second)
			c = 0
		}
		c += 1

		dataByte, _ := json.Marshal(list[i])
		ok, result, _ := te.SendEmail(list[i])
		results = append(results, &EnglishReportSendEmailResult{
			ReportId:   list[i].ReportId,
			EmailId:    list[i].EmailId,
			Email:      list[i].Email,
			Ok:         ok,
			SendData:   string(dataByte),
			ResultData: result,
			Source:     1,
		})
	}
	return
}

// TencentEmailCallBack 回调请求体
type TencentEmailCallBack struct {
	Event      string `description:"事件类型"`
	Email      string `description:"收件人地址"`
	Link       string `description:"用户点击的邮件中的链接 URL，仅在event=click时生效"`
	BulkId     string `description:"SendEmail 接口返回的 MessageId"`
	Timestamp  int    `description:"事件产生的时间戳"`
	Reason     string `description:"邮件递送失败的原因"`
	BounceType string `description:"如果收件人邮件服务商拒信，拒信类型，取值：soft_bounce | hard_bounce，仅在event=bounce的时候生效"`
	Username   string `description:"腾讯云账号对应的 appId"`
	From       string `description:"发信地址（不带发件人别名）"`
	FromDomain string `description:"发信域名"`
	TemplateId int    `description:"模板 Id"`
}

//func init() {
//	fmt.Println("start email init")
//
//	te := new(TencentEmail)
//	te.NewClient()
//	req := new(EnglishReportSendEmailRequest)
//	req.Subject = "这是一封邮件的主题"
//	req.Email = ""
//	req.ReportTitle = "Report Hello World"
//	req.ReportAbstract = "This is abstract"
//	req.ReportContent = "This is content"
//	req.ReportShareLink = "https://share.hzinsights.com/reportEn?code=a226e450e214f350856e2980b6e55ac9"
//	req.ReportTime = "2022/11/23"
//
//	ok, result, e := te.SendEmail(req)
//	fmt.Println(ok)
//	if e != nil {
//		fmt.Println("出错了: ", e)
//	} else {
//		fmt.Println("没出错: ", result)
//	}
//
//	fmt.Println("end email init")
//}
