package api

import (
	"box-cost/log"
	"encoding/json"
	"fmt"
	"sync"

	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	"github.com/alibabacloud-go/tea/tea"
)

func createSmsClient() (_result *dysmsapi20170525.Client, _err error) {
	accessKeyId := tea.String("LTAI4FmvA9HNunGVq6biNASf")
	accessKeySecret := tea.String("QNHsxlW0iESK15TpouJwoLQzRMSxgu")

	config := &openapi.Config{
		AccessKeyId:     accessKeyId,
		AccessKeySecret: accessKeySecret,
	}
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

type SupplierSmsReq struct {
	Product      string `json:"product"`
	SerialNumber string `json:"serialNumber"`
}

func SendSmsNotify(phone string, info *SupplierSmsReq, wg *sync.WaitGroup) error {
	defer wg.Done()
	client, _err := createSmsClient()
	if _err != nil {
		log.Error(_err)
		return _err
	}

	infobytes, _ := json.Marshal(info)

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  tea.String(phone),
		SignName:      tea.String("中鱼互动"),
		TemplateCode:  tea.String("SMS_460545008"),
		TemplateParam: tea.String(string(infobytes)),
	}

	resp, err := client.SendSms(sendSmsRequest)
	if err != nil {
		log.Error(err)
		return err
	}
	if *resp.Body.Code == "OK" {
		return nil
	}
	reserr := fmt.Errorf("code err %s", *resp.Body.Code)
	log.Error(reserr)

	return reserr
}
