package sms

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"testing"
	"voucher/internal/biz/bo"
	"voucher/internal/biz/do"
)

var config = Config{
	AccessKeyID:     "LTAI5tM1X4HuqUwT8D74qXAH",
	AccessKeySecret: "gxsC1QK12NSKH1HkCqKR1EnMdAy3ad",
	Endpoint:        "dysmsapi.aliyuncs.com",
	SignName:        "蓝色兄弟",
	RetryTimes:      0,
	Timeout:         15,
}

func TestSendSMS(t *testing.T) {

	smsService, err := NewService(config)
	if err != nil {
		t.Errorf("创建短信服务失败: %v", err)
		return
	}

	phoneNumber := ""               // 替换为实际手机号
	templateCode := "SMS_274900579" // 替换为实际模板ID

	params := map[string]string{
		"code": "123456",
	}

	err = smsService.SendSMS(context.Background(), []string{phoneNumber}, templateCode, params)
	if err != nil {
		t.Errorf("发送短信失败: %v", err)
		return
	}

	t.Logf("已发送至 %s\n", phoneNumber)
}

func TestWarningSend(t *testing.T) {

	//warningPersonStr := `[{"tag": "CMB", "name": "李子铭", "mobile": "18666173766"}, {"tag": "LSXD", "name": "赵晋琪", "mobile": "13474987525"}]`
	warningPersonStr := `[{"tag": "CMB", "name": "李子铭", "mobile": "18666173766"}, {"tag": "LSXD", "name": "刘子峰", "mobile": "18900966383"}]`
	var warningPerson []do.WarningPerson
	if err := json.Unmarshal([]byte(warningPersonStr), &warningPerson); err != nil {
		t.Error(err)
		return
	}

	var mobileList []string
	for _, person := range warningPerson {
		mobileList = append(mobileList, person.Mobile)
	}

	req := &do.WxResp{
		Amount:          2,
		AllBudget:       70010,
		AllStock:        35005,
		UsedStock:       9390,
		UsedBudget:      18780,
		AvailableStock:  25615,
		AvailableBudget: 51230,
		StockUsageRate:  20,
	}

	product := &bo.ProductBo{
		ProductNo: "CMB20627186",
		BatchName: "招行2元立减金",
	}
	params := buildTemplateParams(product, req)

	js, _ := json.Marshal(params)

	t.Log(string(js))

	smsService, err := NewService(config)
	if err != nil {
		t.Errorf("创建短信服务失败: %v", err)
		return
	}

	err = smsService.SendSMS(context.Background(), []string{"18666173766", "18900966383"}, "SMS_489660721", params)
	if err != nil {
		t.Errorf("发送短信失败: %v", err)
		return
	}
}

func buildTemplateParams(product *bo.ProductBo, req *do.WxResp) map[string]string {
	return map[string]string{
		"stock_name":        product.BatchName,
		"stock_no":          product.ProductNo,
		"amount":            strconv.Itoa(int(req.Amount)),
		"all_budget":        strconv.Itoa(int(req.AllBudget)),
		"all_stock":         strconv.Itoa(int(req.AllStock)),
		"used_stock":        strconv.Itoa(int(req.UsedStock)),
		"used_budget":       strconv.Itoa(int(req.UsedBudget)),
		"available_budget":  strconv.Itoa(int(req.AvailableBudget)),
		"available_stock":   strconv.Itoa(int(req.AvailableStock)),
		"budget_usage_rate": fmt.Sprintf("%.1f", req.StockUsageRate),
	}
}
