package admin_agent

import (
	"context"
	"fmt"
	"strings"

	"jnc-server/app/main/api/internal/svc"
	"jnc-server/app/main/api/internal/types"
	"jnc-server/common/globalkey"
	"jnc-server/common/xerr"

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

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

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

func (l *AdminGetAgentWithdrawListLogic) AdminGetAgentWithdrawList(req *types.AdminGetAgentWithdrawListReq) (resp *types.AdminGetAgentWithdrawListResp, err error) {
	// 1. 构建查询条件
	whereConditions := []string{fmt.Sprintf("del_state = %d", globalkey.DelStateNo)}
	args := []interface{}{}

	// 可选过滤条件
	if req.AgentId != nil && *req.AgentId != "" {
		whereConditions = append(whereConditions, "agent_id = ?")
		args = append(args, *req.AgentId)
	}

	if req.Status != nil {
		whereConditions = append(whereConditions, "status = ?")
		args = append(args, *req.Status)
	}

	whereClause := strings.Join(whereConditions, " AND ")

	// 2. 构建查询builder
	builder := l.svcCtx.AgentWithdrawModel.SelectBuilder().
		Where(whereClause, args...).
		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.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.AdminGetAgentWithdrawListResp{
			Total: 0,
			Items: []types.AgentWithdrawListItem{},
		}, nil
	}

	// 5. 查询列表
	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)
	}

	// 6. 组装响应
	var items []types.AgentWithdrawListItem
	for _, withdrawal := range withdrawals {
		// 处理代理ID
		agentId := withdrawal.AgentId

		// 处理代理手机号
		agentMobile := ""
		if withdrawal.AgentMobile.Valid {
			agentMobile = withdrawal.AgentMobile.String
		}

		// 处理代理编码
		var agentCode int64 = 0
		if withdrawal.AgentCode.Valid {
			agentCode = withdrawal.AgentCode.Int64
		}

		// 银行卡号脱敏（只显示前4位和后4位）
		bankCardNumber := withdrawal.BankCardNumber
		if len(bankCardNumber) > 8 {
			bankCardNumber = fmt.Sprintf("%s****%s", bankCardNumber[:4], bankCardNumber[len(bankCardNumber)-4:])
		}

		// 处理开户支行
		bankBranch := ""
		if withdrawal.BankBranch.Valid {
			bankBranch = withdrawal.BankBranch.String
		}

		// 处理审核人ID
		auditUserId := ""
		if withdrawal.AuditUserId.Valid {
			auditUserId = withdrawal.AuditUserId.String
		}

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

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

		items = append(items, types.AgentWithdrawListItem{
			Id:                 withdrawal.Id,
			AgentId:            agentId,
			AgentMobile:        agentMobile,
			AgentCode:          agentCode,
			WithdrawAmount:     withdrawal.WithdrawAmount,
			TaxAmount:          withdrawal.TaxAmount,
			ActualAmount:       withdrawal.ActualAmount,
			FrozenAmount:       withdrawal.FrozenAmount,
			AccountName:        withdrawal.AccountName,
			BankCardNumber:     bankCardNumber,    // 脱敏显示
			BankCardNumberFull: withdrawal.BankCardNumber, // 完整卡号用于审核
			BankBranch:         bankBranch,
			Status:             withdrawal.Status,
			AuditUserId:        auditUserId,
			AuditTime:          auditTime,
			AuditRemark:        auditRemark,
			CreateTime:         withdrawal.CreateTime.Format("2006-01-02 15:04:05"),
		})
	}

	return &types.AdminGetAgentWithdrawListResp{
		Total: total,
		Items: items,
	}, nil
}
