package beatleader

import (
	"log"
	"os"
	"strconv"
	"sync"

	"git.lxtend.com/qqbot/constants"
	"git.lxtend.com/qqbot/handler"
	"git.lxtend.com/qqbot/message"
	"git.lxtend.com/qqbot/model"
	"git.lxtend.com/qqbot/service/beatleader"
	"git.lxtend.com/qqbot/util"
)

func init() {
	handler.RegisterHandler("查bl", getMyBL, constants.LEVEL_USER)
	handler.RegisterHelpInform("查bl", "beatleader", "查bl 查看您的最新分数")
	handler.RegisterHandler("绑定bl", bindBL, constants.LEVEL_USER)
	handler.RegisterHelpInform("绑定bl", "beatleader", "绑定bl 绑定您的beatleader账号")
	handler.RegisterHandler("解绑bl", unbindBL, constants.LEVEL_USER)
	handler.RegisterHelpInform("解绑bl", "beatleader", "解绑bl 解绑您的beatleader账号")
	handler.RegisterHandler("最新bl", getMyRecentScore, constants.LEVEL_USER)
	handler.RegisterHelpInform("最新bl", "beatleader", "最新bl 查看您的最新游戏记录")
	handler.RegisterHandler("最热bl", getRecentScore, constants.LEVEL_USER)
	handler.RegisterHelpInform("最热bl", "beatleader", "最热bl 查看全大陆的最新游戏记录")
	handler.RegisterHandler("截bl", screenShotBL, constants.LEVEL_USER)
	handler.RegisterHelpInform("截bl", "beatleader", "截bl 截bl 截bl主页截图")
	handler.RegisterHandler("jbl", screenShotBL, constants.LEVEL_USER)
}

func getMyBL(msg model.Message) (reply model.Reply) {
	var (
		resultStr  string
		err        error
		maxRetries = 3 // 最大重试次数
		attempts   = 0
	)

	userIdStr := strconv.Itoa(int(msg.UserId))
	for attempts < maxRetries {
		resultStr, err = beatleader.BLQuery.GetScore(userIdStr)
		if err == nil {
			break // 成功时退出循环
		}
		attempts++
		log.Printf("获取分数时出错，第 %d 次重试: %v", attempts, err)
	}

	// 如果所有尝试都失败，返回适当的错误消息
	if err != nil {
		resultStr = "获取您的分数时出现问题，请稍后重试。"
	}

	return model.Reply{
		ReplyMsg:       resultStr,
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}
func bindBL(msg model.Message) (reply model.Reply) {
	if len(msg.RawMsg) <= len("绑定bl ") {
		return model.Reply{
			ReplyMsg:       "请输入绑定的beatleader账号",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	return model.Reply{
		ReplyMsg:       beatleader.BLQuery.BindBL(strconv.Itoa(int(msg.UserId)), msg.RawMsg[len("绑定bl "):]),
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}

func unbindBL(msg model.Message) (reply model.Reply) {
	return model.Reply{
		ReplyMsg:       beatleader.BLQuery.UnbindBL(strconv.Itoa(int(msg.UserId))),
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}

func getRecentScore(msg model.Message) (reply model.Reply) {
	count := 1
	if len(msg.RawMsg) > len("最热bl ") {
		var err error
		count, err = strconv.Atoi(msg.RawMsg[len("最热bl "):])
		if err != nil || count <= 0 {
			return model.Reply{
				ReplyMsg:       "",
				ReferOriginMsg: true,
				FromMsg:        msg,
			}
		}
		if count > 10 {
			count = 10
		}
	}
	scoreMsg := ""
	for _, v := range beatleader.BlScoresManager.GetRecentScores(count, " WHERE country = 'CN' ") {
		scoreMsg += v.ToString() + "\n\n"
	}
	if len(scoreMsg) > 0 {
		scoreMsg = scoreMsg[:len(scoreMsg)-len("\n\n")]
	}
	return model.Reply{
		ReplyMsg:       scoreMsg,
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}

func getMyRecentScore(msg model.Message) (reply model.Reply) {
	count := 1
	scoreMsg := ""
	if len(msg.RawMsg) > len("最新bl ") {
		var err error
		count, err = strconv.Atoi(msg.RawMsg[len("最新bl "):])
		if err != nil || count <= 0 {
			return model.Reply{
				ReplyMsg:       "",
				ReferOriginMsg: true,
				FromMsg:        msg,
			}
		}
		if count > 10 {
			count = 10
		}
	}
	var userName string
	recordCount := 0
	records, err := beatleader.BLQuery.GetRecentScores(count, strconv.Itoa(int(msg.UserId)))
	if err != nil {
		return model.Reply{
			ReplyMsg:       err.Error(),
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	// 单独线程下载封面图片
	coverImageMap := make(map[string]string)
	wg := sync.WaitGroup{}
	for _, record := range records {
		coverImageMap[record.SongHash] = record.CoverImage
		wg.Add(1)
		go func(songHash string) {
			defer wg.Done()
			//文件存在则跳过
			if _, err := os.Stat(util.GetResizedIamgePathByOrgPath(util.GenTempFilePath(songHash + ".png"))); err == nil {
				return
			}
			util.DownloadFile(coverImageMap[songHash], util.GenTempFilePath(songHash+".png"))
			newPath, err := util.ResizeImageByMaxHeight(util.GenTempFilePath(songHash+".png"), 20)
			os.Remove(util.GenTempFilePath(songHash + ".png"))
			if err != nil {
				log.Printf("缩放图片失败: %v", err)
			}
			coverImageMap[songHash] = newPath
		}(record.SongHash)
	}
	wg.Wait()
	for _, record := range records {
		scoreMsg += record.ToString() + "\n\n"
		userName = record.Name
		recordCount++
	}
	if len(scoreMsg) > 0 {
		scoreMsg = scoreMsg[:len(scoreMsg)-len("\n\n")] //去掉最后一个换行符
	} else {
		return model.Reply{
			ReplyMsg:       "无最近游戏记录",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	return model.Reply{
		ReplyMsg:       "玩家 " + userName + " 的" + strconv.Itoa(recordCount) + "条最近记录为：\n" + scoreMsg,
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}

func screenShotBL(msg model.Message) (reply model.Reply) {
	imageMsg := message.ImageMessage{
		Type: "image",
		Data: message.ImageMessageData{
			File: "file:///tmp/qqbot/" + beatleader.GetBLPicture(strconv.Itoa(int(msg.UserId))),
		},
	}
	return model.Reply{
		ReplyMsg:       imageMsg.ToCQString(),
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}
