package zhimeng

import (
	"applet/app/utils"
	"applet/app/utils/logx"
	"code.fnuoos.com/go_rely_warehouse/zyos_go_third_party_api.git/sms"
	"encoding/json"
	"xorm.io/xorm"
)

// 查询数量
func SmsNum(engine *xorm.Engine, dbName, smsType, appKey, appSecret string) (int, error) {
	if smsType == "1" { //新的
		num := sms.SmsNumGetSmsNum(engine, "putong", dbName)
		return num, nil
	}
	params := map[string]interface{}{
		"appkey":     appKey,
		"secret_key": appSecret,
	}
	resp, err := Send("send_msg", "msg_num", params)
	if err != nil {
		return 0, logx.Warn(err)
	}
	var tmp struct {
		Msg     string `json:"msg"`
		Success int    `json:"success"`
		Data    struct {
			Count string `json:"count"`
		} `json:"data"`
	}
	if err = json.Unmarshal(resp, &tmp); err != nil {
		return 0, logx.Warn("[resp]: " + string(resp) + ", [err]:" + err.Error())
	}
	return utils.StrToInt(tmp.Data.Count), nil
}

func SmsToSend(engine *xorm.Engine, dbName, smsType, appKey, appSecret, content, phone string) (int, error) {
	if smsType == "1" { //新的
		args := map[string]interface{}{
			"mobile":   phone,
			"content":  content,
			"sms_type": "putong",
			"uid":      dbName,
		}
		err := sms.SmsSend(engine, args)
		if err != nil {
			return 0, err
		}
		return 1, nil
	}
	params := map[string]interface{}{
		"appkey":     appKey,
		"secret_key": appSecret,
		"mobile":     phone,
		"content":    content,
	}
	resp, err := Send("send_msg", "msg_doing", params)
	if err != nil {
		return 0, logx.Warn(err)
	}
	var tmp struct {
		Msg     string `json:"msg"`
		Success int    `json:"success"`
	}
	if err = json.Unmarshal(resp, &tmp); err != nil {
		return 0, logx.Warn("[resp]: " + string(resp) + ", [err]:" + err.Error())
	}
	return tmp.Success, nil
}
