package handler

import (
	"encoding/json"
	"errors"
	"gitee.ltd/lxh/wechat-robot/internal/config"
	"gitee.ltd/lxh/wechat-robot/internal/tasks"
	"gitee.ltd/lxh/xybot"
	"github.com/gofiber/fiber/v2/log"
	"strconv"
	"time"

	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"

	"gitee.ltd/lxh/wechat-robot/internal/model"
)

// CheckQRCodeStatus 检查二维码状态
func CheckQRCodeStatus(c *fiber.Ctx) error {
	id, err := strconv.Atoi(c.Params("id"))
	if err != nil {
		return c.JSON(fiber.Map{
			"success": false,
			"message": "无效的机器人ID",
		})
	}

	uuid := c.Query("uuid")
	if uuid == "" {
		return c.JSON(fiber.Map{
			"success": false,
			"message": "UUID参数缺失",
		})
	}

	// 获取机器人实例
	db := model.GetDB()
	var robot model.Robot
	if err = db.First(&robot, id).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return c.JSON(fiber.Map{
				"success": false,
				"message": "机器人不存在",
			})
		}
		return c.JSON(fiber.Map{
			"success": false,
			"message": "查询数据库失败",
		})
	}

	// 调用CheckUuid API检查二维码状态，传递容器访问地址
	robotCli, err := xybot.NewClient(robot.WechatID, robot.ContainerHost, false)
	if err != nil {
		return c.JSON(fiber.Map{
			"success": false,
			"message": "创建微信客户端失败: " + err.Error(),
		})
	}
	response, err := robotCli.Login.CheckUuid(uuid)
	if err != nil {
		return c.JSON(fiber.Map{
			"success": false,
			"message": "检查二维码状态失败: " + err.Error(),
		})
	}

	if cfg, _ := config.Load(); cfg.Server.Env == "development" {
		bs, _ := json.Marshal(response)
		log.Debugf("扫码返回结果: %s", bs)
	}

	// 如果返回status=1，表示已扫码，暂存一下昵称和头像
	if response.Status == 1 {
		robot.Nickname = response.NickName
		robot.Avatar = response.HeadImgUrl
		db.Save(&robot)
	}

	// 如果检测到已登录，更新机器人状态
	if response.AcctSectResp.Username != "" {
		response.Status = 99
		robot.WechatID = response.AcctSectResp.Username

		// 开启自动心跳，传递容器访问地址
		if robot.WechatID != "" {
			_ = robotCli.Login.AutoHeartbeatStart()
		}

		// 更新机器人状态
		robot.Status = model.RobotStatusOnline
		now := time.Now()
		robot.LastLoginAt = &now
		db.Save(&robot)

		// 添加定时任务
		tasks.AddJob(robot)
	}

	return c.JSON(fiber.Map{
		"success":  true,
		"status":   response.Status,
		"message":  "success",
		"userInfo": response.AcctSectResp,
	})
}
