package agent

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

	"github.com/pkg/errors"

	"jnc-server/app/main/api/internal/svc"
	"jnc-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")

	// 系统简化：移除返佣功能（推广返佣和升级返佣）
	return &types.GetRevenueInfoResp{
		Balance:         wallet.Balance,
		TotalEarnings:   wallet.TotalEarnings,
		CommissionTotal: commissionTotal, // 佣金累计总收益
		CommissionToday: commissionToday, // 佣金今日收益
		CommissionMonth: commissionMonth, // 佣金本月收益
	}, nil
}
