package agent

import (
	"context"
	"bdqr-server/app/main/model"
	"bdqr-server/common/ctxdata"
	"bdqr-server/common/globalkey"
	"bdqr-server/common/xerr"
	"bdqr-server/pkg/lzkit/crypto"

	"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 GetUpgradeRebateListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetUpgradeRebateListLogic) GetUpgradeRebateList(req *types.GetUpgradeRebateListReq) (resp *types.GetUpgradeRebateListResp, 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. 构建查询条件：查询 rebate_agent_id = 当前代理ID 且 status = 2（已完成）且 upgrade_type = 1（自主付费）的记录
	// 注意：rebate_agent_id 是 NullInt64 类型，需要同时检查 IS NOT NULL
	// 只要返佣给自己的都要显示，不管升级后是否脱离关系（rebate_agent_id 记录的是升级时的原直接上级）
	builder := 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).
		OrderBy("create_time DESC")

	// 3. 分页查询
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 20
	}
	offset := (page - 1) * pageSize

	// 4. 查询总数
	total, err := l.svcCtx.AgentUpgradeModel.FindCount(l.ctx, builder, "id")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询升级返佣总数失败, %v", err)
	}

	// 5. 查询列表
	builder = builder.Limit(uint64(pageSize)).Offset(uint64(offset))
	upgrades, err := l.svcCtx.AgentUpgradeModel.FindAll(l.ctx, builder, "")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询升级返佣列表失败, %v", err)
	}

	// 6. 组装响应
	var list []types.UpgradeRebateItem
	for _, upgrade := range upgrades {
		// 查询来源代理手机号（升级的代理）
		sourceAgentMobile := ""
		if upgrade.AgentId != "" {
			sourceAgent, err := l.svcCtx.AgentModel.FindOne(l.ctx, upgrade.AgentId)
			if err == nil {
				if sourceAgent.Mobile != "" {
					decrypted, err := crypto.DecryptMobile(sourceAgent.Mobile, l.svcCtx.Config.Encrypt.SecretKey)
					if err == nil {
						sourceAgentMobile = decrypted
					}
				}
			}
		}

		// 获取订单号
		orderNo := ""
		if upgrade.OrderNo.Valid {
			orderNo = upgrade.OrderNo.String
		}

		list = append(list, types.UpgradeRebateItem{
			Id:                upgrade.Id,
			SourceAgentId:     upgrade.AgentId,
			SourceAgentMobile: sourceAgentMobile,
			OrderNo:           orderNo,
			FromLevel:         upgrade.FromLevel,
			ToLevel:           upgrade.ToLevel,
			Amount:            upgrade.RebateAmount,
			CreateTime:        upgrade.CreateTime.Format("2006-01-02 15:04:05"),
		})
	}

	return &types.GetUpgradeRebateListResp{
		Total: total,
		List:  list,
	}, nil
}
