package agent

import (
	"context"
	"fmt"

	"sim-server/app/main/api/internal/svc"
	"sim-server/app/main/api/internal/types"
	"sim-server/app/main/model"
	"sim-server/common/ctxdata"
	"sim-server/common/globalkey"
	"sim-server/common/xerr"

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

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

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

func (l *GetWithdrawListLogic) GetWithdrawList(req *types.GetWithdrawListReq) (resp *types.GetWithdrawListResp, err error) {
	// 1. 获取当前用户ID（代理ID）
	userId, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户信息失败: %v", err)
	}

	// 2. 查询代理信息
	agent, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userId)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			// 不是代理，返回空列表
			return &types.GetWithdrawListResp{
				Total: 0,
				List:  []types.WithdrawItem{},
			}, nil
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询代理信息失败: %v", err)
	}

	// 3. 构建查询条件
	builder := l.svcCtx.AgentWithdrawModel.SelectBuilder().
		Where("agent_id = ? AND del_state = ?", agent.Id, globalkey.DelStateNo).
		OrderBy("create_time DESC")

	// 4. 分页参数
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 20
	}
	offset := (page - 1) * pageSize

	// 5. 查询总数
	total, err := l.svcCtx.AgentWithdrawModel.FindCount(l.ctx, builder, "id")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询提现记录总数失败: %v", err)
	}

	if total == 0 {
		return &types.GetWithdrawListResp{
			Total: 0,
			List:  []types.WithdrawItem{},
		}, nil
	}

	// 6. 查询列表
	builder = builder.Limit(uint64(pageSize)).Offset(uint64(offset))
	withdrawals, err := l.svcCtx.AgentWithdrawModel.FindAll(l.ctx, builder, "")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询提现记录列表失败: %v", err)
	}

	// 7. 组装响应
	var list []types.WithdrawItem
	for _, withdrawal := range withdrawals {
		// 处理银行卡号脱敏（只显示前4位和后4位）
		bankCardNumber := withdrawal.BankCardNumber
		if len(bankCardNumber) > 8 {
			bankCardNumber = fmt.Sprintf("%s****%s", bankCardNumber[:4], bankCardNumber[len(bankCardNumber)-4:])
		}

		// 处理审核备注
		auditRemark := ""
		if withdrawal.AuditRemark.Valid {
			auditRemark = withdrawal.AuditRemark.String
		}

		// 处理审核时间
		auditTime := ""
		if withdrawal.AuditTime.Valid {
			auditTime = withdrawal.AuditTime.Time.Format("2006-01-02 15:04:05")
		}

		list = append(list, types.WithdrawItem{
			Id:             withdrawal.Id,
			WithdrawAmount: fmt.Sprintf("%.2f", withdrawal.WithdrawAmount),
			TaxAmount:      fmt.Sprintf("%.2f", withdrawal.TaxAmount),
			ActualAmount:   fmt.Sprintf("%.2f", withdrawal.ActualAmount),
			AccountName:    withdrawal.AccountName,
			BankCardNumber: bankCardNumber,
			Status:         withdrawal.Status,
			AuditRemark:    auditRemark,
			CreateTime:     withdrawal.CreateTime.Format("2006-01-02 15:04:05"),
			AuditTime:      auditTime,
		})
	}

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