package com.tourguide.modules.order.payment; import com.tourguide.common.huifu.biz.DouGongRefundBiz; import com.tourguide.modules.order.entity.TourOrder; import com.tourguide.modules.order.entity.TourOrderPaymentAttempt; import com.tourguide.modules.order.mapper.TourOrderPaymentAttemptMapper; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.math.BigDecimal; import java.util.Map; @Component public class HuifuPaymentRefundGateway implements PaymentRefundGateway { private static final String SUCCESS_CODE = "00000100"; private final DouGongRefundBiz refundBiz; private final TourOrderPaymentAttemptMapper paymentAttemptMapper; public HuifuPaymentRefundGateway(DouGongRefundBiz refundBiz, TourOrderPaymentAttemptMapper paymentAttemptMapper) { this.refundBiz = refundBiz; this.paymentAttemptMapper = paymentAttemptMapper; } @Override public String refund(TourOrder order, BigDecimal amount) { if (!StringUtils.hasText(order.getRefundOrderNo())) { throw new IllegalStateException("Refund request sequence is missing"); } if (!StringUtils.hasText(order.getPaymentOrderNo())) { throw new IllegalStateException("Original payment sequence is missing"); } TourOrderPaymentAttempt paymentAttempt = paymentAttemptMapper .selectByReqSeqIdForUpdate(order.getPaymentOrderNo()); if (paymentAttempt == null || !StringUtils.hasText(paymentAttempt.getReqDate())) { throw new IllegalStateException("Original payment attempt is missing"); } try { Map response = refundBiz.refund(order.getRefundOrderNo(), amount, paymentAttempt.getReqDate(), paymentAttempt.getReqSeqId()); String responseCode = stringValue(response.get("resp_code")); if (!SUCCESS_CODE.equals(responseCode)) { String description = stringValue(response.get("resp_desc")); throw new IllegalStateException(StringUtils.hasText(description) ? description : "Huifu refund request failed"); } return order.getRefundOrderNo(); } catch (RuntimeException exception) { throw exception; } catch (Exception exception) { throw new IllegalStateException("Huifu refund service unavailable", exception); } } private String stringValue(Object value) { return value == null ? null : String.valueOf(value); } }