package camel_oil

import (
	"context"
	"kami/internal/consts"
	"kami/internal/dao"
	"kami/utility/config"

	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/glog"
)

// ====================================================================================
// 可用订单容量管理相关方法
// ====================================================================================

// GetAvailableOrderCapacity 获取当前可用订单容量
// 计算所有在线账号的剩余可下单数之和
func (s *sCamelOil) GetAvailableOrderCapacity(ctx context.Context) (capacity int, err error) {
	m := dao.V1CamelOilAccount.Ctx(ctx).DB(config.GetDatabaseV1())

	// 查询所有在线账号
	type CapacityResult struct {
		TotalCapacity int `json:"total_capacity"`
	}

	var result CapacityResult
	err = m.Where(dao.V1CamelOilAccount.Columns().Status, consts.CamelOilAccountStatusOnline).
		Fields("SUM(10 - " + dao.V1CamelOilAccount.Columns().DailyOrderCount + ") as total_capacity").
		Scan(&result)

	if err != nil {
		return 0, gerror.Wrap(err, "查询可用订单容量失败")
	}

	return result.TotalCapacity, nil
}

// GetAccountPoolStatus 获取账号池状态统计
func (s *sCamelOil) GetAccountPoolStatus(ctx context.Context) (status map[string]interface{}, err error) {
	m := dao.V1CamelOilAccount.Ctx(ctx).DB(config.GetDatabaseV1())

	// 统计各状态账号数量
	type StatusCount struct {
		Status int `json:"status"`
		Count  int `json:"count"`
	}

	var statusCounts []StatusCount
	err = m.Fields(dao.V1CamelOilAccount.Columns().Status + ", COUNT(*) as count").
		Group(dao.V1CamelOilAccount.Columns().Status).
		Scan(&statusCounts)

	if err != nil {
		return nil, gerror.Wrap(err, "统计账号状态失败")
	}

	// 构建结果
	result := map[string]interface{}{
		"pending":    0, // 待登录
		"logging_in": 0, // 登录中
		"online":     0, // 在线
		"paused":     0, // 已暂停
		"invalid":    0, // 已失效
		"total":      0, // 总数
	}

	for _, sc := range statusCounts {
		switch sc.Status {
		case int(consts.CamelOilAccountStatusPending):
			result["pending"] = sc.Count
		case int(consts.CamelOilAccountStatusSendCode):
			result["logging_in"] = sc.Count
		case int(consts.CamelOilAccountStatusOnline):
			result["online"] = sc.Count
		case int(consts.CamelOilAccountStatusPaused):
			result["paused"] = sc.Count
		case int(consts.CamelOilAccountStatusInvalid):
			result["invalid"] = sc.Count
		}
		result["total"] = result["total"].(int) + sc.Count
	}

	// 获取可用订单容量
	capacity, err := s.GetAvailableOrderCapacity(ctx)
	if err != nil {
		glog.Error(ctx, "获取可用订单容量失败", err)
	} else {
		result["available_capacity"] = capacity
	}

	return result, nil
}
