package com.yn.bftl.thirdparty.modules.unionpay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yn.bftl.common.common.exception.YnceError;
import com.yn.bftl.common.common.util.RouteUtil;
import com.yn.bftl.common.modules.account.entity.Payment;
import com.yn.bftl.common.modules.account.enums.PaymentType;
import com.yn.bftl.common.modules.company.entity.Company;
import com.yn.bftl.common.modules.configuration.entity.ThirdPartyPaySet;
import com.yn.bftl.common.modules.order.dto.PosRefundDTO;
import com.yn.bftl.common.modules.order.entity.Order;
import com.yn.bftl.common.modules.order.entity.Shipping;
import com.yn.bftl.common.modules.order.entity.TopUpOrder;
import com.yn.bftl.common.modules.order.enums.*;
import com.yn.bftl.common.modules.order.vo.OrderOnlinePayVO;
import com.yn.bftl.common.modules.relation.entity.SMArchives;
import com.yn.bftl.thirdparty.common.exception.YnceErrorException;
import com.yn.bftl.thirdparty.common.repository.OrderRepository;
import com.yn.bftl.thirdparty.common.repository.PaymentRepository;
import com.yn.bftl.thirdparty.common.repository.SMArchivesRepository;
import com.yn.bftl.thirdparty.common.service.BaseMemberService;
import com.yn.bftl.thirdparty.common.util.HttpClientUtil;
import com.yn.bftl.thirdparty.common.util.SequenceUtil;
import com.yn.bftl.thirdparty.common.repository.RefundRepository;
import com.yn.bftl.thirdparty.modules.business.service.SubaccountService;
import com.yn.bftl.thirdparty.modules.business.util.ThirdPartyConfigUtil;
import com.yn.bftl.thirdparty.modules.erp.service.ErpService;
import com.yn.bftl.thirdparty.modules.erp.vo.ErpResponseVO;
import com.yn.bftl.thirdparty.modules.unionpay.dto.PosAppRechargeDTO;
import com.yn.bftl.thirdparty.modules.unionpay.dto.PosPayResultDTO;
import com.yn.bftl.thirdparty.modules.unionpay.dto.PosRefundResultDTO;
import com.yn.bftl.thirdparty.modules.unionpay.dto.UnionpaySubOrderItemDTO;
import com.yn.bftl.thirdparty.modules.unionpay.enums.UnionpayAppOrderType;
import com.yn.bftl.thirdparty.modules.unionpay.repository.TopUpOrderRepository;
import com.yn.bftl.thirdparty.modules.unionpay.service.PosPayService;
import com.yn.bftl.thirdparty.modules.unionpay.service.UmsPayService;
import com.yn.bftl.thirdparty.modules.unionpay.util.UnionpayUtil;
import com.yn.bftl.thirdparty.modules.unionpay.vo.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author：Vance
 * @Description：POS支付
 * @Date：2022/9/13 09:21
 */
@Service
@RequiredArgsConstructor
public class PosPayServiceImpl extends BaseMemberService implements PosPayService {

    private final OrderRepository orderRepository;
    private final UmsPayService umsPayService;
    private final PaymentRepository paymentRepository;
    private final SubaccountService subaccountService;
    private final UnionpayUtil unionpayUtil;
    private final ThirdPartyConfigUtil thirdPartyConfigUtil;
    private final SequenceUtil sequenceUtil;
    private final RefundRepository refundRepository;
    private final TopUpOrderRepository topUpOrderRepository;
    private final SMArchivesRepository smArchivesRepository;
    private final ErpService erpService;
    private final Logger logger = LoggerFactory.getLogger(PosPayServiceImpl.class);

    @Transactional(rollbackFor = Exception.class)
    @Override
    public PosPayVO appOrder(Long orderId, String hardwareSn, PosPaymentType payType) {
        Order order = this.orderRepository.findById(orderId)
                .orElseThrow(() -> new YnceErrorException(YnceError.YNCE_204003));
        if (!OrderStatus.CREATED.equals(order.getOrderStatus())) {
            throw new YnceErrorException("订单" + order.getOrderStatus().getName());
        }
        if (!order.getApprovalStatus().equals(ApprovalStatus.APPROVE)) {
            throw new YnceErrorException(YnceError.YNCE_204016);
        }
        if (!order.getPaymentStatus().equals(PaymentStatus.UN_PAID)) {
            throw new YnceErrorException(YnceError.YNCE_204015);
        }

        // 创建支付单
        this.subaccountService.createPayment(order, null, UnionpayAppOrderType.POS, null, payType, hardwareSn);
        // 银联POS配置
        /*
         * 测试参数
         * 包名：com.ums.paydemo
         * appid: 158ecf64f30c45a28432bc4e7d80ccaa
         * appkey: a243dda74add473c82dd53c3bbb3555f
         */
        ThirdPartyPaySet thirdPartyPaySet = this.unionpayUtil.getThirdPartyPaySet(order.getConsignmentCompany() != null ? order.getConsignmentCompany().getId() : order.getSellerCompany().getId());
        PosPayVO posPayVO = new PosPayVO();
        if (payType.equals(PosPaymentType.BANK_CARD)) {
            posPayVO.setTransId("消费");
            posPayVO.setAppName("银行卡收款");
        } else if (payType.equals(PosPaymentType.RICH_SCAN)) {
            posPayVO.setTransId("扫一扫");
            posPayVO.setAppName("POS 通");
        }
        PostPayDataVO postPayDataVO = new PostPayDataVO();
        postPayDataVO.setAppId(thirdPartyPaySet.getPosAppId());
        postPayDataVO.setExtOrderNo(order.getSn());
        postPayDataVO.setIsNeedPrintReceipt(false);
        postPayDataVO.setAmt(order.getAmount().subtract(order.getPayAmount()).multiply(new BigDecimal(100)).longValue());
        postPayDataVO.setExtToUlink(true);
        posPayVO.setTransData(postPayDataVO);
        return posPayVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public PosRefundVO refund(Long orderId) {
        logger.info("订单ID[{}]请求POS撤销", orderId);
        Payment payment = paymentRepository.findFirstByOrderIdAndPayStatusOrderByIdDesc(orderId + "", PayStatus.SUCC);
        if (payment == null) {
            throw new YnceErrorException(YnceError.YNCE_205007);
        }
        if (!PaymentMethod.POS.equals(payment.getPaymentMethod())) {
            throw new YnceErrorException("此接口只支持POS方式支付的订单退款");
        }
        // POS支付的订单在退款时需校验是否当天
        if (!payment.getPaymentTime().toLocalDate().equals(LocalDate.now())) {
            throw new YnceErrorException("非下单当天不允许进行撤销");
        }
        // 查询订单
        Order order = orderRepository.findById(orderId).orElse(null);
        if (order == null) {
            throw new YnceErrorException(YnceError.YNCE_204003);
        }

        // 关闭U9订单
        this.closeU9Order(order);

        String refundSn = sequenceUtil.getNextSequenceNumber("TK");
        payment.setRefundSn(refundSn);
        paymentRepository.save(payment);
        return getPosRefundVO(payment, order.getConsignmentCompany() != null ? order.getConsignmentCompany().getId() : order.getSellerCompany().getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public PosRefundSalesVO refundSales(Long orderId) {
        logger.info("订单ID[{}]请求POS退货", orderId);
        Order order = orderRepository.findById(orderId).orElseThrow(() -> new YnceErrorException(YnceError.YNCE_204003));
        Payment payment = paymentRepository.findFirstByOrderIdAndPayStatusOrderByIdDesc(orderId + "", PayStatus.SUCC);
        if (payment == null) {
            throw new YnceErrorException(YnceError.YNCE_205007);
        }
        if (!PaymentMethod.POS.equals(payment.getPaymentMethod())) {
            throw new YnceErrorException("此接口只支持POS方式支付的订单退款");
        }
        if (payment.getPaymentTime().toLocalDate().equals(LocalDate.now())) {
            throw new YnceErrorException("下单当天请调用撤销进行退款");
        }
        // 需判断单据（自有订单根据订单是否分账、OEM订单根据发货单是否分账判断）是否已分账，确定是否可申请退款
        if (order.getIsSeparateAccounts()) {
            throw new YnceErrorException(YnceError.YNCE_204077);
        }
        List<Shipping> shippings = order.getShippings();
        if (CollectionUtils.isNotEmpty(shippings)) {
            for (Shipping shipping : shippings) {
                if (shipping.getIsSeparateAccounts()) {
                    throw new YnceErrorException(YnceError.YNCE_204077);
                }
            }
        }

        // 关闭U9订单
        this.closeU9Order(order);

        // 银联POS配置
        /*
         * 测试参数
         * 包名：com.ums.paydemo
         * appid: 158ecf64f30c45a28432bc4e7d80ccaa
         * appkey: a243dda74add473c82dd53c3bbb3555f
         */
        String refundSn = sequenceUtil.getNextSequenceNumber("TK");
        payment.setRefundSn(refundSn);
        paymentRepository.save(payment);
        ThirdPartyPaySet thirdPartyPaySet = this.unionpayUtil.getThirdPartyPaySet(order.getConsignmentCompany() != null ? order.getConsignmentCompany().getId() : order.getSellerCompany().getId());
        PosRefundSalesVO refundSalesVO = new PosRefundSalesVO();
        refundSalesVO.setAppName("公共资源");
        refundSalesVO.setTransId("退货");
        PosRefundSalesDataVO transData = new PosRefundSalesDataVO();
        transData.setAppId(thirdPartyPaySet.getPosAppId());
        transData.setIsNeedPrintReceipt(false);
        transData.setExtOrderNo(refundSn);
        transData.setAmt(payment.getAmount().multiply(new BigDecimal("100")).longValue());
        transData.setUseScan("false");
        transData.setRefNo(payment.getExternalId());
        transData.setDate(payment.getPaymentTime().format(DateTimeFormatter.ofPattern("MMdd")));
        transData.setTradeYear(payment.getPaymentTime().format(DateTimeFormatter.ofPattern("YYYY")));
        refundSalesVO.setTransData(transData);
        return refundSalesVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean payCallBack(PosPayResultDTO dto) {
        if (StringUtils.isBlank(dto.getTransData().getExtOrderNo())) {
            throw new YnceErrorException(YnceError.YNCE_205007);
        }
        List<Payment> payments = paymentRepository.findByOrderSn(dto.getTransData().getExtOrderNo());
        if (CollectionUtils.isEmpty(payments)) {
            throw new YnceErrorException(YnceError.YNCE_205007);
        }
        Payment payment = payments.get(0);
        if (PayStatus.SUCC.equals(payment.getPayStatus())) {
            return true;
        }

        if ("0".equals(dto.getResultCode())) {
            if ("00".equals(dto.getTransData().getResCode())) {
                ThirdPartyPaySet thirdPartyPaySet = thirdPartyConfigUtil.getPlatform();
                if (thirdPartyPaySet == null) {
                    throw new YnceErrorException("未配置第三方请求地址");
                }
                // 生成收款单以及后续业务操作
                LocalDateTime payTime = LocalDateTime.parse(dto.getTransData().getDate() + dto.getTransData().getTime(),
                        DateTimeFormatter.ofPattern("yyyy/MM/ddHH:mm:ss"));
                OrderOnlinePayVO orderOnlinePayVO = new OrderOnlinePayVO();
                orderOnlinePayVO.setOrderId(Long.valueOf(payment.getOrderId()));
                orderOnlinePayVO.setPaymentId(payment.getId());
                orderOnlinePayVO.setPayTime(payTime);
                orderOnlinePayVO.setExternalId(dto.getTransData().getRefNo());
                JSONObject result = HttpClientUtil.getInstance().sendPost(thirdPartyPaySet.getServiceUrl() + RouteUtil.ROUTE_RECEIPT_ONLINE_PAY, orderOnlinePayVO);
                if (!result.get("code").toString().equals("200")) {
                    throw new YnceErrorException("线上收款失败！");
                }
                payment.setPayStatus(PayStatus.SUCC);
                payment.setPaymentTime(payTime);
                payment.setExternalId(dto.getTransData().getRefNo());
                payment.setUnionpaySn(dto.getTransData().getRefNo());
                payment.setTraceNo(dto.getTransData().getTraceNo());
                payment.setMerchantName(dto.getTransData().getMerchantName());
                payment.setMerchantNo(dto.getTransData().getMerchantNo());
                payment.setTerminalNo(dto.getTransData().getTerminalNo());
                paymentRepository.save(payment);
                return true;
            } else {
                throw new YnceErrorException(dto.getTransData().getResCode(), dto.getTransData().getResDesc());
            }
        } else {
            throw new YnceErrorException(dto.getResultCode(), dto.getResultMsg());
        }
    }

    @Override
    public Boolean refundCallBack(PosRefundResultDTO dto) {
        if ("0".equals(dto.getResultCode())) {
            if ("00".equals(dto.getTransData().getResCode())) {
                if (refundRepository.existsByUnionpayRefundSn(dto.getTransData().getRefNo())) {
                    return true;
                }

                Payment payment = paymentRepository.findFirstByRefundSnOrderByIdDesc(dto.getTransData().getExtOrderNo());
                if (payment == null) {
                    throw new YnceErrorException(YnceError.YNCE_205007);
                }
                if (!PayStatus.SUCC.equals(payment.getPayStatus())) {
                    throw new YnceErrorException("支付单状态异常");
                }
                ThirdPartyPaySet thirdPartyPaySet = thirdPartyConfigUtil.getPlatform();
                if (thirdPartyPaySet == null) {
                    throw new YnceErrorException("未配置第三方请求地址");
                }
                PosRefundDTO posRefundDTO = new PosRefundDTO();
                posRefundDTO.setOrderId(Long.valueOf(payment.getOrderId()));
                posRefundDTO.setRefundSn(dto.getTransData().getExtOrderNo());
                LocalDateTime refundTime = LocalDateTime.parse(dto.getTransData().getDate() + dto.getTransData().getTime(),
                        DateTimeFormatter.ofPattern("yyyy/MM/ddHH:mm:ss"));
                posRefundDTO.setRefundTime(refundTime);
                posRefundDTO.setRefNo(dto.getTransData().getRefNo());
                posRefundDTO.setCardNo(dto.getTransData().getCardNo());
                posRefundDTO.setCardIssuerCode(dto.getTransData().getCardIssuerCode());
                JSONObject result = HttpClientUtil.getInstance().sendPost(thirdPartyPaySet.getServiceUrl() + RouteUtil.ROUTE_ORDER_POS_REFUND, posRefundDTO);
                if (!result.get("code").toString().equals("200")) {
                    throw new YnceErrorException("退款失败！");
                }
                return true;
            } else {
                throw new YnceErrorException(dto.getTransData().getResCode(), dto.getTransData().getResDesc());
            }
        } else {
            throw new YnceErrorException(dto.getResultCode(), dto.getResultMsg());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public PosPayVO appRecharge(PosAppRechargeDTO posAppRechargeDTO) {
        // 获取充值企业
        SMArchives smArchives = smArchivesRepository.findById(posAppRechargeDTO.getDealerId()).orElseThrow(() -> new YnceErrorException("没有找到经销商"));
        // 获取登录企业
        Company company = getUser().getCompany();
        // if (!smArchives.getCompanyRelation().getPartyA().getId().equals(company.getId())) {
        //     throw new YnceErrorException("只允许给自己的经销商充值");
        // }

        Company partyB = smArchives.getCompanyRelation().getPartyB();
        // 生成充值订单
        TopUpOrder topUpOrder = new TopUpOrder();
        topUpOrder.setSn(sequenceUtil.getNextSequenceNumber("CZDD"));
        topUpOrder.setCompany(company);
        topUpOrder.setTopUpCompany(partyB);
        topUpOrder.setRemark(posAppRechargeDTO.getRemark());
        topUpOrder.setAmount(posAppRechargeDTO.getAmount());
        topUpOrder.setPaymentStatus(PayStatus.READY);
        topUpOrder.setSyncState(SyncState.UNSYNCED);
        topUpOrder.setRefunded(false);
        topUpOrder.setHardwareSn(posAppRechargeDTO.getHardwareSn());
        topUpOrder.setOrderType(TopUpOrderType.POS);
        topUpOrderRepository.saveAndFlush(topUpOrder);
        // 模拟订单数据
        Order order = new Order();
        order.setId(topUpOrder.getId());
        order.setAmount(posAppRechargeDTO.getAmount());
        order.setSellerCompany(company);
        order.setBuyerCompany(partyB);
        order.setPaymentStatus(PaymentStatus.UN_PAID);
        // 创建支付单
        this.subaccountService.createPayment(order, PaymentType.RECHARGE, UnionpayAppOrderType.POS, null,
                posAppRechargeDTO.getPayType(), posAppRechargeDTO.getHardwareSn());
        // 银联POS配置
        /*
         * 测试参数
         * 包名：com.ums.paydemo
         * appid: 158ecf64f30c45a28432bc4e7d80ccaa
         * appkey: a243dda74add473c82dd53c3bbb3555f
         */
        ThirdPartyPaySet thirdPartyPaySet = this.unionpayUtil.getThirdPartyPaySet(topUpOrder.getCompany().getId());
        PosPayVO posPayVO = new PosPayVO();
        if (posAppRechargeDTO.getPayType().equals(PosPaymentType.BANK_CARD)) {
            posPayVO.setTransId("消费");
            posPayVO.setAppName("银行卡收款");
        } else if (posAppRechargeDTO.getPayType().equals(PosPaymentType.RICH_SCAN)) {
            posPayVO.setTransId("扫一扫");
            posPayVO.setAppName("POS 通");
        }
        PostPayDataVO postPayDataVO = new PostPayDataVO();
        postPayDataVO.setAppId(thirdPartyPaySet.getPosAppId());
        postPayDataVO.setExtOrderNo(topUpOrder.getSn());
        postPayDataVO.setIsNeedPrintReceipt(false);
        postPayDataVO.setAmt(topUpOrder.getAmount().multiply(new BigDecimal(100)).longValue());
        postPayDataVO.setExtToUlink(true);
        posPayVO.setTransData(postPayDataVO);
        return posPayVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean rechargeCallBack(PosPayResultDTO dto) {
        if (StringUtils.isBlank(dto.getTransData().getExtOrderNo())) {
            throw new YnceErrorException(YnceError.YNCE_205007);
        }
        List<Payment> payments = paymentRepository.findByTopUpOrderSn(dto.getTransData().getExtOrderNo());
        if (CollectionUtils.isEmpty(payments)) {
            throw new YnceErrorException(YnceError.YNCE_205007);
        }
        Payment payment = payments.get(0);
        if (PayStatus.SUCC.equals(payment.getPayStatus())) {
            return true;
        }
        TopUpOrder topUpOrder = topUpOrderRepository.findBySn(dto.getTransData().getExtOrderNo());
        if (topUpOrder == null) {
            throw new YnceErrorException("POS充值订单未找到");
        }
        if (PayStatus.SUCC.equals(topUpOrder.getPaymentStatus())) {
            return true;
        }

        if ("0".equals(dto.getResultCode())) {
            if ("00".equals(dto.getTransData().getResCode())) {
                LocalDateTime payTime = LocalDateTime.parse(dto.getTransData().getDate() + dto.getTransData().getTime(),
                        DateTimeFormatter.ofPattern("yyyy/MM/ddHH:mm:ss"));
                payment.setPayStatus(PayStatus.SUCC);
                payment.setPaymentTime(payTime);
                payment.setExternalId(dto.getTransData().getRefNo());
                payment.setUnionpaySn(dto.getTransData().getRefNo());
                payment.setTraceNo(dto.getTransData().getTraceNo());
                payment.setMerchantName(dto.getTransData().getMerchantName());
                payment.setMerchantNo(dto.getTransData().getMerchantNo());
                payment.setTerminalNo(dto.getTransData().getTerminalNo());
                paymentRepository.save(payment);
                topUpOrder.setPaymentStatus(PayStatus.SUCC);
                topUpOrder.setPayTime(payTime);
                topUpOrder.setExternalId(dto.getTransData().getRefNo());
                topUpOrderRepository.save(topUpOrder);
                return true;
            } else if ("FK".equals(dto.getTransData().getResCode())) {
                topUpOrder.setPaymentStatus(PayStatus.CANCEL);
                topUpOrder.setFailReason(dto.getTransData().getResCode() + "：" + dto.getTransData().getResDesc());
                topUpOrderRepository.save(topUpOrder);
                return false;
            } else {
                topUpOrder.setPaymentStatus(PayStatus.FAILED);
                topUpOrder.setFailReason(dto.getTransData().getResCode() + "：" + dto.getTransData().getResDesc());
                topUpOrderRepository.save(topUpOrder);
                return false;
            }
        } else {
            topUpOrder.setPaymentStatus(PayStatus.ERROR);
            topUpOrder.setFailReason(dto.getResultCode() + "：" + dto.getResultMsg());
            topUpOrderRepository.save(topUpOrder);
            return false;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public PosRefundVO rechargeRefund(Long topUpOrderId) {
        logger.info("充值订单ID[{}]请求POS撤销", topUpOrderId);
        Payment payment = paymentRepository.findFirstByTopUpOrderIdAndPayStatusOrderByIdDesc(topUpOrderId, PayStatus.SUCC);
        if (payment == null) {
            throw new YnceErrorException(YnceError.YNCE_205007);
        }
        if (!payment.getPaymentTime().toLocalDate().equals(LocalDate.now())) {
            throw new YnceErrorException("非充值当天不允许进行撤销");
        }
        TopUpOrder topUpOrder = topUpOrderRepository.findById(payment.getTopUpOrderId()).orElseThrow(() -> new YnceErrorException("充值订单不存在"));
        if (SyncState.SYNCED.equals(topUpOrder.getSyncState())) {
            throw new YnceErrorException("订单已同步，不允许撤销");
        }
        String refundSn = sequenceUtil.getNextSequenceNumber("CZTK");
        payment.setRefundSn(refundSn);
        paymentRepository.save(payment);
        return getPosRefundVO(payment, topUpOrder.getCompany().getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean rechargeRefundCallBack(PosRefundResultDTO dto) {
        if ("0".equals(dto.getResultCode())) {
            if ("00".equals(dto.getTransData().getResCode())) {
                Payment payment = paymentRepository.findFirstByRefundSnOrderByIdDesc(dto.getTransData().getExtOrderNo());
                if (payment == null) {
                    throw new YnceErrorException(YnceError.YNCE_205007);
                }
                if (!PayStatus.SUCC.equals(payment.getPayStatus())) {
                    throw new YnceErrorException("支付单状态异常");
                }
                TopUpOrder topUpOrder = topUpOrderRepository.findById(payment.getTopUpOrderId()).orElseThrow(() -> new YnceErrorException("充值订单不存在"));
                if (topUpOrder.getRefunded()) {
                    return true;
                }
                LocalDateTime refundTime = LocalDateTime.parse(dto.getTransData().getDate() + dto.getTransData().getTime(),
                        DateTimeFormatter.ofPattern("yyyy/MM/ddHH:mm:ss"));
                topUpOrder.setRefundTime(refundTime);
                topUpOrder.setRefundSn(dto.getTransData().getExtOrderNo());
                topUpOrder.setRefundRefNo(dto.getTransData().getRefNo());
                topUpOrder.setRefunded(true);
                topUpOrderRepository.save(topUpOrder);
                return true;
            } else {
                throw new YnceErrorException(dto.getTransData().getResCode(), dto.getTransData().getResDesc());
            }
        } else {
            throw new YnceErrorException(dto.getResultCode(), dto.getResultMsg());
        }
    }

    private PosRefundVO getPosRefundVO(Payment payment, Long companyId) {
        // 银联POS配置
        /*
         * 测试参数
         * 包名：com.ums.paydemo
         * appid: 158ecf64f30c45a28432bc4e7d80ccaa
         * appkey: a243dda74add473c82dd53c3bbb3555f
         */
        ThirdPartyPaySet thirdPartyPaySet = this.unionpayUtil.getThirdPartyPaySet(companyId);
        PosRefundVO refundVo = new PosRefundVO();
        refundVo.setAppName("公共资源");
        refundVo.setTransId("撤销");
        PosRefundDataVO transData = new PosRefundDataVO();
        transData.setAppId(thirdPartyPaySet.getPosAppId());
        transData.setIsNeedPrintReceipt(false);
        transData.setExtOrderNo(payment.getRefundSn());
        transData.setUseScan("false");
        transData.setOrgTraceNo(payment.getTraceNo());
        refundVo.setTransData(transData);
        return refundVo;
    }

    /**
     * 关闭U9订单
     */
    private void closeU9Order(Order order) {
        if (StringUtils.isBlank(order.getErpNumber())) {
            return;
        }

        ErpResponseVO erpResponseVO = erpService.deleteWholeLine(order);
        if ("0".equals(erpResponseVO.getErrcode())) {
            return;
        }
        if (StringUtils.contains(erpResponseVO.getErrmsg(), "找不到对应单据")) {
            return;
        }
        throw new YnceErrorException("关闭U9订单失败：" + erpResponseVO.getErrmsg());
    }
}
