package agent

import (
	"context"
	"tydata-server/app/main/model"
	"tydata-server/common/ctxdata"
	"tydata-server/common/xerr"

	"github.com/Masterminds/squirrel"
	"github.com/pkg/errors"

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

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

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

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

func (l *GetBankCardInfoLogic) GetBankCardInfo(req *types.GetBankCardInfoReq) (resp *types.GetBankCardInfoResp, err error) {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败: %v", err)
	}

	// 查询代理信息
	agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败: %v", err)
	}

	// 查询实名认证信息
	agentRealName, err := l.svcCtx.AgentRealNameModel.FindOneByAgentId(l.ctx, agentModel.Id)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return nil, errors.Wrapf(xerr.NewErrMsg("您未进行实名认证"), "您未进行实名认证")
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "查询代理实名信息失败: %v", err)
	}

	// 初始化响应，包含实名认证信息
	resp = &types.GetBankCardInfoResp{
		PayeeName:  agentRealName.Name,
		IdCard:     agentRealName.IdCard,
		BankCardNo: "",
		BankName:   "",
	}

	// 查询最近一次成功的银行卡提现记录，用于自动填充
	builder := l.svcCtx.AgentWithdrawalModel.SelectBuilder()
	builder = builder.Where(squirrel.Eq{"agent_id": agentModel.Id})
	builder = builder.Where(squirrel.Eq{"withdraw_type": 2}) // 银行卡提现
	builder = builder.Where(squirrel.Eq{"status": 2})        // 成功状态
	builder = builder.OrderBy("create_time DESC")
	builder = builder.Limit(1)

	list, err := l.svcCtx.AgentWithdrawalModel.FindAll(l.ctx, builder, "create_time DESC")
	if err == nil && len(list) > 0 {
		lastRecord := list[0]
		if lastRecord.BankCardNo.Valid {
			resp.BankCardNo = lastRecord.BankCardNo.String
		}
		if lastRecord.BankName.Valid {
			resp.BankName = lastRecord.BankName.String
		}
	}

	return resp, nil
}
