package admin_agent

import (
	"context"

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

	"github.com/Masterminds/squirrel"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *AdminGetAgentWithdrawalListLogic) AdminGetAgentWithdrawalList(req *types.AdminGetAgentWithdrawalListReq) (resp *types.AdminGetAgentWithdrawalListResp, err error) {
	builder := l.svcCtx.AgentWithdrawalModel.SelectBuilder()
	if req.AgentId != nil {
		builder = builder.Where(squirrel.Eq{"agent_id": *req.AgentId})
	}
	if req.Status != nil {
		builder = builder.Where(squirrel.Eq{"status": *req.Status})
	}
	if req.WithdrawNo != nil && *req.WithdrawNo != "" {
		builder = builder.Where(squirrel.Eq{"withdraw_no": *req.WithdrawNo})
	}
	list, total, err := l.svcCtx.AgentWithdrawalModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "create_time DESC")
	if err != nil {
		return nil, err
	}
	items := make([]types.AgentWithdrawalListItem, 0, len(list))
	for _, v := range list {
		item := types.AgentWithdrawalListItem{}
		_ = copier.Copy(&item, v)
		item.Remark = ""
		if v.Remark.Valid {
			item.Remark = v.Remark.String
		}
		item.CreateTime = v.CreateTime.Format("2006-01-02 15:04:05")
		
		// 手动设置银行卡信息（copier不会自动处理sql.NullString）
		item.WithdrawType = v.WithdrawType
		if v.BankCardNo.Valid {
			item.BankCardNo = v.BankCardNo.String
		}
		if v.BankName.Valid {
			item.BankName = v.BankName.String
		}
		if v.PayeeName.Valid {
			item.PayeeName = v.PayeeName.String
		}
		
		items = append(items, item)
	}
	resp = &types.AdminGetAgentWithdrawalListResp{
		Total: total,
		Items: items,
	}
	return
}
