package admin_order

import (
	"context"
	"fmt"
	"time"

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

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

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

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

func (l *AdminGetRevenueStatisticsLogic) AdminGetRevenueStatistics(req *types.AdminGetRevenueStatisticsReq) (resp *types.AdminGetRevenueStatisticsResp, 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.OrderModel.SelectBuilder()

	// 查询总流水收入金额（status=paid表示已支付）
	totalRevenueBuilder := builder.Where("status = ?", "paid")
	totalRevenueAmount, err := l.svcCtx.OrderModel.FindSum(l.ctx, totalRevenueBuilder, "amount")
	if err != nil {
		logx.Errorf("查询总收入金额失败: %v", err)
		return nil, fmt.Errorf("查询总收入金额失败: %w", err)
	}

	// 查询今日流水收入金额（status=paid表示已支付，且支付时间为今日）
	todayRevenueBuilder := builder.Where("status = ? AND pay_time >= ? AND pay_time < ?", "paid", startOfDay, endOfDay)
	todayRevenueAmount, err := l.svcCtx.OrderModel.FindSum(l.ctx, todayRevenueBuilder, "amount")
	if err != nil {
		logx.Errorf("查询今日收入金额失败: %v", err)
		return nil, fmt.Errorf("查询今日收入金额失败: %w", err)
	}

	// 查询代理订单金额总和（只查询agent_platform_deduction表，不进行联表）
	deductionAmount, err := l.svcCtx.AgentPlatformDeductionModel.FindSum(
		l.ctx,
		l.svcCtx.AgentPlatformDeductionModel.SelectBuilder(),
		"amount")
	if err != nil {
		logx.Errorf("查询代理订单金额总和失败: %v", err)
		return nil, fmt.Errorf("查询代理订单金额总和失败: %w", err)
	}

	// 计算非代理订单金额，使用订单表作为主表，关联agent_platform_deduction表，查询没有代理记录的订单
	// 使用子查询方式避免JOIN，与order/list接口保持一致的查询风格
	nonDeductionBuilder := l.svcCtx.OrderModel.SelectBuilder().
		Where("status = ? AND id NOT IN (SELECT order_id FROM agent_platform_deduction WHERE order_id IS NOT NULL)", "paid")
	nonDeductionAmount, err := l.svcCtx.OrderModel.FindSum(
		l.ctx,
		nonDeductionBuilder,
		"amount")
	if err != nil {
		logx.Errorf("查询非代理订单金额失败: %v", err)
		return nil, fmt.Errorf("查询非代理订单金额失败: %w", err)
	}

	// 查询订单成本总和（只查询order表，不进行联表）
	orderCostBuilder := l.svcCtx.OrderModel.SelectBuilder().
		Where("status = ? AND del_state = 0", "paid")
	orderCostAmount, err := l.svcCtx.OrderModel.FindSum(
		l.ctx,
		orderCostBuilder,
		"sales_cost")
	if err != nil {
		logx.Errorf("查询订单成本总和失败: %v", err)
		return nil, fmt.Errorf("查询订单成本总和失败: %w", err)
	}
	// 计算总利润 = 代理订单金额总和 + 非代理订单金额总和 - 订单成本总和
	// 总收入 = 代理订单金额 + 非代理订单金额
	// 总利润 = 总收入 - 所有订单成本
	totalProfitAmount := deductionAmount + nonDeductionAmount - orderCostAmount

	// 计算今日利润 = 今日代理订单金额 + 今日非代理订单金额 - 今日订单成本总和

	// 1. 查询今日代理订单金额
	todayDeductionBuilder := l.svcCtx.AgentPlatformDeductionModel.SelectBuilder().
		Where("create_time >= ? AND create_time < ?", startOfDay, endOfDay)
	todayDeductionAmount, err := l.svcCtx.AgentPlatformDeductionModel.FindSum(
		l.ctx,
		todayDeductionBuilder,
		"amount")
	if err != nil {
		logx.Errorf("查询今日代理订单金额失败: %v", err)
		return nil, fmt.Errorf("查询今日代理订单金额失败: %w", err)
	}

	// 2. 查询今日非代理订单金额
	todayNonDeductionBuilder := l.svcCtx.OrderModel.SelectBuilder().
		Where("status = ? AND pay_time >= ? AND pay_time < ? AND id NOT IN (SELECT order_id FROM agent_platform_deduction WHERE order_id IS NOT NULL)",
			"paid", startOfDay, endOfDay)
	todayNonDeductionAmount, err := l.svcCtx.OrderModel.FindSum(
		l.ctx,
		todayNonDeductionBuilder,
		"amount")
	if err != nil {
		logx.Errorf("查询今日非代理订单金额失败: %v", err)
		return nil, fmt.Errorf("查询今日非代理订单金额失败: %w", err)
	}

	// 3. 查询今日订单成本总和
	todayOrderCostBuilder := l.svcCtx.OrderModel.SelectBuilder().
		Where("status = ? AND pay_time >= ? AND pay_time < ?", "paid", startOfDay, endOfDay)
	todayOrderCostAmount, err := l.svcCtx.OrderModel.FindSum(
		l.ctx,
		todayOrderCostBuilder,
		"sales_cost")
	if err != nil {
		logx.Errorf("查询今日订单成本总和失败: %v", err)
		return nil, fmt.Errorf("查询今日订单成本总和失败: %w", err)
	}

	// 4. 计算今日利润 = 今日代理订单金额 + 今日非代理订单金额 - 今日订单成本总和
	todayProfitAmount := todayDeductionAmount + todayNonDeductionAmount - todayOrderCostAmount

	// 构建响应
	resp = &types.AdminGetRevenueStatisticsResp{
		TotalRevenueAmount: totalRevenueAmount,
		TodayRevenueAmount: todayRevenueAmount,
		TotalProfitAmount:  totalProfitAmount,
		TodayProfitAmount:  todayProfitAmount,
	}

	return resp, nil
}
