package mesqueue

import (
	"fmt"
	"goutil/fileUtil"
	"goutil/logUtilPlus"
	"goutil/webUtil"
	"time"
)

type GameMsg struct {

	//订单id
	OrderID int64

	//玩家id
	PlayerID string

	//区服id
	ServerID int64

	//游戏id
	GameId string

	//充值金额
	price int64

	// 充值商品id
	storeId int64

	// 推送次数
	pushCount int32
}

var (
	//消息队列
	msgQueue = make(chan GameMsg, 100)

	fileName = "ErrPushMsg"
)

func init() {
	go ConsumeQueue()
}

// AddQueue 添加消息队列
func AddQueue(gameMsg GameMsg) {
	msgQueue <- gameMsg
}

// ConsumeQueue 消费消息队列
func ConsumeQueue() {
	//捕获异常
	defer func() {
		if err := recover(); err != nil {
			//TODO 捕获异常
			logUtilPlus.ErrorLog("推送充值信息到game异常 err:%s", err)

			//重新开启
			restartConsumer()
		}
	}()

	for {
		gameMsg := <-msgQueue

		url := fmt.Sprintf("http://www.game.com/pay %s", gameMsg.GameId)

		//消费消息队列 推送重置信息到game
		result, err := webUtil.GetWebData(url, map[string]string{})
		if err != nil {
			logUtilPlus.ErrorLog("推送充值信息到game异常 err:%s", err)

			//放入消息队列重新推送
			if gameMsg.pushCount < 3 {
				msgQueue <- gameMsg
				gameMsg.pushCount++
			} else { //加入文件放弃推送
				WriteErrPushMsg(url)
			}
		}

		if string(result) != "" {

		}
	}
}

// WriteErrPushMsg 推送异常消息 写入文件
func WriteErrPushMsg(messages string) {

	//文件名拼接
	filePath := fileName + "/" + time.Now().Format("2006-01-02")
	fileName := time.Now().Format("2006-01-02 09") + ".txt"

	//消息 添加换行符
	messages += ";\r\n"
	err := fileUtil.WriteFile(filePath, fileName, true, messages)
	if err != nil {
		logUtilPlus.ErrorLog(" MegPush 写入文件失败 err:%s", err)
	}
}

// restartConsumer 重启消费者
func restartConsumer() {
	// 设置重试次数
	maxRetries := 5
	retryCount := 0

	for {
		select {
		case <-time.After(5 * time.Second): // 等待5秒后重试
			if retryCount >= maxRetries {
				logUtilPlus.ErrorLog("消费者重启失败，达到最大重试次数")
				return
			}
			logUtilPlus.InfoLog("重新启动消费者，重试次数: %d", retryCount+1)
			go ConsumeQueue()
			return
		}
		retryCount++
	}
}
