package verifica

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

type nationAccount struct {
	ak string
	sk string
}

type NationMsg struct {
	Apikey     string `json:"apikey"`
	Secret     string `json:"secret"`
	Content    string `json:"content"`
	Mobile     string `json:"mobile"`
	TemplateId int    `json:"template_id"`
	SendTime   int64  `json:"send_time"`
}

const (
	sendNationMsgUrl    = "https://api.4321.sh/inter/send"
	nationMsgTemplateId = 107570 //[$$]您此次验证码为$$，60秒内有效，请您尽快验证！
	accessKey           = "I1185562576"
	secretKey           = "1185566b86c739e71"
)

var nationAccountObj *nationAccount

func loadEnv(ak, sk string) {
	nationAccountObj = &nationAccount{
		ak: ak,
		sk: sk,
	}
}

func SendNationMsg(telNum, content string, templateId int) error {
	if templateId == 0 {
		templateId = nationMsgTemplateId
	}
	fmt.Print("content:", content)
	loadEnv(accessKey, secretKey)
	//设置飞鸽发送短信需要的参数
	msg := NationMsg{
		Apikey:     nationAccountObj.ak,
		Secret:     nationAccountObj.sk,
		Content:    content,
		Mobile:     telNum,
		TemplateId: templateId,
		SendTime:   time.Now().Unix(),
	}

	//转json
	dataJsonBytes, _ := json.Marshal(msg)
	data := strings.NewReader(string(dataJsonBytes))
	fmt.Println(string(dataJsonBytes))

	resp, err := http.Post(sendNationMsgUrl, "application/json", data)
	if err != nil {
		return err
	}
	bodyText, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	fmt.Printf("%s\n", bodyText)

	return nil
}
