package agent

import (
	"context"
	"time"
	"bdqr-server/app/main/model"
	"bdqr-server/common/ctxdata"
	"bdqr-server/common/globalkey"
	"bdqr-server/common/xerr"

	"github.com/pkg/errors"

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

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

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

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

func (l *GetRevenueInfoLogic) GetRevenueInfo() (resp *types.GetRevenueInfoResp, err error) {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户信息失败, %v", err)
	}

	// 1. 获取代理信息
	agent, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return nil, errors.Wrapf(xerr.NewErrMsg("您不是代理"), "")
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败, %v", err)
	}

	// 2. 获取钱包信息
	wallet, err := l.svcCtx.AgentWalletModel.FindOneByAgentId(l.ctx, agent.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询钱包信息失败, %v", err)
	}

	// 获取当前时间
	now := time.Now()
	// 今日开始时间（00:00:00）
	todayStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	// 本月开始时间（1号 00:00:00）
	monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())

	// 3. 统计佣金总额（从 agent_commission 表统计）
	commissionBuilder := l.svcCtx.AgentCommissionModel.SelectBuilder().
		Where("agent_id = ? AND del_state = ?", agent.Id, globalkey.DelStateNo)
	commissionTotal, _ := l.svcCtx.AgentCommissionModel.FindSum(l.ctx, commissionBuilder, "amount")

	// 3.1 统计佣金今日收益
	commissionTodayBuilder := l.svcCtx.AgentCommissionModel.SelectBuilder().
		Where("agent_id = ? AND del_state = ? AND create_time >= ?", agent.Id, globalkey.DelStateNo, todayStart)
	commissionToday, _ := l.svcCtx.AgentCommissionModel.FindSum(l.ctx, commissionTodayBuilder, "amount")

	// 3.2 统计佣金本月收益
	commissionMonthBuilder := l.svcCtx.AgentCommissionModel.SelectBuilder().
		Where("agent_id = ? AND del_state = ? AND create_time >= ?", agent.Id, globalkey.DelStateNo, monthStart)
	commissionMonth, _ := l.svcCtx.AgentCommissionModel.FindSum(l.ctx, commissionMonthBuilder, "amount")

	// 4. 统计返佣总额（包括推广返佣和升级返佣）
	// 4.1 统计推广返佣（从 agent_rebate 表）
	rebateBuilder := l.svcCtx.AgentRebateModel.SelectBuilder().
		Where("agent_id = ? AND del_state = ?", agent.Id, globalkey.DelStateNo)
	promoteRebateTotal, _ := l.svcCtx.AgentRebateModel.FindSum(l.ctx, rebateBuilder, "rebate_amount")

	// 4.2 统计升级返佣（从 agent_upgrade 表，查询 rebate_agent_id = 当前代理ID 且 status = 2（已完成）且 upgrade_type = 1（自主付费）的记录）
	// 注意：只要返佣给自己的都要统计，不管升级后是否脱离关系（rebate_agent_id 记录的是升级时的原直接上级）
	upgradeRebateBuilder := l.svcCtx.AgentUpgradeModel.SelectBuilder().
		Where("rebate_agent_id IS NOT NULL AND rebate_agent_id = ? AND status = ? AND upgrade_type = ? AND del_state = ?",
			agent.Id, 2, 1, globalkey.DelStateNo)
	upgradeRebateTotal, _ := l.svcCtx.AgentUpgradeModel.FindSum(l.ctx, upgradeRebateBuilder, "rebate_amount")

	rebateTotal := promoteRebateTotal + upgradeRebateTotal

	// 4.3 统计返佣今日收益
	// 推广返佣今日
	promoteRebateTodayBuilder := l.svcCtx.AgentRebateModel.SelectBuilder().
		Where("agent_id = ? AND del_state = ? AND create_time >= ?", agent.Id, globalkey.DelStateNo, todayStart)
	promoteRebateToday, _ := l.svcCtx.AgentRebateModel.FindSum(l.ctx, promoteRebateTodayBuilder, "rebate_amount")
	// 升级返佣今日
	upgradeRebateTodayBuilder := l.svcCtx.AgentUpgradeModel.SelectBuilder().
		Where("rebate_agent_id IS NOT NULL AND rebate_agent_id = ? AND status = ? AND upgrade_type = ? AND del_state = ? AND create_time >= ?",
			agent.Id, 2, 1, globalkey.DelStateNo, todayStart)
	upgradeRebateToday, _ := l.svcCtx.AgentUpgradeModel.FindSum(l.ctx, upgradeRebateTodayBuilder, "rebate_amount")
	rebateToday := promoteRebateToday + upgradeRebateToday

	// 4.4 统计返佣本月收益
	// 推广返佣本月
	promoteRebateMonthBuilder := l.svcCtx.AgentRebateModel.SelectBuilder().
		Where("agent_id = ? AND del_state = ? AND create_time >= ?", agent.Id, globalkey.DelStateNo, monthStart)
	promoteRebateMonth, _ := l.svcCtx.AgentRebateModel.FindSum(l.ctx, promoteRebateMonthBuilder, "rebate_amount")
	// 升级返佣本月
	upgradeRebateMonthBuilder := l.svcCtx.AgentUpgradeModel.SelectBuilder().
		Where("rebate_agent_id IS NOT NULL AND rebate_agent_id = ? AND status = ? AND upgrade_type = ? AND del_state = ? AND create_time >= ?",
			agent.Id, 2, 1, globalkey.DelStateNo, monthStart)
	upgradeRebateMonth, _ := l.svcCtx.AgentUpgradeModel.FindSum(l.ctx, upgradeRebateMonthBuilder, "rebate_amount")
	rebateMonth := promoteRebateMonth + upgradeRebateMonth

	return &types.GetRevenueInfoResp{
		Balance:         wallet.Balance,
		FrozenBalance:   wallet.FrozenBalance,
		TotalEarnings:   wallet.TotalEarnings,
		WithdrawnAmount: wallet.WithdrawnAmount,
		CommissionTotal: commissionTotal, // 佣金累计总收益（推广订单获得的佣金）
		CommissionToday: commissionToday, // 佣金今日收益
		CommissionMonth: commissionMonth, // 佣金本月收益
		RebateTotal:     rebateTotal,     // 返佣累计总收益（包括推广返佣和升级返佣）
		RebateToday:     rebateToday,     // 返佣今日收益
		RebateMonth:     rebateMonth,     // 返佣本月收益
	}, nil
}
