package ding

import (
	"fmt"
	"strings"
	"testing"
	"voucher/internal/biz/bo"
	"voucher/internal/biz/do"
)

func TestSendTextMessage(t *testing.T) {
	webhookURL := "your_webhook_url"
	secret := "your_secret"

	client := NewDingTalkClient(webhookURL, secret)

	// 发送文本消息
	content := "这是一条测试文本消息，@相关人员。"
	atMobiles := []string{"13800138000"}
	isAtAll := false

	err := client.SendTextMessage(content, atMobiles, isAtAll)
	if err != nil {
		fmt.Println("文本消息发送失败:", err)
	} else {
		fmt.Println("文本消息发送成功")
	}
}

func TestSendLinkMessage(t *testing.T) {
	title := "测试链接消息"
	text := "这是一条测试链接消息的详细内容，@相关人员。"
	messageURL := "https://example.com"
	picURL := "https://example.com/pic.jpg"

	webhookURL := "your_webhook_url"
	secret := "your_secret"

	atMobiles := []string{"13800138000"}

	client := NewDingTalkClient(webhookURL, secret)
	err := client.SendLinkMessage(title, text, messageURL, picURL, atMobiles, false)
	if err != nil {
		fmt.Println("链接消息发送失败:", err)
	} else {
		fmt.Println("链接消息发送成功")
	}
}

func TestSendMarkdownMessage(t *testing.T) {
	markdownTitle := "测试 Markdown 消息"

	//markdownText := "# <font color='green'><h1>立减金发放平台报警通知</h1></font> \n<font color='black'>不好了，订单发放发生异常了，错误内容[<font color='#FFA500'>批次号不存在</font>]@相关人员。</font>"
	markdownText := alarmText("批次号不存在")

	atMobiles := []string{"18666173766", "15102807142"}

	webhookURL := "https://oapi.dingtalk.com/robot/send?access_token=5f10c2213cbf8168985cb2d061ebb1a5f70bd1dd47ec7cef58fa6fe545d52588"
	secret := "SEC77b63d70a9e22317144e712b4538ce1e0013db885c65f7f9bae283e8958b39eb"

	client := NewDingTalkClient(webhookURL, secret)
	if err := client.SendMarkdownMessage(markdownTitle, markdownText, atMobiles, false); err != nil {
		fmt.Println("Markdown 消息发送失败:", err)
	} else {
		fmt.Println("Markdown 消息发送成功")
	}
}

func alarmText(errMsg string) string {

	remarks := fmt.Sprintf("订单号:%s，商品编号:%s,原因:%s", "123456", "001", errMsg)

	msg := "# <font color='green'>" +
		"<h1>立减金发放平台报警通知</h1>" +
		"</font> \n" +
		"<font color='black'>" +
		"不好了，订单发放发生异常了" +
		"[<font color='red'>%s</font>]请尽快处理@相关人员。" +
		"</font>"

	return fmt.Sprintf(msg, remarks)
}

func TestSend(t *testing.T) {
	webhookURL := "your_webhook_url"
	secret := "your_secret"

	client := NewDingTalkClient(webhookURL, secret)

	// 发送文本消息
	content := "这是一条测试文本消息，@相关人员。"
	atMobiles := []string{"13800138000"}

	err := client.SendTextMessage(content, atMobiles, false)
	if err != nil {
		fmt.Println("文本消息发送失败:", err)
	} else {
		fmt.Println("文本消息发送成功")
	}

	// 发送链接消息
	title := "测试链接消息"
	text := "这是一条测试链接消息的详细内容，@相关人员。"
	messageURL := "https://example.com"
	picURL := "https://example.com/pic.jpg"

	err = client.SendLinkMessage(title, text, messageURL, picURL, atMobiles, false)
	if err != nil {
		fmt.Println("链接消息发送失败:", err)
	} else {
		fmt.Println("链接消息发送成功")
	}

	// 发送 Markdown 消息
	markdownTitle := "测试 Markdown 消息"
	markdownText := "# 标题\n这是一条测试 Markdown 消息的详细内容，@13800138000。"

	err = client.SendMarkdownMessage(markdownTitle, markdownText, atMobiles, false)
	if err != nil {
		fmt.Println("Markdown 消息发送失败:", err)
	} else {
		fmt.Println("Markdown 消息发送成功")
	}
}

func TestWarningBudgetText(t *testing.T) {

	req := do.WarningBudget{
		StockName:       "招行2元立减金",
		StockId:         "20627186",
		StockNo:         "CMB20627186",
		Amount:          2,
		AllBudget:       70010,
		AllStock:        35005,
		UsedStock:       9390,
		UsedBudget:      18780,
		AvailableStock:  25615,
		RemainingBudget: 51230,
	}

	str := formatAsCard(req)
	t.Log("\n" + str)

	markdownTitle := "批次预算预警"

	atMobiles := []string{"18666173766"}

	webhookURL := "https://oapi.dingtalk.com/robot/send?access_token=5f10c2213cbf8168985cb2d061ebb1a5f70bd1dd47ec7cef58fa6fe545d52588"
	secret := "SEC77b63d70a9e22317144e712b4538ce1e0013db885c65f7f9bae283e8958b39eb"

	client := NewDingTalkClient(webhookURL, secret)

	if err := client.SendMarkdownMessage(markdownTitle, str, atMobiles, false); err != nil {
		fmt.Println("Markdown 消息发送失败:", err)
	} else {
		fmt.Println("Markdown 消息发送成功")
	}
}

func formatAsCard(req do.WarningBudget) string {
	var card strings.Builder

	card.WriteString("### " + req.StockName + "\n\n")

	// 基本信息
	card.WriteString("#### 🎫 基本信息\n")
	card.WriteString(fmt.Sprintf("- **批次号**: %s\n", req.StockId))
	card.WriteString(fmt.Sprintf("- **活动号**: %s\n", req.StockNo))
	card.WriteString(fmt.Sprintf("- **面额**: %d元\n", req.Amount))
	card.WriteString(fmt.Sprintf("- **总预算**: %d元\n", req.AllBudget))
	card.WriteString(fmt.Sprintf("- **总库存**: %d张\n", req.AllStock))
	card.WriteString("\n")

	// 使用情况
	card.WriteString("#### 📊 使用情况\n")
	card.WriteString(fmt.Sprintf("- **已发券数**: %d张\n", req.UsedStock))
	card.WriteString(fmt.Sprintf("- **已发券金额**: %d元\n", req.UsedBudget))
	card.WriteString(fmt.Sprintf("- **剩余库存**: %d张\n", req.AvailableStock))
	card.WriteString(fmt.Sprintf("- **剩余预算**: %d元\n", req.RemainingBudget))
	card.WriteString("\n")

	// 使用率
	stockUsageRate := float64(req.UsedStock) / float64(req.AllStock) * 100

	card.WriteString("#### 📈 使用率\n")
	card.WriteString(fmt.Sprintf("- **使用率**: %.1f%%\n", stockUsageRate))

	return card.String()
}

func TestOrderFailSend(t *testing.T) {

	order := &bo.OrderBo{
		OrderNo:    "20231101001",
		OutBizNo:   "CMB_20231101001",
		VoucherNo:  "123456",
		ProductNo:  "CMB202020",
		BatchNo:    "202020",
		Account:    "oUx7j0xxdcdergdaegasfcg",
		AppID:      "app_123456gadabout",
		MerchantNo: "185585225542",
	}
	markdownText := alarmText2(order, "测试，券发放异常通知，Post https://api.mch.weixin.qq.com/v3/marketing/favor/users/oW97fjtVl8wHarrDpptBvQQKKu7Q/coupons: EOF")
	t.Logf("\n%s", markdownText)

	markdownTitle := "测试 Markdown 消息"
	atMobiles := []string{"18666173766"}

	webhookURL := "https://oapi.dingtalk.com/robot/send?access_token=5f10c2213cbf8168985cb2d061ebb1a5f70bd1dd47ec7cef58fa6fe545d52588"
	secret := "SEC77b63d70a9e22317144e712b4538ce1e0013db885c65f7f9bae283e8958b39eb"

	client := NewDingTalkClient(webhookURL, secret)
	if err := client.SendMarkdownMessage(markdownTitle, markdownText, atMobiles, false); err != nil {
		fmt.Println("Markdown 消息发送失败:", err)
	} else {
		fmt.Println("Markdown 消息发送成功")
	}
}

func alarmText2(order *bo.OrderBo, errMsg string) string {
	var card strings.Builder

	// 警示信息（简化版）
	card.WriteString("⚠️ **券发放异常** ⚠️\n\n")

	// 订单信息（通过引用和代码块模拟小字体）
	card.WriteString("> **订单信息：**\n\n")
	card.WriteString(fmt.Sprintf("> AppID: `%s`\n\n", order.AppID))
	card.WriteString(fmt.Sprintf("> OpenID: `%s`\n\n", order.Account))
	card.WriteString(fmt.Sprintf("> 批次号: `%s`\n\n", order.BatchNo))
	card.WriteString(fmt.Sprintf("> 活动号: `%s`\n\n", order.ProductNo))
	card.WriteString(fmt.Sprintf("> 订单号: `%s`\n\n", order.OrderNo))
	card.WriteString(fmt.Sprintf("> 招行订单号: `%s`\n", order.OutBizNo))
	card.WriteString("\n")

	// 报警原因（通过引用和代码块模拟小字体）
	card.WriteString("> **❗ 报警原因：**\n\n")
	card.WriteString(fmt.Sprintf("> `%s`\n", errMsg))

	return card.String()
}
