package sms

import (
	"encoding/json"
	"eta/eta_mini_ht_api/common/component/config"
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/common/exception"
	"eta/eta_mini_ht_api/common/utils/sms"
	"fmt"
	"io"
	"net/http"
	"net/url"
)

const (
	apiURL      = "http://v.juhe.cn/sms/send"
	SendSuccess = "发送成功"

	SendFail = "发送失败"
)

type JuheSmsSender struct {
	tplId           string
	SmsExpireMinute int
	Key             string
}

func (jh *JuheSmsSender) InitSender(config *config.SMSConfig) {
	jh.tplId = config.GetJhTlpId()
	jh.SmsExpireMinute = config.GetJhExpireMinute()
	jh.Key = config.GetKey()
}
func (jh *JuheSmsSender) GetExpireMinute() int {
	return jh.SmsExpireMinute
}

type JHResp struct {
	Reason    string `json:"reason"`
	Result    Result `json:"result"`
	ErrorCode int
}
type Result struct {
	Sid   string `json:"sid"`
	Fee   int    `json:"fee"`
	Count int    `json:"count"`
}

func (jh *JuheSmsSender) SendSms(mobile string, code string, _ int) (result string, err error) {
	var Url *url.URL
	//初始化参数
	param := url.Values{}
	//配置请求参数,方法内部已处理urlencode问题,中文参数可以直接传参
	param.Set("mobile", mobile)   //接受短信的用户手机号码
	param.Set("tpl_id", jh.tplId) //您申请的短信模板ID，根据实际情况修改
	tplVal := fmt.Sprintf(`#code#=%s&#m#=%d`, code, jh.SmsExpireMinute)
	param.Set("tpl_value", tplVal) //您设置的模板变量，根据实际情况
	param.Set("key", jh.Key)       //应用APPKEY(应用详细页查询)
	Url, err = url.Parse(apiURL)
	if err != nil {
		logger.Warn("[短信发送]解析url错误:%v", err)
		return SendFail, exception.New(exception.SendingSMSFailed)
	}
	//如果参数中有中文参数,这个方法会进行URLEncode
	Url.RawQuery = param.Encode()
	resp, err := http.Get(Url.String())
	if err != nil {
		logger.Warn("[短信发送]发送失败:%v", err)
		return SendFail, exception.New(exception.SendingSMSFailed)
	}
	body, _ := io.ReadAll(resp.Body)
	var jsonResp JHResp
	err = json.Unmarshal(body, &jsonResp)
	if err != nil {
		logger.Warn("[短信发送]解析jh应答失败:%v", err)
		return SendFail, exception.New(exception.SendingSMSFailed)
	}
	if jsonResp.ErrorCode != 0 {
		logger.Warn("[短信发送]发送失败%v", jsonResp.Reason)
		return SendFail, exception.New(exception.SendingSMSFailed)
	}
	defer func(Body io.ReadCloser) {
		closeErr := Body.Close()
		if closeErr != nil {
			logger.Error("关闭Response失败:%v", closeErr)
		}
	}(resp.Body)
	logger.Info("[短信发送]发送成功,sid:%v", jsonResp.Result.Sid)
	return SendSuccess, nil
}
func NewJHClient() sms.SMSClient {
	return &JuheSmsSender{}
}
func init() {
	sms.Register(sms.Juhe, NewJHClient)
}
