package shop.alien.store.strategy.payment.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import shop.alien.entity.result.R;
import shop.alien.entity.store.RefundRecord;
import shop.alien.entity.store.StoreAliPayRefundLog;
import shop.alien.mapper.AlipayZftCreateRecordMapper;
import shop.alien.store.service.RefundRecordService;
import shop.alien.store.service.StoreAliPayRefundLogService;
import shop.alien.store.strategy.payment.PaymentStrategy;
import shop.alien.util.common.UniqueRandomNumGenerator;
import shop.alien.util.common.constant.PaymentEnum;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Slf4j
@Component
@RequiredArgsConstructor
public class AlipayPartnerPaymentStrategyImpl implements PaymentStrategy {

    private final AlipayZftCreateRecordMapper alipayZftCreateRecordMapper;
    private final StoreAliPayRefundLogService storeAliPayRefundLogService;
    private final RefundRecordService refundRecordService;



    /**
     * 生成支付宝直付通二级商户支付预订单
     */
    public R createAlipayZftPreOrder(String orderNo, String amount, String subject, String smid) throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());



        // 构造请求参数以调用接口
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

        // 设置商户订单号
        // 生成随机订单号
        orderNo = "alipay_zft_" + System.currentTimeMillis() + new Random().nextInt(999999);
        model.setOutTradeNo(orderNo);

        // 设置订单总金额
        // 除以100
        BigDecimal total = new BigDecimal(amount);
        model.setTotalAmount(total.toPlainString());

        // 设置订单标题
        model.setSubject(subject);
        // 1. 构建二级商户信息
        SubMerchant subMerchant = new SubMerchant();
        subMerchant.setMerchantId(smid); // 替换为实际的二级商户编号
        // 【关键】设置二级商户信息（直付通必传）
        model.setSubMerchant(subMerchant);


        // 设置产品码
//        model.setProductCode("QUICK_MSECURITY_PAY");

        // 设置订单包含的商品列表信息
//        List<GoodsDetail> goodsDetail = new ArrayList<GoodsDetail>();
//        GoodsDetail goodsDetail0 = new GoodsDetail();
//        goodsDetail0.setGoodsName("ipad");
//        goodsDetail0.setAlipayGoodsId("20010001");
//        goodsDetail0.setQuantity(1L);
//        goodsDetail0.setPrice("2000");
//        goodsDetail0.setGoodsId("apple-01");
//        goodsDetail0.setGoodsCategory("34543238");
//        goodsDetail0.setCategoriesTree("124868003|126232002|126252004");
//        goodsDetail0.setShowUrl("http://www.alipay.com/xxx.jpg");
//        goodsDetail.add(goodsDetail0);
//        model.setGoodsDetail(goodsDetail);

        // 设置订单绝对超时时间
//        model.setTimeExpire("2016-12-31 10:05:00");

        // 设置业务扩展参数
//        ExtendParams extendParams = new ExtendParams();
//        extendParams.setSysServiceProviderId("2088511833207846");
//        extendParams.setHbFqSellerPercent("100");
//        extendParams.setHbFqNum("3");
//        extendParams.setIndustryRefluxInfo("{\"scene_code\":\"metro_tradeorder\",\"channel\":\"xxxx\",\"scene_data\":{\"asset_name\":\"ALIPAY\"}}");
//        extendParams.setRoyaltyFreeze("true");
//        extendParams.setCardType("S0JP0000");
//        model.setExtendParams(extendParams);

        // 设置公用回传参数
//        model.setPassbackParams("merchantBizType%3d3C%26merchantBizNo%3d2016010101111");

        // 设置商户的原始订单号
//        model.setMerchantOrderNo("20161008001");

        // 设置外部指定买家
//        ExtUserInfo extUserInfo = new ExtUserInfo();
//        extUserInfo.setCertType("IDENTITY_CARD");
//        extUserInfo.setCertNo("362334768769238881");
//        extUserInfo.setMobile("16587658765");
//        extUserInfo.setName("李明");
//        extUserInfo.setMinAge("18");
//        extUserInfo.setNeedCheckInfo("F");
//        extUserInfo.setIdentityHash("27bfcd1dee4f22c8fe8a2374af9b660419d1361b1c207e9b41a754a113f38fcc");
//        model.setExtUserInfo(extUserInfo);

        // 设置通知参数选项
//        List<String> queryOptions = new ArrayList<String>();
//        queryOptions.add("hyb_amount");
//        queryOptions.add("enterprise_pay_info");
//        model.setQueryOptions(queryOptions);
        SettleInfo settleInfo = new SettleInfo();
        SettleDetailInfo settleDetailInfo = new SettleDetailInfo();
        settleDetailInfo.setTransInType("defaultSettle");
        settleDetailInfo.setAmount(total.toString());
        List<SettleDetailInfo>  settleDetailInfos = new ArrayList<>();
        settleDetailInfos.add(settleDetailInfo);
        settleInfo.setSettleDetailInfos(settleDetailInfos);
        model.setSettleInfo(settleInfo);

        request.setNotifyUrl("https://frp-off.com:40279/alienStore/alipayPartnerNotify");
        request.setBizModel(model);

        // 第三方代调用模式下请设置app_auth_token
        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");
//        model.setProductCode("QUICK_MSECURITY_PAY");
        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
        String orderStr = response.getBody();
        System.out.println(orderStr);

        if (response.isSuccess()) {
            Map<String, Object> analyzeRequest = new HashedMap<>();
            analyzeRequest.put("orderStr", orderStr);
            analyzeRequest.put("orderNumber", orderNo);
            return R.data(analyzeRequest);
        } else {
            return R.fail("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
    }

    private static AlipayConfig getAlipayConfig() {
        String privateKey  = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCBTOvScNrk0mw+WbR6Qtx2+HrPxB5IU/V2HSPGZUTDNiCiSU9UZcuXlo0UNwMksFYR43btk4BHW9OsZETdr3uJzbEEko4jQPrY49V6V8d3yFUiexcbLKf9W2X+h7EwdPDahHk6wmM73Lm500xzv8JxdGeo/d2uGTh+qD66HcPW+QYj1YbjRV1JyCOiJ2OiwLcb28arNNLOgj6PktQ69FPSWS4hWrM7nl6DLRr6SdOlyfBT47gwPtW0BQ96/2b9O+qxKBPfrcqdRDH323HvrGFDwa8GoWTdchnKwFjmfIFHMvf+eq3tzilFi8H7vQRtzVRrndwrNa0z+1ss07fcWFDRAgMBAAECggEAItgU0OAizPk7vE22SiBMgy8RAX5rXrhpdIwDwQo3Tpf+kV1KKIdKJy6mFCWDDlcKysVOnlVag2BmmZVnzYnls8wfgQjxjuSK9Pno5JBVK51r+9/J6UPOfYMs6Duu700EPw7mEISj81TXJBGiD6tEfgiNisfm/mzDgbZbORKeXQbaTyrtB+GZn6FNSyyHA1vraARMrgfMEGNzQ4AbtfcUxGO+mejdTFs0PxAq6lovHBY3fYYHI1Nx6kf9iPoom/G4UrcMO67W6QU+1tOCZCXjy4bD2y421z/8XD73+WDyYp+Tjy0hTLqVZc7TpYAOximo1vMIUe23EdJJngdlkdpDFQKBgQDFyETL0knwBSakLfAe2BmFb2x++B4YXUnt4dGbCFBnVooxf5i06GVt/CrfkJhYK6hBSowOScIRf8P6BOSQptRZb2/I1ngQm4vcpAZw6EjUTlgOj/J3XJ+ApUNQnRqE28jDrE4m2RHg4BkQo6yA3DizJAluPCtFoCYDm1a7dV7u7wKBgQCnXEH5sD8VSxURv02/gn80g/uZIP/EOU3ycjBEqZdRGkNINwXT+zqrlZIGYb+bxLvU/R2OqKC5vhcyAL3T1A8ORYqPu5KLnAxg7C+rHuVilUWwCEH7POpCk+ETPXCZwcNvLNa5PIqBH/gdV9Y9PBTef6J4rN6V6TDFgosf5by8PwKBgDpVG71Fk1sAGep4RgbC05wgRc6Y3T9wXDqVzJ098YDY7D83E9HfbPLoWbjAS75Nef1vwCkCpgNFPIbD5KmpGp4aGM0SPC0hwzlbAy9PwxMi3CPHXsrHfZ+SnmzrOQQQUoErk40vnm9FiP74VwtWaD6llUZ25ohNeIi9yvHU5x/vAoGAdU2d1JOq85LHtsO+i9+8pyNnAsJ1YqTDtI5CtK2lqKvewswGIrlxOvi//AchVN3ExZmP0QDyfp31BhAs/T8iOl+Vqf7PzVjX+Eszch5aqwlzadmv3ZepnnamCGVE+hAsmkz0R6tebPjqYC7Ds/HbssQFLc4EyVBD5fwE5ZuR+OMCgYAvGHUYpi0dY9uMHXzL721tIopiwUfKCgLAn3yhSH3p7644NxHBqLLaBLVT2q7JAZQUaZUvXlwiyxU1zvo0xmvcbnB/Vd2qp8KbEUkvHyIYVJkM6Fn+9xBosorcrHv+7B2V1XR9WQcXvppxbN/8farWGuAA0anBD+UGrxd8B0/hHg==";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnxevClLpYc6c8A9lwmnftPO2BeU+X6aZ/+b/n1Cvq096VJKiHmqcsRgRbrnSlmPDHRrQpDti4en2Ys0L2lx7CObIr/2xP/jJVwjIO1iWHUj/w/NAbjv7dLW/FFY4SeNp8rU+hlgGgviyUxzonfNfr3v+o8grFqQq27/hiZJAofsQRMQu1dEQqoKdJj7eQLkTstiK5miJMyQ+Y3tLztrEUMBz/zRgaCEfGqmFmRZ2diy2X+1dGaX6H4+0QJ2u50eY2QTBkNuvREGbAn6/lttAgvg/+CywPYKGeC4xOfnl5wP8iA1QXYbXrVJRkZjU097nyOmSNhLy9KvJH2BNpojS1QIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId("2021005196608960");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }

    @Override
    public R createPreAliPayOrder(String orderNo, String price, String subject, String smid) throws Exception {
        return createAlipayZftPreOrder(orderNo, price, subject, smid);
    }

    @Override
    public R createPrePayOrder(String price, String subject) throws Exception {
        return null;
    }

    @Override
    public R handleNotify(String notifyData) throws Exception {
        log.info("处理支付宝支付通知，通知数据：{}", notifyData);
        // 通过订单ID查询记录中对应数据,取得storeId
        // 通过storeId查询storeInfo对应数据,
        //更新smid
        return null;
    }

    @Override
    public R searchOrderByOutTradeNoPath(String transactionId) throws Exception {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            AlipayTradeQueryModel model = new AlipayTradeQueryModel();
            model.setOutTradeNo(transactionId);
            List<String> queryOptions = new ArrayList<>();
            queryOptions.add("trade_settle_info");
            model.setQueryOptions(queryOptions);
            request.setBizModel(model);

            AlipayTradeQueryResponse response = alipayClient.execute(request);
            log.debug("支付宝订单查询 rawBody 长度={}", response.getBody() != null ? response.getBody().length() : 0);

            Map<String, Object> data = buildAlipayTradeQueryData(response);
            if (response.isSuccess()) {
//                data.get("tradeStatus")
                return R.data(200,"","支付成功" );
            }
            String sub = response.getSubMsg() != null ? response.getSubMsg() : "";
            return R.data(200,"","支付失败");
        } catch (AlipayApiException e) {
            log.error("支付宝订单查询异常, transactionId={}", transactionId, e);
            return R.data(200,"","查询失败");
        }
    }

    /**
     * 将 {@link AlipayTradeQueryResponse} 转为与前端约定一致的 Map（与支付宝网关返回字段对齐，便于序列化为示例 JSON 结构）。
     */
    private static Map<String, Object> buildAlipayTradeQueryData(AlipayTradeQueryResponse response) {
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("code", response.getCode());
        data.put("msg", response.getMsg());
        data.put("body", response.getBody());
        if (response.getParams() != null && !response.getParams().isEmpty()) {
            data.put("params", response.getParams());
        }
        data.put("buyerLogonId", response.getBuyerLogonId());
        data.put("buyerPayAmount", response.getBuyerPayAmount());
        data.put("buyerUserId", response.getBuyerUserId());

        List<TradeFundBill> fundBillList = response.getFundBillList();
        if (fundBillList != null && !fundBillList.isEmpty()) {
            List<Map<String, String>> bills = new ArrayList<>();
            for (TradeFundBill fb : fundBillList) {
                if (fb == null) {
                    continue;
                }
                Map<String, String> row = new LinkedHashMap<>();
                row.put("amount", fb.getAmount());
                row.put("fundChannel", fb.getFundChannel());
                bills.add(row);
            }
            data.put("fundBillList", bills);
        }

        data.put("invoiceAmount", response.getInvoiceAmount());
        data.put("outTradeNo", response.getOutTradeNo());
        data.put("pointAmount", response.getPointAmount());
        data.put("receiptAmount", response.getReceiptAmount());
        data.put("sendPayDate", response.getSendPayDate());
        data.put("totalAmount", response.getTotalAmount());
        data.put("tradeNo", response.getTradeNo());

        TradeSettleInfo tradeSettleInfo = response.getTradeSettleInfo();
        if (tradeSettleInfo != null) {
            Map<String, String> settle = new LinkedHashMap<>();
            settle.put("tradeUnsettledAmount", tradeSettleInfo.getTradeUnsettledAmount());
            data.put("tradeSettleInfo", settle);
        }

        data.put("tradeStatus", response.getTradeStatus());
        data.put("errorCode", response.getCode());
        data.put("success", response.isSuccess());
        return data;
    }

    @Override
    public String handleRefund(Map<String, String> params) throws Exception {
        log.info("[支付宝服务商退款] 处理退款请求，参数：{}", params);
        try {
            // 调用 alipay.trade.refund 接口发起退款
            AlipayTradeRefundRequest refundRequest = buildRefundRequest(params);
            AlipayTradeRefundResponse response = refundRun(refundRequest);
            String refundResult = "";
            JSONObject responseBody = JSONObject.parseObject(response.getBody());
            JSONObject refundResponse = responseBody.getJSONObject("alipay_trade_refund_response");

            if (response.isSuccess()) {
                refundResult = "调用成功";
                log.info("[支付宝服务商退款] 退款成功 outTradeNo={}, tradeNo={}, refundFee={}",
                        refundResponse.getString("out_trade_no"),
                        refundResponse.getString("trade_no"),
                        refundResponse.getString("refund_fee"));

                // 保存退款信息到支付宝退款记录表
                StoreAliPayRefundLog refundLog = new StoreAliPayRefundLog();
                refundLog.setResponseCode(refundResponse.getString("code"));
                refundLog.setResponseMsg(refundResponse.getString("msg"));
                refundLog.setBuyerLogonId(refundResponse.getString("buyer_logon_id"));
                refundLog.setBuyerOpenId(refundResponse.getString("buyer_open_id"));
                refundLog.setFundChange(refundResponse.getString("fund_change"));
                refundLog.setOutTradeNo(refundResponse.getString("out_trade_no"));
                refundLog.setTradeNo(refundResponse.getString("trade_no"));
                refundLog.setRefundFee(refundResponse.getString("refund_fee"));
                refundLog.setSendBackFee(refundResponse.getString("send_back_fee"));
                if (refundResponse.containsKey("refund_detail_item_list")) {
                    JSONArray refundDetailList = refundResponse.getJSONArray("refund_detail_item_list");
                    if (refundDetailList != null) {
                        refundLog.setRefundDetailItemList(JSON.toJSONString(refundDetailList));
                    }
                }
                String gmtRefundPayStr = refundResponse.getString("gmt_refund_pay");
                if (StringUtils.isNotBlank(gmtRefundPayStr)) {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        refundLog.setGmtRefundPay(sdf.parse(gmtRefundPayStr));
                    } catch (ParseException e) {
                        log.warn("[支付宝服务商退款] 解析退款时间失败: {}", gmtRefundPayStr, e);
                    }
                }
                refundLog.setRefundReason(params.get("refundReason"));
                refundLog.setOutRequestNo(params.get("partialRefundCode"));
                refundLog.setAlipayCertSn(responseBody.getString("alipay_cert_sn"));
                refundLog.setSign(responseBody.getString("sign"));
                refundLog.setDeleteFlag(0);
                refundLog.setCreatedTime(new Date());
                storeAliPayRefundLogService.save(refundLog);

                // 保存到通用退款记录表
                try {
                    RefundRecord refundRecord = buildRefundRecordFromAlipayResponse(refundResponse, responseBody, params);
                    if (refundRecord != null) {
                        long count = refundRecordService.lambdaQuery()
                                .eq(RefundRecord::getOutRefundNo, refundRecord.getOutRefundNo())
                                .count();
                        if (count == 0) {
                            refundRecordService.save(refundRecord);
                            log.info("[支付宝服务商退款] 退款记录已保存，商户退款单号：{}", refundRecord.getOutRefundNo());
                        } else {
                            log.info("[支付宝服务商退款] 退款记录已存在，跳过插入，商户退款单号：{}", refundRecord.getOutRefundNo());
                        }
                    }
                } catch (Exception e) {
                    log.error("[支付宝服务商退款] 保存 RefundRecord 失败", e);
                }
            } else {
                log.warn("[支付宝服务商退款] 退款失败 body={}", response.getBody());
                refundResult = refundResponse.getString("sub_msg");

                try {
                    RefundRecord refundRecord = buildRefundRecordFromAlipayError(refundResponse, responseBody, params);
                    if (refundRecord != null) {
                        long count = refundRecordService.lambdaQuery()
                                .eq(RefundRecord::getOutRefundNo, refundRecord.getOutRefundNo())
                                .count();
                        if (count == 0) {
                            refundRecordService.save(refundRecord);
                            log.info("[支付宝服务商退款] 退款失败记录已保存，商户退款单号：{}", refundRecord.getOutRefundNo());
                        } else {
                            log.info("[支付宝服务商退款] 退款失败记录已存在，跳过插入，商户退款单号：{}", refundRecord.getOutRefundNo());
                        }
                    }
                } catch (Exception e) {
                    log.error("[支付宝服务商退款] 保存退款失败 RefundRecord 失败", e);
                }
            }
            return refundResult;
        } catch (AlipayApiException e) {
            log.error("[支付宝服务商退款] 调用 alipay.trade.refund 异常 outTradeNo={}", params.get("outTradeNo"), e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 构建 alipay.trade.refund 退款请求。
     */
    private AlipayTradeRefundRequest buildRefundRequest(Map<String, String> params) {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        model.setOutTradeNo(params.get("outTradeNo"));
        model.setRefundAmount(params.get("refundAmount"));
        model.setRefundReason(params.get("refundReason"));
        if (StringUtils.isNotBlank(params.get("partialRefundCode"))) {
            model.setOutRequestNo(params.get("partialRefundCode"));
        }
        // 设置退分账明细信息
        List<OpenApiRoyaltyDetailInfoPojo> refundRoyaltyParameters = new ArrayList<OpenApiRoyaltyDetailInfoPojo>();
        OpenApiRoyaltyDetailInfoPojo refundRoyaltyParameters0 = new OpenApiRoyaltyDetailInfoPojo();
//        refundRoyaltyParameters0.setAmount("0.01");
//        refundRoyaltyParameters0.setTransIn("2088101126708402");
//        refundRoyaltyParameters0.setRoyaltyType("transfer");
//        refundRoyaltyParameters0.setTransOut("2088101126765726");
//        refundRoyaltyParameters0.setTransOutType("userId");
//        refundRoyaltyParameters0.setRoyaltyScene("达人佣金");
//        refundRoyaltyParameters0.setTransInType("userId");
//        refundRoyaltyParameters0.setTransInName("张三");
//        refundRoyaltyParameters0.setDesc("分账给2088101126708402");
//        refundRoyaltyParameters.add(refundRoyaltyParameters0);

        model.setRefundRoyaltyParameters(refundRoyaltyParameters);
        request.setBizModel(model);
        return request;
    }

    /**
     * 执行退款请求（直付通使用公钥模式，调用 execute）。
     */
    private AlipayTradeRefundResponse refundRun(AlipayTradeRefundRequest request) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
        return alipayClient.execute(request);
    }

    /**
     * 从支付宝退款成功响应构建 RefundRecord。
     */
    private RefundRecord buildRefundRecordFromAlipayResponse(JSONObject refundResponse, JSONObject responseBody, Map<String, String> params) {
        try {
            RefundRecord record = new RefundRecord();
            record.setPayType(PaymentEnum.ALIPAY_PARTNER.getType());
            record.setOutTradeNo(refundResponse.getString("out_trade_no"));
            record.setTransactionId(refundResponse.getString("trade_no"));
            String outRefundNo = params.get("partialRefundCode");
            if (StringUtils.isBlank(outRefundNo)) {
                outRefundNo = UniqueRandomNumGenerator.generateUniqueCode(19);
            }
            record.setOutRefundNo(outRefundNo);
            record.setRefundStatus("SUCCESS");

            String refundFeeStr = refundResponse.getString("refund_fee");
            String sendBackFeeStr = refundResponse.getString("send_back_fee");
            if (StringUtils.isNotBlank(refundFeeStr)) {
                record.setRefundAmount(new BigDecimal(refundFeeStr).multiply(new BigDecimal(100)).longValue());
            }
            if (StringUtils.isNotBlank(sendBackFeeStr)) {
                record.setActualRefundAmount(new BigDecimal(sendBackFeeStr).multiply(new BigDecimal(100)).longValue());
            }
            String totalAmountStr = params.get("totalAmount");
            if (StringUtils.isNotBlank(totalAmountStr)) {
                record.setTotalAmount(new BigDecimal(totalAmountStr).multiply(new BigDecimal(100)).longValue());
            }
            record.setCurrency("CNY");
            record.setRefundReason(params.get("refundReason"));

            if (refundResponse.containsKey("refund_detail_item_list")) {
                JSONArray refundDetailList = refundResponse.getJSONArray("refund_detail_item_list");
                if (refundDetailList != null) {
                    record.setRefundDetail(JSON.toJSONString(refundDetailList));
                }
            }
            record.setUserReceivedAccount(refundResponse.getString("buyer_logon_id"));

            String gmtRefundPayStr = refundResponse.getString("gmt_refund_pay");
            if (StringUtils.isNotBlank(gmtRefundPayStr)) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date refundTime = sdf.parse(gmtRefundPayStr);
                    record.setRefundSuccessTime(refundTime);
                    record.setRefundCreateTime(refundTime);
                } catch (ParseException e) {
                    log.warn("[支付宝服务商退款] 解析退款时间失败: {}", gmtRefundPayStr, e);
                }
            }

            fillRefundRecordBusinessFields(record, params);
            record.setResponseData(responseBody.toJSONString());
            record.setDeleteFlag(0);
            record.setCreatedTime(new Date());
            return record;
        } catch (Exception e) {
            log.error("[支付宝服务商退款] 构建 RefundRecord 失败", e);
            return null;
        }
    }

    /**
     * 从支付宝退款失败响应构建 RefundRecord。
     */
    private RefundRecord buildRefundRecordFromAlipayError(JSONObject refundResponse, JSONObject responseBody, Map<String, String> params) {
        try {
            RefundRecord record = new RefundRecord();
            record.setPayType(PaymentEnum.ALIPAY_PARTNER.getType());
            record.setOutTradeNo(params.get("outTradeNo"));
            String outRefundNo = params.get("partialRefundCode");
            if (StringUtils.isBlank(outRefundNo)) {
                outRefundNo = UniqueRandomNumGenerator.generateUniqueCode(19);
            }
            record.setOutRefundNo(outRefundNo);
            record.setRefundStatus("ABNORMAL");

            String refundAmountStr = params.get("refundAmount");
            if (StringUtils.isNotBlank(refundAmountStr)) {
                record.setRefundAmount(new BigDecimal(refundAmountStr).multiply(new BigDecimal(100)).longValue());
            }
            String totalAmountStr = params.get("totalAmount");
            if (StringUtils.isNotBlank(totalAmountStr)) {
                record.setTotalAmount(new BigDecimal(totalAmountStr).multiply(new BigDecimal(100)).longValue());
            }
            record.setCurrency("CNY");
            record.setRefundReason(params.get("refundReason"));
            record.setErrorCode(refundResponse.getString("code"));
            record.setErrorMsg(refundResponse.getString("sub_msg"));

            fillRefundRecordBusinessFields(record, params);
            record.setResponseData(responseBody.toJSONString());
            record.setDeleteFlag(0);
            record.setCreatedTime(new Date());
            record.setRefundCreateTime(new Date());
            return record;
        } catch (Exception e) {
            log.error("[支付宝服务商退款] 构建退款失败 RefundRecord 失败", e);
            return null;
        }
    }

    /**
     * 填充退款记录中的业务字段（userId、orderId、storeId）。
     */
    private void fillRefundRecordBusinessFields(RefundRecord record, Map<String, String> params) {
        if (params.containsKey("userId")) {
            try {
                record.setUserId(Integer.parseInt(params.get("userId")));
            } catch (NumberFormatException e) {
                log.warn("[支付宝服务商退款] 解析 userId 失败: {}", params.get("userId"));
            }
        }
        if (params.containsKey("orderId")) {
            record.setOrderId(params.get("orderId"));
        }
        if (params.containsKey("storeId")) {
            try {
                record.setStoreId(Integer.parseInt(params.get("storeId")));
            } catch (NumberFormatException e) {
                log.warn("[支付宝服务商退款] 解析 storeId 失败: {}", params.get("storeId"));
            }
        }
    }

    @Override
    public R searchRefundRecordByOutRefundNo(String outRefundNo) throws Exception {
        return null;
    }

    @Override
    public String getType() {
        return PaymentEnum.ALIPAY_PARTNER.getType();
    }
}
