package camel_oil

import (
	"context"
	"fmt"
	v1 "kami/api/camel_oil/v1"
	"kami/internal/consts"
	"kami/internal/dao"
	"kami/internal/model/entity"
	"kami/utility/config"

	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtime"
)

// ====================================================================================
// 账号统计信息
// ====================================================================================

// GetAccountStatistics 获取账号统计信息
func (s *sCamelOil) GetAccountStatistics(ctx context.Context, req *v1.AccountStatisticsReq) (res *v1.AccountStatisticsRes, err error) {
	// 1. 获取账号基本信息
	var account *entity.V1CamelOilAccount
	err = dao.V1CamelOilAccount.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1CamelOilAccount.Columns().Id, req.AccountId).
		Scan(&account)
	if err != nil {
		glog.Error(ctx, "获取账号信息失败", err)
		return nil, err
	}
	if account == nil {
		return nil, fmt.Errorf("账号不存在")
	}

	// 2. 统计订单信息
	m := dao.V1CamelOilOrder.Ctx(ctx).DB(config.GetDatabaseV1())
	m = m.Where(dao.V1CamelOilOrder.Columns().AccountId, req.AccountId)

	// 总订单数
	totalOrders, _ := m.Clone().Count()

	// 已支付订单数
	paidOrders, _ := m.Clone().
		Where(dao.V1CamelOilOrder.Columns().PayStatus, consts.CamelOilPaymentStatusPaid).
		Count()

	// 待支付订单数
	pendingOrders, _ := m.Clone().
		Where(dao.V1CamelOilOrder.Columns().PayStatus, consts.CamelOilPaymentStatusUnpaid).
		Count()

	// 超时订单数
	timeoutOrders, _ := m.Clone().
		Where(dao.V1CamelOilOrder.Columns().PayStatus, consts.CamelOilPaymentStatusTimeout).
		Count()

	// 3. 查询近7天订单趋势（使用假数据）
	recentTrend := make([]struct {
		Date       string `json:"date" description:"日期"`
		OrderCount int    `json:"orderCount" description:"订单数"`
	}, 0)

	for i := 6; i >= 0; i-- {
		date := gtime.Now().AddDate(0, 0, -i).Format("Y-m-d")
		count := 0
		if i <= 3 {
			count = 2 // 最近几天有订单
		}
		recentTrend = append(recentTrend, struct {
			Date       string `json:"date" description:"日期"`
			OrderCount int    `json:"orderCount" description:"订单数"`
		}{
			Date:       date,
			OrderCount: count,
		})
	}

	// 4. 计算使用情况
	onlineDuration := "0小时"
	if account.LastLoginAt != nil && account.Status == int(consts.CamelOilAccountStatusOnline) {
		duration := gtime.Now().Sub(account.LastLoginAt)
		hours := int(duration.Hours())
		onlineDuration = fmt.Sprintf("%d小时", hours)
	}

	lastUsedAt := "-"
	if account.LastUsedAt != nil {
		lastUsedAt = account.LastUsedAt.String()
	}

	// 计算日均订单数
	avgOrdersDaily := 0
	if totalOrders > 0 && account.CreatedAt != nil {
		days := int(gtime.Now().Sub(account.CreatedAt).Hours() / 24)
		if days > 0 {
			avgOrdersDaily = totalOrders / days
		}
	}

	// 5. 组装响应数据
	res = &v1.AccountStatisticsRes{}

	// 账号基本信息
	res.AccountInfo.AccountId = account.Id
	res.AccountInfo.AccountName = account.AccountName
	res.AccountInfo.Phone = maskPhone(account.Phone)
	res.AccountInfo.Status = consts.CamelOilAccountStatus(account.Status)
	res.AccountInfo.LastUsedAt = account.LastUsedAt
	res.AccountInfo.LastLoginAt = account.LastLoginAt
	res.AccountInfo.TokenExpireAt = account.TokenExpireAt

	// 订单统计
	res.OrderStats.TotalOrders = totalOrders
	res.OrderStats.PaidOrders = paidOrders
	res.OrderStats.PendingOrders = pendingOrders
	res.OrderStats.TimeoutOrders = timeoutOrders
	res.OrderStats.DailyOrderCount = account.DailyOrderCount
	res.OrderStats.RemainingOrders = 10 - account.DailyOrderCount

	// 使用情况
	res.UsageInfo.OnlineDuration = onlineDuration
	res.UsageInfo.LastUsedAt = lastUsedAt
	res.UsageInfo.AvgOrdersDaily = avgOrdersDaily

	// 近期趋势
	res.RecentTrend = recentTrend

	return res, nil
}
