package services

import (
	"encoding/json"
	"eta/eta_mobile/utils"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dm "github.com/alibabacloud-go/dm-20151123/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"time"
)

// AliyunEmail 阿里云邮件
type AliyunEmail struct {
	Client *dm.Client
}

// NewClient
func (em *AliyunEmail) NewClient() (err error) {
	config := &openapi.Config{
		AccessKeyId:     tea.String(utils.AliyunEmailAccessKeyId),
		AccessKeySecret: tea.String(utils.AliyunEmailAccessKeySecret),
	}
	// 访问的域名
	config.Endpoint = tea.String("dm.aliyuncs.com")
	_result, _err := dm.NewClient(config)
	em.Client = _result
	err = _err
	return
}

// AliyunEmailResult 邮件推送响应体
type AliyunEmailResult struct {
	Code        string `description:"错误码"`
	StatusCode  int    `description:"状态码"`
	Message     string `description:"响应信息"`
	Data        string `description:"请求体"`
	Description string `description:"描述"`
	EnvId       string `description:"请求成功-事件ID"`
	RequestId   string `description:"请求成功-请求ID"`
}

// AliyunEmailResultData 邮件推送响应内容
type AliyunEmailResultData struct {
	Code       string `description:"错误码"`
	HostId     string `description:""`
	Message    string `description:"响应信息"`
	Recommend  string `description:""`
	RequestId  string `description:"请求ID"`
	StatusCode int    `description:"状态码"`
}

// SendEmail 邮件推送
func (em *AliyunEmail) SendEmail(item *EnglishReportSendEmailRequest) (ok bool, result string, err error) {
	if em.Client == nil {
		if e := em.NewClient(); e != nil {
			err = e
			return
		}
	}
	singleSendMailRequest := &dm.SingleSendMailRequest{}
	singleSendMailRequest.SetAccountName(utils.AliyunEmailAccountName)
	singleSendMailRequest.SetAddressType(1)
	singleSendMailRequest.SetReplyToAddress(false)
	singleSendMailRequest.SetSubject(item.Subject)
	singleSendMailRequest.SetToAddress(item.Email)
	singleSendMailRequest.SetHtmlBody(item.HtmlBody)
	singleSendMailRequest.SetFromAlias(item.FromAlias)

	runtime := &util.RuntimeOptions{}
	tryErr := func() error {
		res, e := em.Client.SingleSendMailWithOptions(singleSendMailRequest, runtime)
		if e != nil {
			return e
		}
		// 请求成功
		if tea.Int32Value(res.StatusCode) == 200 {
			ok = true
		}
		resByte, e := json.Marshal(res.Body)
		if e != nil {
			return e
		}
		result = string(resByte)
		return nil
	}()

	if tryErr != nil {
		var e = &tea.SDKError{}
		if t, ok := tryErr.(*tea.SDKError); ok {
			e = t
		} else {
			e.Message = tea.String(tryErr.Error())
		}
		err = e
		errByte, _ := json.Marshal(err)
		result = string(errByte)
	}
	return
}

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

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

		dataByte, _ := json.Marshal(list[i])
		ok, result, _ := em.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
}
