package models

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"regexp"
	"strconv"
	"strings"

	"github.com/eatmoreapple/openwechat"
	"github.com/joho/godotenv"
	"github.com/tidwall/gjson"
)

type OpenChatZ struct {
	ExceArr  map[int]string
	Self     *openwechat.Self
	Groups   openwechat.Groups
	KdNumber int
}

func (ggg *OpenChatZ) Setup() *OpenChatZ {
	ggg.ExceArr = map[int]string{
		0: "查物流",
		1: "拦截",
		2: "改地址",
		3: "查重",
		4: "催件",
		5: "核实签收",
		6: "破损",
		7: "遗失",
	}
	return ggg

}
func (ggg *OpenChatZ) hasThirteenConsecutiveDigits(s string) bool {
	// 定义匹配连续13位数字的正则表达式
	pattern := regexp.MustCompile(`\d{13}`)
	return pattern.MatchString(s)
}

/*
*
去除html标签，过滤html标签
*/
func (ggg *OpenChatZ) TrimHtml(src string) string {
	//将HTML标签全转换成小写
	re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllStringFunc(src, strings.ToLower)
	//去除STYLE
	re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
	src = re.ReplaceAllString(src, "")
	//去除SCRIPT
	re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
	src = re.ReplaceAllString(src, "")
	//去除所有尖括号内的HTML代码，并换成换行符
	re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllString(src, "\n")
	//去除连续的换行符
	re, _ = regexp.Compile("\\s{2,}")
	src = re.ReplaceAllString(src, "\n")
	return strings.TrimSpace(src)
}

// 发送http post请求数据为form
func (ggg *OpenChatZ) PostForm(url string, data url.Values) (string, error) {
	resp, err := http.PostForm(url, data)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	content, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(content), nil
}
func (ggg *OpenChatZ) SendTextGroupZ(groupName, msg string) {
	// 遍历群组，找到目标群并发送消息
	for _, group := range ggg.Groups {
		fmt.Println(group.NickName)
		if group.NickName == groupName {
			// 发送文本消息
			_, err := ggg.Self.SendTextToGroup(group, msg)
			if err != nil {
				fmt.Println("发送消息失败：", err)
			}
		}
	}
}
func (ggg *OpenChatZ) Start() {

	err := godotenv.Load(".env")
	myUID := ""
	myNicname := ""

	// 读取环境变量
	api := os.Getenv("API_BASE")
	entId := os.Getenv("API_ENT_ID")
	replyType := os.Getenv("REPLY_TYPE")
	bot := openwechat.DefaultBot(openwechat.Desktop) // 桌面模式

	// 注册消息处理函数
	bot.MessageHandler = func(msg *openwechat.Message) {

		if msg.IsText() {

			log.Printf("收到消息：%s\n", msg.Content)

			isSend := false
			//群聊
			if msg.IsSendByGroup() {
				sender, err := msg.SenderInGroup()
				if err == nil {
					log.Println("消息发送者：" + sender.NickName)
				}
				if strings.Contains(msg.Content, "@"+myNicname) {
					msg.Content = strings.TrimSpace(strings.ReplaceAll(msg.Content, "@"+myNicname, ""))
					isSend = true
				} else {
					isSend = false
				}
			} else {
				//单聊
				sender, err := msg.Sender()
				if err == nil {
					log.Println("消息发送者：" + sender.NickName)
				}
				if replyType != "GROUP" {
					isSend = true
				}
			}
			//字符串装是否含有13位连续的数字
			if ggg.hasThirteenConsecutiveDigits(msg.Content[0:13]) {
				//如果输入单号错误为14位数字也不会触发
				_, errInt := strconv.Atoi(msg.Content[13:14])
				if errInt != nil {
					tmpNumber := msg.Content[0:13]
					tmpKdNumber, _ := strconv.Atoi(tmpNumber)
					ggg.KdNumber = tmpKdNumber
					selectTmp := []rune(msg.Content)
					selectStr := string(selectTmp[0:22])
					for _, v := range ggg.ExceArr {
						if strings.Contains(selectStr, v) {
							if v == "查物流" {
								// 遍历群组，找到目标群并发送消息
								ggg.SendTextGroupZ("群快递机器人助手研发", "接收到"+tmpNumber+" "+v+" 指令,准备执行命令")
								break
							}
							if v == "拦截" {
								// 遍历群组，找到目标群并发送消息
								ggg.SendTextGroupZ("群快递机器人助手研发", "接收到"+tmpNumber+" "+v+" 指令,准备执行命令")
								break
							}
							if v == "改地址" {
								// 遍历群组，找到目标群并发送消息
								ggg.SendTextGroupZ("群快递机器人助手研发", "接收到"+tmpNumber+" "+v+" 指令,准备执行命令")
								break
							}
							if v == "查重" {
								// 遍历群组，找到目标群并发送消息
								ggg.SendTextGroupZ("群快递机器人助手研发", "接收到"+tmpNumber+" "+v+" 指令,准备执行命令")
								break
							}
							if v == "催件" {
								// 遍历群组，找到目标群并发送消息
								ggg.SendTextGroupZ("群快递机器人助手研发", "接收到"+tmpNumber+" "+v+" 指令,准备执行命令")
								break
							}
							if v == "核实签收" {
								// 遍历群组，找到目标群并发送消息
								ggg.SendTextGroupZ("群快递机器人助手研发", "接收到"+tmpNumber+" "+v+" 指令,准备执行命令")
								break
							}
							if v == "破损" {
								// 遍历群组，找到目标群并发送消息
								ggg.SendTextGroupZ("群快递机器人助手研发", "接收到"+tmpNumber+" "+v+" 指令,准备执行命令")
								break
							}
							if v == "遗失" {
								// 遍历群组，找到目标群并发送消息
								ggg.SendTextGroupZ("群快递机器人助手研发", "接收到"+tmpNumber+" "+v+" 指令,准备执行命令")
								break
							}

						}
					}
				}
			}
			if isSend {
				data := url.Values{}
				data.Set("ent_id", entId)
				data.Set("visitor_id", msg.MsgId)
				data.Set("content", msg.Content)
				res, err := ggg.PostForm(api, data)
				if err == nil {
					r := gjson.Get(res, "result.content").String()
					r = ggg.TrimHtml(r)
					msg.ReplyText(r)
				}
			}

		}
	}
	// 注册登陆二维码回调
	bot.UUIDCallback = openwechat.PrintlnQrcodeUrl

	// 登陆
	if err := bot.Login(); err != nil {
		fmt.Println(err)
		return
	}

	// 获取登陆的用户
	selfs, err := bot.GetCurrentUser()
	if err != nil {
		fmt.Println(err)
		return
	}
	ggg.Self = selfs
	// 获取所有的群组

	group, err := ggg.Self.Groups()
	fmt.Println(group.Count())
	if err != nil {
		fmt.Println(err)
		return
	}
	ggg.Groups = group
	// 遍历群组列表并打印群组名称和ID
	for _, vv := range ggg.Groups {
		fmt.Printf("群组名称: %s, 群组ID: %d\n", vv.NickName, vv.ID)
	}

	myUID = string(ggg.Self.ID())
	myNicname = ggg.Self.NickName
	log.Printf("当前登录用户：%s,uid：%s \n", myNicname, myUID)
	// 获取所有的好友
	//friends, err := self.Friends()
	//fmt.Println(friends, err)

	// 获取所有的群组
	//groups, err := self.Groups()
	//fmt.Println(groups, err)

	// 阻塞主goroutine, 直到发生异常或者用户主动退出
	bot.Block()

}
