package service

import (
	"cold-delivery/conf"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"strings"

	"gogs.baozhida.cn/zoie/OAuth-core/pkg/sms"
)

// SendSmsToDeliveryPerson 发送配送通知短信给配送员
func SendSmsToDeliveryPerson(phone, orderNo string) error {
	vars := map[string]string{"orderNo": orderNo}
	varsBytes, _ := json.Marshal(vars)

	payload := url.Values{}
	payload.Set("appid", conf.ExtConfig.SubMail.Appid)
	payload.Set("signature", conf.ExtConfig.SubMail.Signature)
	payload.Set("to", phone)
	payload.Set("project", "gOK601")
	payload.Set("vars", string(varsBytes))

	req, err := http.NewRequest("POST", "https://api-v4.mysubmail.com/sms/xsend", strings.NewReader(payload.Encode()))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	var res sms.XSendRes
	if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
		return err
	}
	if res.Status != sms.SUCCESS {
		return errors.New(res.Msg)
	}
	return nil
}

// BuildSmsSendLog 构建短信发送日志
func BuildSmsSendLog(phone, orderNo string) string {
	return fmt.Sprintf("【贵州宝智达冷链科技有限公司】您有新的配送订单请及时处理，订单号：%s", orderNo)
}
