package admin_agent

import (
	"context"
	"fmt"
	"time"

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

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

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

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

func (l *AdminGetWithdrawalStatisticsLogic) AdminGetWithdrawalStatistics(req *types.AdminGetWithdrawalStatisticsReq) (resp *types.AdminGetWithdrawalStatisticsResp, 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.AgentWithdrawalModel.SelectBuilder()

	// 查询总提现金额（status=2表示成功）
	totalBuilder := builder.Where("status = ?", 2)
	totalWithdrawalAmount, err := l.svcCtx.AgentWithdrawalModel.FindSum(l.ctx, totalBuilder, "amount")
	if err != nil {
		logx.Errorf("查询总提现金额失败: %v", err)
		return nil, fmt.Errorf("查询总提现金额失败: %w", err)
	}

	// 查询今日提现金额（status=2表示成功）
	todayBuilder := builder.Where("status = ? AND create_time >= ? AND create_time < ?", 2, startOfDay, endOfDay)
	todayWithdrawalAmount, err := l.svcCtx.AgentWithdrawalModel.FindSum(l.ctx, todayBuilder, "amount")
	if err != nil {
		logx.Errorf("查询今日提现金额失败: %v", err)
		return nil, fmt.Errorf("查询今日提现金额失败: %w", err)
	}

	// 查询总实际到账金额（status=2表示成功）
	totalActualAmount, err := l.svcCtx.AgentWithdrawalModel.FindSum(l.ctx, totalBuilder, "actual_amount")
	if err != nil {
		logx.Errorf("查询总实际到账金额失败: %v", err)
		return nil, fmt.Errorf("查询总实际到账金额失败: %w", err)
	}

	// 查询总扣税金额（status=2表示成功）
	totalTaxAmount, err := l.svcCtx.AgentWithdrawalModel.FindSum(l.ctx, totalBuilder, "tax_amount")
	if err != nil {
		logx.Errorf("查询总扣税金额失败: %v", err)
		return nil, fmt.Errorf("查询总扣税金额失败: %w", err)
	}

	// 构建响应
	resp = &types.AdminGetWithdrawalStatisticsResp{
		TotalWithdrawalAmount: totalWithdrawalAmount,
		TodayWithdrawalAmount: todayWithdrawalAmount,
		TotalActualAmount:     totalActualAmount,
		TotalTaxAmount:        totalTaxAmount,
	}

	return resp, nil
}
