package admin_agent

import (
	"context"
	"fmt"
	"time"

	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminGetAgentOrderStatisticsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminGetAgentOrderStatisticsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminGetAgentOrderStatisticsLogic {
	return &AdminGetAgentOrderStatisticsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminGetAgentOrderStatisticsLogic) AdminGetAgentOrderStatistics(req *types.AdminGetAgentOrderStatisticsReq) (resp *types.AdminGetAgentOrderStatisticsResp, err error) {
	// 获取今日的开始和结束时间
	today := time.Now()
	startOfDay := time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, today.Location())
	endOfDay := startOfDay.Add(24 * time.Hour)

	// 构建查询条件
	builder := l.svcCtx.AgentOrderModel.SelectBuilder()

	// 查询总代理订单数
	totalBuilder := builder
	totalAgentOrderCount, err := l.svcCtx.AgentOrderModel.FindCount(l.ctx, totalBuilder, "id")
	if err != nil {
		logx.Errorf("查询总代理订单数失败: %v", err)
		return nil, fmt.Errorf("查询总代理订单数失败: %w", err)
	}

	// 查询今日代理订单数
	todayBuilder := builder.Where("create_time >= ? AND create_time < ?", startOfDay, endOfDay)
	todayAgentOrderCount, err := l.svcCtx.AgentOrderModel.FindCount(l.ctx, todayBuilder, "id")
	if err != nil {
		logx.Errorf("查询今日代理订单数失败: %v", err)
		return nil, fmt.Errorf("查询今日代理订单数失败: %w", err)
	}

	// 构建响应
	resp = &types.AdminGetAgentOrderStatisticsResp{
		TotalAgentOrderCount: totalAgentOrderCount,
		TodayAgentOrderCount: todayAgentOrderCount,
	}

	return resp, nil
}
