package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

// 定义请求和响应的结构体
type SmsRequest struct {
	Account      string         `json:"account"`
	Password     string         `json:"password"`
	RequestLists []MtSmsMessage `json:"requestLists"`
	//RequestId      string         `json:"requestId,omitempty"`
	//StatusCallback string         `json:"statusCallback,omitempty"`
}

type MtSmsMessage struct {
	Mobiles       []string          `json:"mobiles"`
	TemplateId    string            `json:"templateId"`
	TemplateParas map[string]string `json:"templateParas,omitempty"`

	Signature string `json:"signature"`
}

type SmsResponse struct {
	ResultCode  string            `json:"resultCode"`
	ResultDesc  string            `json:"resultDesc,omitempty"`
	ResultLists []MtSmsMessageRsp `json:"resultLists,omitempty"`
}

type MtSmsMessageRsp struct {
	Mobile     string `json:"mobile"`
	ResultCode string `json:"resultCode"`
	ResultDesc string `json:"resultDesc"`
	MessageId  string `json:"messageId"`
}

// SendSms 发送短信的函数
func SendSms(url string, reqData SmsRequest) (*SmsResponse, error) {
	// 序列化请求数据
	jsonData, err := json.Marshal(reqData)
	if err != nil {
		return nil, fmt.Errorf("error marshalling request data: %v", err)
	}

	// 创建HTTP请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, fmt.Errorf("error creating request: %v", err)
	}
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("error sending request: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应数据
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("error reading response body: %v", err)
	}

	// 解析响应数据
	var response SmsResponse
	if err := json.Unmarshal(body, &response); err != nil {
		return nil, fmt.Errorf("error unmarshalling response data: %v", err)
	}

	return &response, nil
}

func main() {
	// API URL https://139.9.32.119:18312/common/sms/sendTemplateMessage
	// https://sms.huaweiita.com:18000/common/sms/sendTemplateMessage
	url := "https://sms.huaweiita.com:18000/common/sms/sendTemplateMessage"

	// 构建请求数据
	requestData := SmsRequest{
		Account:  "970027",
		Password: "QM-jA9(tnBR==eiz",
		RequestLists: []MtSmsMessage{
			{
				Mobiles:    []string{"18539256182", "13601902367"},
				TemplateId: "SMS_24052800005",
				TemplateParas: map[string]string{
					"Snames":    "Amigo,Ford,lily,Tom等",
					"TIME":      "2020-04-30 23:59:59",
					"MHTIndexs": "冲动倾向-孤独倾向-学习焦虑-对人焦虑等指标",
				},
				Signature: "【觉卿科技】",
			},
		},
	}

	// 使用SendSms函数发送短信
	response, err := SendSms(url, requestData)
	if err != nil {
		fmt.Printf("Error sending SMS: %v\n", err)
		return
	}

	if response.ResultCode == "0" {
		fmt.Printf("发送消息成功!")
	} else if response.ResultCode == "100003" {
		fmt.Printf("参数格式错误!")
	}

}
