package com.bonus.core.pay.channel.ali.service;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.alipay.api.*;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.core.allocation.alloc.model.AllocPayModel;
import com.bonus.core.allocation.api.AllocMetadataApi;
import com.bonus.core.allocation.api.AllocPayMetadataApi;
import com.bonus.core.auth.mobile.api.AliPayApi;
import com.bonus.core.common.config.sys.ThirdApiUrlProperties;
import com.bonus.core.common.constant.NuclearModeEnum;
import com.bonus.core.common.enums.MetadataModelTypeEnum;
import com.bonus.core.common.enums.SourceTypeEnum;
import com.bonus.core.common.thirdutils.alipay.AliPayUtil;
import com.bonus.core.common.thirdutils.alipay.model.BusinessParamsReq;
import com.bonus.core.common.thridutils.alipay.AliEnterpriseCodeUtil;
import com.bonus.core.common.thridutils.pay.ali.constant.AliPayTradeStatusEnum;
import com.bonus.core.common.thridutils.pay.ali.vo.AlipayNotifyVO;
import com.bonus.core.common.utils.LeCodeUtil;
import com.bonus.core.common.utils.SpringContextHolder;
import com.bonus.core.common.utils.TenantContextHolder;
import com.bonus.core.customer.api.CustCasualApi;
import com.bonus.core.order.utils.LeOrderUtil;
import com.bonus.core.pay.channel.ali.api.AlipayAPI;
import com.bonus.core.pay.channel.ali.extension.AliPayExtension;
import com.bonus.core.pay.channel.ali.mq.PayMqSender;
import com.bonus.core.pay.common.business.ChannelBusiness;
import com.bonus.core.pay.common.constants.*;
import com.bonus.core.pay.common.dto.*;
import com.bonus.core.pay.common.mapper.TradeRecordChannelMapper;
import com.bonus.core.pay.common.model.TradeChannel;
import com.bonus.core.pay.common.service.PayChannelSelectService;
import com.bonus.core.pay.common.service.TradeChannelService;
import com.bonus.core.pay.common.vo.*;
import com.bonus.core.pay.custom.PayCustomAlipayBusiness;
import com.bonus.core.report.bill.vo.BillDetailVO;
import com.bonus.domain.CustCasual;
import com.bonus.i18n.I18n;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service("aliPay")
public class AliPayServiceImpl implements AliPayExtension {
   private static final Logger log = LoggerFactory.getLogger(AliPayServiceImpl.class);
   @Autowired
   @Lazy
   private AllocMetadataApi allocMetadataApi;
   @Autowired
   @Lazy
   private AllocPayMetadataApi allocPayMetadataApi;
//   @Lazy
//   @Autowired
//   private CustInfoApi custInfoApi;
   @Autowired
   private AliPayUtil aliPayUtil;
   @Autowired
   private ThirdApiUrlProperties thirdApiUrlProperties;
   @Value("${system.notify.notify-url}")
   private String notifyUrl;

//   @Autowired
//   private AlipayProperties alipayProperties;
//   @Autowired
//   private AlipayServiceApi alipayServiceApi;
//   @Autowired
   @Lazy
   private AliPayApi aliPayApi;
   @Autowired
   @Lazy
   private CustCasualApi custCasualApi;
   @Autowired
   @Lazy
   private ChannelBusiness channelBusiness;
   @Autowired
   @Lazy
   private TradeChannelService tradeChannelService;
   @Autowired
   @Lazy
   private PayCustomAlipayBusiness payCustomAlipayBusiness;
//   private final String notifyUrl = "/dev-api/smart-canteen/api/v2/pay/ali/notify";
   private static final List<PayAsset> PAY_ASSETS = Lists.newArrayList(new PayAsset[]{new PayAsset()});

   @Nullable
   public String parseOpenIdFromAuthCode(@Nonnull String authCode, @Nullable Long canteenId) {
      if (!LeCodeUtil.isAliPayCode(authCode)) {
         log.warn("[支付宝]付款码格式不正确: {}", authCode);
         return null;
      } else {
         return this.aliPayApi.paymentCodeDecod(authCode);
      }
   }

   public MobilePayVO mobilePay(MobilePayDTO mobilePayDTO) {
      log.info("[支付宝]移动端支付下单_上送参数:{}", JSONObject.toJSONString(mobilePayDTO));
      MobilePayVO mobilePayVO = new MobilePayVO();
      mobilePayVO.setCode(PayStateEnum.PAY_FAIL.getKey());
      if (PayTypeEnum.ALI_APP_PAY.getKey().equals(mobilePayDTO.getPayType())) {
         this.appPay(mobilePayDTO, mobilePayVO);
         return mobilePayVO;
      } else if (!PayTypeEnum.ALI_NATIVE.getKey().equals(mobilePayDTO.getPayType()) && !PayTypeEnum.ALI_SCAN.getKey().equals(mobilePayDTO.getPayType())) {
         if (PayTypeEnum.ALI_H5_PAY.getKey().equals(mobilePayDTO.getPayType())) {
            this.h5Pay(mobilePayDTO, mobilePayVO);
            return mobilePayVO;
         } else {
            if (PayTypeEnum.ALI_ENTERPRISE_WITHHOLD.getKey().equals(mobilePayDTO.getPayType())) {
               log.info("[移动端企业码代扣]: " + mobilePayDTO.getCustId());
               AlipayAPI.EnterpriseCodeAliParam param = AlipayAPI.EnterpriseCodeAliParam.builder().totalAmount(this.centConvertDollarToStr(mobilePayDTO.getTotalAmount())).openId(mobilePayDTO.getOpenid()).accountId(AliEnterpriseCodeUtil.findEnterpriseAccountId()).outTradeNo(String.valueOf(mobilePayDTO.getTradeId())).alreadyPaid(this.centConvertDollarToStr(mobilePayDTO.getTotalAmount().subtract(mobilePayDTO.getAmount()))).canteenId(mobilePayDTO.getCanteenId()).build();
               AlipayAPI.EnterpriseCodeResponse response = this.enterpriseCodeAliPay(param);
               log.info("[企业码]返回： " + String.valueOf(response));
               mobilePayVO.setCode(response.getCode());
               mobilePayVO.setMsg(response.getMsg());
               mobilePayVO.setOutTradeNo(response.getOutTradeNo());
               mobilePayVO.setTradeId(mobilePayDTO.getTradeId());
               mobilePayVO.setAmount(mobilePayDTO.getAmount());
               if (response.getCode().equals(PayStateEnum.PAY_SUCC.getKey())) {
                  mobilePayVO.setRealAmount(mobilePayDTO.getAmount());
               }
            } else if (PayTypeEnum.ALI_PAY_WITHHOLD.getKey().equals(mobilePayDTO.getPayType())) {
               log.info("[支付宝]代扣支付: " + String.valueOf(mobilePayDTO));
               AlipayAPI.HoldingParam param = BeanUtil.copyProperties(mobilePayDTO, AlipayAPI.HoldingParam.class, new String[0]);
               AlipayAPI.HoldingResponse response = this.holdingAliPay(param);
               log.info("[支付宝]代扣支付返回： " + String.valueOf(response));
               mobilePayVO.setCode(response.getCode());
               mobilePayVO.setMsg(response.getMsg());
               mobilePayVO.setOutTradeNo(response.getOutTradeNo());
               mobilePayVO.setTradeId(mobilePayDTO.getTradeId());
               mobilePayVO.setAmount(mobilePayDTO.getAmount());
               if (response.getCode().equals(PayStateEnum.PAY_SUCC.getKey())) {
                  mobilePayVO.setRealAmount(mobilePayDTO.getAmount());
               }
            } else {
               mobilePayVO.setMsg(I18n.getMessage("pay.not-support-pay-type", new Object[0]));
            }

            return mobilePayVO;
         }
      } else {
         this.appletPay(mobilePayDTO, mobilePayVO);
         return mobilePayVO;
      }
   }
//
//   public AndroidPayVO androidPay(AndroidPayDTO androidPayDTO) {
//      if (PayTypeEnum.ALI_ENTERPRISE_QRCODE.getKey().equals(androidPayDTO.getPayType())) {
//         log.info("[企业码开启]: " + String.valueOf(androidPayDTO));
//         if (AliEnterpriseCodeUtil.isEnterpriseCodeEnabled()) {
//            AlipayAPI.EnterpriseCodeResponse response = this.enterpriseCodeFacePay(androidPayDTO);
//            AndroidPayVO androidPayVO = new AndroidPayVO();
//            if (response.getCode().equals(PayStateEnum.PAY_SUCC.getKey())) {
//               this.paySuccResultHandler(androidPayVO, androidPayDTO, response.getOutTradeNo());
//            } else if (response.getCode().equals(PayStateEnum.PAY_INPROCESS.getKey())) {
//               androidPayVO.setCode(PayStateEnum.PAY_INPROCESS.getKey());
//               androidPayVO.setMsg(response.getMsg());
//            } else {
//               androidPayVO.setCode(PayStateEnum.PAY_FAIL.getKey());
//               androidPayVO.setMsg(response.getMsg());
//            }
//
//            log.info("[设备在线企业码当面付]: " + String.valueOf(androidPayVO));
//            return androidPayVO;
//         }
//
//         log.info("[企业码]: 企业账户未激活");
//      } else {
//         AndroidPayVO androidPayVO;
//         if (PayTypeEnum.ALI_ENTERPRISE_WITHHOLD.getKey().equals(androidPayDTO.getPayType())) {
//            log.info("[企业码]: " + String.valueOf(androidPayDTO));
//            if (AliEnterpriseCodeUtil.isEnterpriseCodeEnabled()) {
//               log.info("[企业码]员工已加入: " + androidPayDTO.getOpenid());
//               AlipayAPI.EnterpriseCodeAliParam param = AlipayAPI.EnterpriseCodeAliParam.builder().totalAmount(this.centConvertDollarToStr(androidPayDTO.getTotalAmount())).outTradeNo(androidPayDTO.getTradeId().toString()).accountId(AliEnterpriseCodeUtil.findEnterpriseAccountId()).openId(androidPayDTO.getOpenid()).alreadyPaid(this.centConvertDollarToStr(androidPayDTO.getTotalAmount().subtract(androidPayDTO.getAmount()))).terminalParams(androidPayDTO.getTerminalParams()).alipayContractNum(androidPayDTO.getAlipayContractNum()).canteenId(androidPayDTO.getCanteenId()).build();
//               AlipayAPI.EnterpriseCodeResponse response = this.enterpriseCodeAliPay(param);
//               androidPayVO = new AndroidPayVO();
//               androidPayVO.setCode(response.getCode());
//               androidPayVO.setMsg(response.getMsg());
//               if (response.getCode().equals(PayStateEnum.PAY_SUCC.getKey())) {
//                  this.paySuccResultHandler(androidPayVO, androidPayDTO, response.getOutTradeNo());
//               }
//
//               log.info("[企业码代扣]: " + String.valueOf(androidPayVO));
//               return androidPayVO;
//            }
//
//            log.info("[企业码]: 企业账户未激活");
//            log.info("[企业码]员工没有加入到企业码里: " + androidPayDTO.getCustId());
//         } else if (PayTypeEnum.ALI_PAY_WITHHOLD.getKey().equals(androidPayDTO.getPayType())) {
//            log.info("[支付宝]代扣支付: " + String.valueOf(androidPayDTO));
//            AlipayAPI.HoldingParam param = (AlipayAPI.HoldingParam)BeanUtil.copyProperties(androidPayDTO, AlipayAPI.HoldingParam.class, new String[0]);
//            AlipayAPI.HoldingResponse response = this.holdingAliPay(param);
//            androidPayVO = new AndroidPayVO();
//            androidPayVO.setCode(response.getCode());
//            androidPayVO.setMsg(response.getMsg());
//            androidPayVO.setOutTradeNo(response.getOutTradeNo());
//            if (response.getCode().equals(PayStateEnum.PAY_SUCC.getKey())) {
//               this.paySuccResultHandler(androidPayVO, androidPayDTO, response.getOutTradeNo());
//            }
//
//            log.info("[支付宝]代扣支付: " + String.valueOf(androidPayVO));
//            return androidPayVO;
//         }
//      }
//
//      return this.faceToFaceAliPay(androidPayDTO);
//   }

   public AndroidPayVO paySelect(PaySelectDTO paySelectDTO) {
      log.info("[支付宝]查询支付结果_上传参数：{}", JSONObject.toJSONString(paySelectDTO));
      AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
      AndroidPayVO androidPayVO = new AndroidPayVO();
      androidPayVO.setCode(PayStateEnum.PAY_INPROCESS.getKey());
      AlipayTradeQueryModel queryModel = new AlipayTradeQueryModel();
      queryModel.setOutTradeNo(paySelectDTO.getTradeId().toString());
      request.setBizModel(queryModel);

      try {
         PayClient client = this.getAliPayClient(paySelectDTO.getCanteenId(), paySelectDTO.getPayType());
         AlipayTradeQueryResponse response = (AlipayTradeQueryResponse)this.execute(client, request);
         log.info("[支付宝]查询支付结果_返回参数：{}", response.getBody());
         androidPayVO.setCode(PayStateEnum.PAY_FAIL.getKey());
         if (response.isSuccess()) {
            String tradeStatus = response.getTradeStatus();
            if (AliPayTradeStatusEnum.TRADE_STATUS_SUCCESS.getKey().equals(tradeStatus)) {
               androidPayVO.setCode(PayStateEnum.PAY_SUCC.getKey());
               androidPayVO.setMsg(PayStateEnum.PAY_SUCC.getDesc());
               androidPayVO.setTradeId(Long.valueOf(response.getOutTradeNo()));
               androidPayVO.setOutTradeNo(response.getTradeNo());
               androidPayVO.setPersonalPay(androidPayVO.getAmount());
            } else if (AliPayTradeStatusEnum.TRADE_STATUS_WAIT.getKey().equals(tradeStatus)) {
               androidPayVO.setCode(PayStateEnum.PAY_INPROCESS.getKey());
               androidPayVO.setMsg(PayStateEnum.PAY_INPROCESS.getDesc());
            } else if (AliPayTradeStatusEnum.TRADE_STATUS_CLOSED.getKey().equals(tradeStatus)) {
               androidPayVO.setCode(PayStateEnum.PAY_FAIL.getKey());
               androidPayVO.setMsg(response.getSubMsg());
            }
         } else if (AliPayTradeStatusEnum.BUSINESS_CODE_FAIL.getKey().equals(response.getCode()) && AliPayTradeStatusEnum.BUSINESS_STATUS_SUCCESS.getKey().equals(response.getSubCode())) {
            androidPayVO.setCode(PayStateEnum.PAY_SUCC.getKey());
            androidPayVO.setMsg("该笔订单已支付");
         }
      } catch (Exception var8) {
         log.info("[支付宝]支付交易结果查询异常明细:", var8);
         androidPayVO.setMsg("查询支付宝支付结果异常");
      }

      return androidPayVO;
   }

   public PayCancelVO payCancel(PayCancelDTO payCancelDTO) {
      log.info("[支付宝]取消支付_上传参数:{}", JSONObject.toJSONString(payCancelDTO));
      AlipayTradeCancelRequest request = new AlipayTradeCancelRequest();
      AlipayTradeCancelModel cancelModel = new AlipayTradeCancelModel();
      cancelModel.setOutTradeNo(payCancelDTO.getTradeId().toString());
      request.setBizModel(cancelModel);
      PayCancelVO cancelResultVO = new PayCancelVO();
      cancelResultVO.setCode(CancelResultEnum.CANCEL_FAIL.getKey());
      cancelResultVO.setMsg(CancelResultEnum.CANCEL_FAIL.getDesc());

      try {
         PayClient client = this.getAliPayClient(payCancelDTO.getCanteenId(), payCancelDTO.getPayType());
         AlipayTradeCancelResponse response = (AlipayTradeCancelResponse)this.execute(client, request);
         log.info("[支付宝]关闭订单返回:{}", response.getBody());
         if (response.isSuccess()) {
            if (AliPayTradeStatusEnum.TRADE_STATUS_CANCEL_CLOSE.getKey().equals(response.getAction())) {
               log.info("[支付宝]取消支付成功,无退款");
            } else if (AliPayTradeStatusEnum.TRADE_STATUS_CANCEL_REFUND.getKey().equals(response.getAction())) {
               log.info("[支付宝]取消支付成功,有退款");
            }

            log.info("[支付宝]取消支付成功 tradeId:{} outTradeNo:{}", payCancelDTO.getTradeId(), response.getOutTradeNo());
            cancelResultVO.setCode(CancelResultEnum.CANCEL_SUCCESS.getKey());
            cancelResultVO.setMsg(CancelResultEnum.CANCEL_SUCCESS.getDesc());
         } else {
            cancelResultVO.setMsg(response.getSubMsg());
         }

         return cancelResultVO;
      } catch (AlipayApiException var7) {
         log.info("[支付宝]支付订单关闭异常明细:", var7);
         return cancelResultVO;
      }
   }

   public PayRefundVO payRefund(PayRefundDTO payRefundDTO) {
      log.info("[支付宝]支付退款_上传参数：{}", JSONObject.toJSONString(payRefundDTO));
      PayClient client = this.getAliPayClient(payRefundDTO.getCanteenId(), payRefundDTO.getPayType());
      AlipayTradeRefundRequest refundRequest = new AlipayTradeRefundRequest();
      AlipayTradeRefundModel refundModel = new AlipayTradeRefundModel();
      refundModel.setOutTradeNo(String.valueOf(payRefundDTO.getTradeId()));
      refundModel.setRefundAmount(this.centConvertDollarToStr(payRefundDTO.getRefundAmount()));
      refundModel.setOutRequestNo(String.valueOf(payRefundDTO.getRefundTradeId()));
      refundRequest.setBizModel(refundModel);
      PayRefundVO payRefundVO = new PayRefundVO();
      payRefundVO.setCode(PayStateEnum.PAY_FAIL.getKey());
      payRefundVO.setMsg("退款失败");

      try {
         AlipayTradeRefundResponse refundResponse = (AlipayTradeRefundResponse)this.execute(client, refundRequest);
         log.info("[支付宝]退款返回结果：{}", refundResponse.getBody());
         if (AliPayTradeStatusEnum.REQUEST_CODE_SUCCESS.getKey().equals(refundResponse.getCode())) {
            if ("Y".equals(refundResponse.getFundChange())) {
               this.refundSuccResultHandler(payRefundVO, payRefundDTO, refundResponse.getTradeNo());
            }
         } else {
            payRefundVO.setMsg(refundResponse.getSubMsg());
         }
      } catch (AlipayApiException var7) {
         log.error("[支付宝]退款异常：", var7);
         payRefundVO.setMsg(var7.getMessage());
      }

      return payRefundVO;
   }

   public RefundSelectVO refundSelect(RefundSelectDTO refundSelectDTO) {
      TradeRecordChannelMapper channelMapper = (TradeRecordChannelMapper) SpringContextHolder.getBean(TradeRecordChannelMapper.class);
      TradeChannel tradeChannel = (TradeChannel)channelMapper.selectById(refundSelectDTO.getTradeChannelId());
      AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
      AlipayTradeRefundModel refundModel = new AlipayTradeRefundModel();
      refundModel.setOutRequestNo(tradeChannel.getOutTradeNo());
      refundModel.setOutRequestNo(tradeChannel.getOutTradeNo());
      request.setBizModel(refundModel);
      RefundSelectVO result = new RefundSelectVO();

      try {
         PayClient client = this.getAliPayClient(refundSelectDTO.getCanteenId(), refundSelectDTO.getPayType());
         AlipayTradeFastpayRefundQueryResponse response = (AlipayTradeFastpayRefundQueryResponse)this.execute(client, request);
         if (response.isSuccess() && ObjectUtils.nullSafeEquals(response.getRefundStatus(), "REFUND_SUCCESS")) {
            result.setCode(PayStateEnum.PAY_SUCC.getKey());
            result.setMsg(PayStateEnum.PAY_SUCC.getDesc());
            return result;
         }
      } catch (AlipayApiException var9) {
         log.warn("[支付宝退款查询]出错: " + var9.getMessage());
      }

      result.setCode(PayStateEnum.PAY_INPROCESS.getKey());
      result.setMsg(PayStateEnum.PAY_INPROCESS.getDesc());
      return result;
   }

   public MobileNotifyVO aliNotifyHandler(Map<String, String> params) {
      String paramsStr = JSONUtil.toJsonStr(params);
      log.info("[支付宝]回调参数为：{}", paramsStr);
      AlipayNotifyVO notifyVO = (AlipayNotifyVO)JSONUtil.toBean(paramsStr, AlipayNotifyVO.class);
      Long tenantId = this.parseTenantIdInPassbackParams(notifyVO.getPassbackParams());
      Long canteenId = this.parseCanteenIdInPassbackParams(notifyVO.getPassbackParams());
      TenantContextHolder.setTenantId(tenantId);

      try {
         Long tradeId = Long.parseLong(notifyVO.getOutTradeNo());
         TradeChannel tradeRecord = this.tradeChannelService.getByTradeChannelId(tradeId);
         log.info("[支付宝]回调_查询交易记录_{}", JSON.toJSON(tradeRecord));
         if (ObjectUtil.isNull(tradeRecord)) {
            log.info("交易记录不存在：{}", tradeId);
            return null;
         }

         PayClient aliPayClient = this.getAliPayClient(canteenId, tradeRecord.getPayType());
         String charset = Optional.ofNullable((String)params.get("charset")).orElse("utf-8");
         boolean flag = AlipaySignature.rsaCheckV1(params, aliPayClient.getPublicKey(), charset, "RSA2");
         if (flag) {
            if (!aliPayClient.getAppId().equals(notifyVO.getAppId())) {
               log.info("回传appid不正确 appid：{}", notifyVO.getAppId());
               return null;
            }

            if (!AliPayTradeStatusEnum.TRADE_STATUS_SUCCESS.getKey().equals(notifyVO.getTradeStatus()) && !AliPayTradeStatusEnum.TRADE_STATUS_FINISHED.getKey().equals(notifyVO.getTradeStatus())) {
               log.info("支付未成功，支付状态：{}", notifyVO.getTradeStatus());
               return null;
            }

            MobileNotifyVO mobileNotifyVO = new MobileNotifyVO();
            if (PayStateEnum.PAY_SUCC.getKey().equals(tradeRecord.getTradeState())) {
               mobileNotifyVO.setPayState(PayStateEnum.PAY_FAIL.getKey());
               mobileNotifyVO.setTradeResult("已支付支付成功");
               return mobileNotifyVO;
            }

            BigDecimal payAmount = (new BigDecimal(notifyVO.getTotalAmount())).multiply(new BigDecimal(100)).setScale(0, 4);
            if (payAmount.compareTo(tradeRecord.getAmount()) != 0) {
               log.warn("[支付宝]回调_支付金额不正确 amount: {}, payAmount: {}", tradeRecord.getAmount(), payAmount);
            }

            mobileNotifyVO.setOutTradeNo(notifyVO.getTradeNo());
            mobileNotifyVO.setTradeChannelId(Long.parseLong(notifyVO.getOutTradeNo()));
            mobileNotifyVO.setPayState(PayStateEnum.PAY_SUCC.getKey());
            mobileNotifyVO.setTradeResult(PayStateEnum.PAY_SUCC.getDesc());
            mobileNotifyVO.setMerchantId(tenantId);
            return mobileNotifyVO;
         }
      } catch (AlipayApiException var13) {
         log.error("[支付宝]回调处理异常：", var13);
      }

      return null;
   }

   public OfflinePayVO offlinePay(AndroidPayDTO androidPayDTO) {
      OfflinePayVO offlinePayVO = new OfflinePayVO();
      if (PayTypeEnum.ALI_ENTERPRISE_WITHHOLD.getKey().equals(androidPayDTO.getPayType())) {
         log.info("[自助餐/线下企业码代扣]: " + androidPayDTO.getCustId());
         AlipayAPI.EnterpriseCodeAliParam param = AlipayAPI.EnterpriseCodeAliParam.builder().totalAmount(this.centConvertDollarToStr(androidPayDTO.getTotalAmount())).openId(androidPayDTO.getOpenid()).accountId(AliEnterpriseCodeUtil.findEnterpriseAccountId()).outTradeNo(String.valueOf(androidPayDTO.getTradeId())).alreadyPaid(this.centConvertDollarToStr(androidPayDTO.getTotalAmount().subtract(androidPayDTO.getAmount()))).terminalParams(androidPayDTO.getTerminalParams()).alipayContractNum(androidPayDTO.getAlipayContractNum()).canteenId(androidPayDTO.getCanteenId()).build();
         AlipayAPI.EnterpriseCodeResponse response = this.enterpriseCodeAliPay(param);
         offlinePayVO.setCode(response.getCode());
         offlinePayVO.setMsg(response.getMsg());
         log.info("[企业码]返回： " + String.valueOf(response));
         if (response.getCode().equals(PayStateEnum.PAY_SUCC.getKey())) {
            offlinePayVO.setOutTradeNo(response.getOutTradeNo());
            offlinePayVO.setTradeId(androidPayDTO.getTradeId());
            offlinePayVO.setRealAmount(androidPayDTO.getAmount());
            offlinePayVO.setAmount(androidPayDTO.getAmount());
         }

         return offlinePayVO;
      } else if (PayTypeEnum.ALI_PAY_WITHHOLD.getKey().equals(androidPayDTO.getPayType())) {
         log.info("[支付宝]代扣支付: " + String.valueOf(androidPayDTO));
         AlipayAPI.HoldingParam param = (AlipayAPI.HoldingParam)BeanUtil.copyProperties(androidPayDTO, AlipayAPI.HoldingParam.class, new String[0]);
         AlipayAPI.HoldingResponse response = this.holdingAliPay(param);
         offlinePayVO.setCode(response.getCode());
         offlinePayVO.setMsg(response.getMsg());
         offlinePayVO.setOutTradeNo(response.getOutTradeNo());
         offlinePayVO.setTradeId(androidPayDTO.getTradeId());
         offlinePayVO.setAmount(androidPayDTO.getAmount());
         if (response.getCode().equals(PayStateEnum.PAY_SUCC.getKey())) {
            offlinePayVO.setRealAmount(androidPayDTO.getAmount());
         }

         return offlinePayVO;
      } else {
         offlinePayVO.setCode(PayStateEnum.PAY_FAIL.getKey());
         offlinePayVO.setMsg(I18n.getMessage("pay.not-support-pay-type", new Object[0]));
         return offlinePayVO;
      }
   }

//   public BillDateQueryVO billDateQuery(BillDateQueryDTO billDateQueryDTO) {
//      try {
//         List<BillDetailVO> billDetailVOS = this.alipayServiceApi.aliDownloadBill(billDateQueryDTO.getDate(), billDateQueryDTO.getCanteenId());
//         return BillDateQueryVO.successOf(billDetailVOS);
//      } catch (Exception var3) {
//         log.error("支付宝账单查询异常", var3);
//         return BillDateQueryVO.fail(var3 instanceof ServiceException ? var3.getMessage() : "支付宝账单查询失败");
//      }
//   }

   public boolean payChannelSelect(PayChannelSelectEnum selectType, PayChannelSelectDTO payChannelSelectDTO, AllocPayModel canteenPayModel, AllocPayModel merchantPayModel, PayChannelSelectService payChannelSelectService, PayChannelSelectResultVO resultVO) {
      if (payChannelSelectDTO.ifEqualPayType(PayTypeEnum.ALI_FACE)) {
         if (resultVO.getCustPayVO() != null) {
            resultVO.addPayChannelSplit(PayTypeEnum.MEAL_CARD.getKey(), PayChannelEnum.ACC.getKey());
         } else {
            resultVO.removePayChannel(PayChannelEnum.ACC.getKey());
            resultVO.removeErrorInfoIfCode(LeRetCodeEnum.PAY_PERSONAL_NO_EXIT.getKey(), LeRetCodeEnum.CUST_PERSONAL_NO_EXIT.getKey());
         }

         resultVO.addPayChannelSplit(payChannelSelectDTO.getPayType(), PayChannelEnum.ALI.getKey());
      } else if (payChannelSelectDTO.ifEqualPayType(PayTypeEnum.MIXTURE_PAY_ALI_QRCODE, PayTypeEnum.MIXTURE_PAY_ALI_NATIVE)) {
         resultVO.addPayChannelSplit(PayTypeEnum.MEAL_CARD.getKey(), PayChannelEnum.ACC.getKey());
         Integer finalPayType = PayTypeEnum.MIXTURE_PAY_ALI_QRCODE.getKey().equals(payChannelSelectDTO.getPayType()) ? PayTypeEnum.ALI_QRCODE.getKey() : PayTypeEnum.ALI_NATIVE.getKey();
         resultVO.addPayChannelSplit(finalPayType, PayChannelEnum.ALI.getKey());
      } else if (payChannelSelectDTO.ifEqualPayType(PayTypeEnum.ALI_PAY_WITHHOLD)) {
         if ("1".equals(merchantPayModel.getIfOpenAlipayWithholdPayMix())) {
            resultVO.addPayChannelSplit(PayTypeEnum.MEAL_CARD.getKey(), PayChannelEnum.ACC.getKey());
         }

         this.fillAliContractNumIfNecessary(resultVO);
         resultVO.addPayChannelSplit(payChannelSelectDTO.getPayType(), PayChannelEnum.ALI.getKey());
      } else if (NuclearModeEnum.isQrCode(payChannelSelectDTO.getNuClearMode()) && LeCodeUtil.isAliPayCode(payChannelSelectDTO.getAuthCode())) {
         resultVO.addPayChannelSplit(PayTypeEnum.ALI_QRCODE.getKey(), PayChannelEnum.ALI.getKey());
      } else if ((PayChannelSelectEnum.MOBILE_CONSUME.equals(selectType) || PayChannelSelectEnum.MOBILE_RECHARGE.equals(selectType)) && payChannelSelectDTO.ifEqualPayType(PayTypeEnum.ALI_NATIVE, PayTypeEnum.ALI_APP_PAY, PayTypeEnum.ALI_SCAN, PayTypeEnum.ALI_H5_PAY)) {
         resultVO.addPayChannelSplit(payChannelSelectDTO.getPayType(), PayChannelEnum.ALI.getKey());
      } else if (PayChannelSelectEnum.DEVICE_RECHARGE.equals(selectType) && payChannelSelectDTO.ifEqualPayType(PayTypeEnum.ALI_QRCODE)) {
         resultVO.addPayChannelSplit(PayTypeEnum.ALI_QRCODE.getKey(), PayChannelEnum.ALI.getKey());
      }

      this.handleMixPay(payChannelSelectDTO, resultVO, merchantPayModel);
      this.handleAliEnterprise(selectType, payChannelSelectDTO, resultVO);
      if (resultVO.containsPayChannel(PayChannelEnum.ALI.getKey()) && !PayChannelSelectEnum.DEVICE_OFFLINE_CONSUME.equals(selectType)) {
         String startTimeStr = canteenPayModel.getAlipayRecConsumeLimitTimeStart();
         String endTimeStr = canteenPayModel.getAlipayRecConsumeLimitTimeEnd();
         if (!LeOrderUtil.checkNowTimeWithin(startTimeStr, endTimeStr)) {
            resultVO.setErrorInfo(LeRetCodeEnum.FAIL.getKey(), I18n.getMessage("pay.channel.out-of-time", new Object[]{startTimeStr, endTimeStr}));
         }
      }

      return true;
   }
//
//   protected AlipayAPI.EnterpriseCodeResponse enterpriseCodeFacePay(AndroidPayDTO androidPayDTO) {
//      AlipayTradePayRequest request = new AlipayTradePayRequest();
//      String appToken = this.allocMetadataApi.getMetadataValue(MetadataModelTypeEnum.MOBILE, "alipayAppAuthToken");
//      request.putOtherTextParam("app_auth_token", appToken);
//      JSONObject bizContent = new JSONObject();
//      bizContent.put("out_trade_no", androidPayDTO.getTradeId());
//      bizContent.put("total_amount", this.centConvertDollarToStr(androidPayDTO.getAmount()));
//      bizContent.put("product_code", "FACE_TO_FACE_PAYMENT");
//      if (PayTypeEnum.ALI_FACE.getKey().equals(androidPayDTO.getPayType())) {
//         bizContent.put("subject", "企业码扫脸付");
//         bizContent.put("scene", "security_code");
//         bizContent.put("terminal_params", androidPayDTO.getTerminalParams());
//      } else {
//         bizContent.put("subject", "企业码付款码支付");
//         bizContent.put("scene", "bar_code");
//      }
//
//      bizContent.put("auth_code", androidPayDTO.getAuthCode());
//      JSONObject businessParams = new JSONObject();
//      businessParams.put("assignJointAccountId", AliEnterpriseCodeUtil.findEnterpriseAccountId());
//      businessParams.put("identityPayBizInfo", this.getBizInfo(AliEnterpriseCodeUtil.findEnterpriseAccountId()));
//      businessParams.put("enterprise_pay_info", this.getEnterprisePayInfo());
//      bizContent.put("business_params", businessParams);
//      JSONObject extendParams = new JSONObject();
//      extendParams.put("pdSubBizScene", "enterprisePay");
//      extendParams.put("DYNAMIC_TOKEN_OUT_BIZ_NO", androidPayDTO.getAuthCode());
//      bizContent.put("extend_params", extendParams);
//      JSONArray queryOptions = new JSONArray();
//      queryOptions.add("enterprise_pay_info");
//      bizContent.put("query_options", queryOptions);
//      JSONObject payAssets = new JSONObject();
//      payAssets.put("assets_list", PAY_ASSETS);
//      bizContent.put("priority_pay_assets", payAssets);
//      request.setBizContent(bizContent.toString());
//      log.info("[企业码当面付]请求参数: " + String.valueOf(bizContent));
//
//      try {
//         this.payCustomAlipayBusiness.beforeEnterpriseCodeFacePay(request, androidPayDTO);
//         PayClient client = this.getAliPayClient(androidPayDTO.getCanteenId(), androidPayDTO.getPayType());
//         AlipayTradePayResponse response = (AlipayTradePayResponse)this.execute(client, request);
//         log.info("[支付宝]扫码支付返回结果：{}", response.getBody());
//         if (response.isSuccess()) {
//            if (AliPayTradeStatusEnum.REQUEST_CODE_SUCCESS.getKey().equals(response.getCode())) {
//               return AlipayAPI.EnterpriseCodeResponse.success();
//            }
//
//            if (!response.getCode().equals("10003") && !response.getCode().equals("20000")) {
//               return AlipayAPI.EnterpriseCodeResponse.fail(response.getMsg());
//            }
//
//            return AlipayAPI.EnterpriseCodeResponse.progress();
//         }
//      } catch (AlipayApiException var11) {
//         log.info("[支付宝]异常明细:", var11);
//         return AlipayAPI.EnterpriseCodeResponse.fail(var11.getMessage());
//      }
//
//      return AlipayAPI.EnterpriseCodeResponse.fail("");
//   }

   public AlipayAPI.EnterpriseCodeResponse enterpriseCodeAliPay(AlipayAPI.EnterpriseCodeAliParam param) {
      boolean zeroPayAmount = NumberUtil.toBigDecimal(param.getTotalAmount()).compareTo(NumberUtil.toBigDecimal(param.getAlreadyPaid())) == 0;
      if (!param.isAsync() && zeroPayAmount) {
         log.info("[支付宝]代扣支付金额为0，直接返回成功，异步上传支付结果：{}", param);
         PayMqSender.enterpriseCodePayAsync(param);
         return AlipayAPI.EnterpriseCodeResponse.success();
      } else {
         AlipayTradePayRequest request = new AlipayTradePayRequest();
         JSONObject bizContent = new JSONObject();
         bizContent.put("out_trade_no", param.getOutTradeNo());
         bizContent.put("total_amount", param.getTotalAmount());
         String appToken = this.allocMetadataApi.getMetadataValue(MetadataModelTypeEnum.MOBILE, "alipayAppAuthToken");
         request.putOtherTextParam("app_auth_token", appToken);
         bizContent.put("product_code", "GENERAL_WITHHOLDING");
         bizContent.put("subject", "企业码代扣");
         if (CharSequenceUtil.isNotBlank(param.getTerminalParams())) {
            bizContent.put("terminal_params", param.getTerminalParams());
         }

         JSONObject businessParams = new JSONObject();
         businessParams.put("assignJointAccountId", param.getAccountId());
         businessParams.put("enterprisePayAmount", param.getAlreadyPaid());
         businessParams.put("identityPayBizInfo", this.getBizInfo(param.getAccountId()));
         businessParams.put("enterprise_pay_info", this.getEnterprisePayInfo());
         bizContent.put("business_params", businessParams);
         JSONObject extendParams = new JSONObject();
         extendParams.put("pdSubBizScene", "enterprisePay");
         bizContent.put("extend_params", extendParams);
         JSONArray queryOptions = new JSONArray();
         queryOptions.add("enterprise_pay_info");
         bizContent.put("query_options", queryOptions);
         JSONObject agreement = new JSONObject();
         String alipayContractNum = this.queryAliContractNumIfNecessary(param.getAlipayContractNum(), param.getOpenId());
         if (StringUtils.isBlank(alipayContractNum)) {
            return AlipayAPI.EnterpriseCodeResponse.fail("当前人员未签约代扣协议");
         } else {
            agreement.put("agreement_no", alipayContractNum);
            bizContent.put("agreement_params", agreement);
            JSONObject payAssets = new JSONObject();
            payAssets.put("assets_list", PAY_ASSETS);
            bizContent.put("priority_pay_assets", payAssets);
            request.setBizContent(bizContent.toString());
            log.info("[企业码代扣]请求参数: " + String.valueOf(bizContent));
            PayClient client = this.getAliPayClient(param.getCanteenId(), PayTypeEnum.ALI_ENTERPRISE_WITHHOLD.getKey());

            try {
               this.payCustomAlipayBusiness.beforeEnterpriseCodePay(request, param, param.getCanteenId());
               AlipayTradePayResponse response = (AlipayTradePayResponse)this.execute(client, request);
               if (response.isSuccess()) {
                  if (AliPayTradeStatusEnum.REQUEST_CODE_SUCCESS.getKey().equals(response.getCode())) {
                     return AlipayAPI.EnterpriseCodeResponse.success();
                  }

                  if (!response.getCode().equals("10003") && !response.getCode().equals("20000")) {
                     return AlipayAPI.EnterpriseCodeResponse.fail("", param);
                  }

                  return AlipayAPI.EnterpriseCodeResponse.progress();
               }
            } catch (AlipayApiException var14) {
               log.info("[支付宝]代扣异常明细:", var14);
               return AlipayAPI.EnterpriseCodeResponse.progress();
            }

            return AlipayAPI.EnterpriseCodeResponse.fail("");
         }
      }
   }

   protected AlipayAPI.HoldingResponse holdingAliPay(AlipayAPI.HoldingParam param) {
      log.info("[支付宝代扣]请求参数：{}", JSONObject.toJSONString(param));
      AlipayAPI.HoldingResponse offlinePayVO = new AlipayAPI.HoldingResponse();
      offlinePayVO.setCode(PayStateEnum.PAY_FAIL.getKey());
      if (ObjectUtil.isEmpty(param.getCustId())) {
         log.info("[支付宝代扣]人员id不可为空");
         offlinePayVO.setMsg("人员id不可为空");
         return offlinePayVO;
      } else {
         String alipayContractNum = this.queryAliContractNumIfNecessary(param.getAlipayContractNum(), param.getOpenid());
         if (StringUtils.isBlank(alipayContractNum)) {
            log.info("[支付宝代扣]当前人员未签约代扣协议");
            offlinePayVO.setMsg("当前人员未签约代扣协议");
            return offlinePayVO;
         } else {
            String appToken = this.allocMetadataApi.getMetadataValue(MetadataModelTypeEnum.MOBILE, "alipayAppAuthToken");
            log.info("[支付宝]获取到配置信息：{}", appToken);
            if (StringUtils.isBlank(appToken)) {
               log.info("[支付宝]未找到当前应用配置信息");
               offlinePayVO.setMsg("配置信息读取错误！请检查配置信息");
               return offlinePayVO;
            } else {
               AlipayTradePayRequest alipayTradePayRequest = new AlipayTradePayRequest();
               alipayTradePayRequest.putOtherTextParam("app_auth_token", appToken);
               AlipayTradePayModel payModel = new AlipayTradePayModel();
               payModel.setOutTradeNo(param.getTradeId().toString());
               payModel.setTotalAmount(this.centConvertDollarToStr(param.getAmount()));
               payModel.setSubject(param.getCanteenName() + ": 消费");
               payModel.setBusinessParams(new BusinessParamsReq());
               payModel.setProductCode("GENERAL_WITHHOLDING");
               AgreementParams agreementParams = new AgreementParams();
               agreementParams.setAgreementNo(alipayContractNum);
               payModel.setAgreementParams(agreementParams);
               if (CharSequenceUtil.isAllNotEmpty(new CharSequence[]{param.getAuthCode(), param.getTerminalParams()})) {
                  payModel.setAuthCode(param.getAuthCode());
                  payModel.setTerminalParams(param.getTerminalParams());
                  ExtendParams extendParams = new ExtendParams();
                  extendParams.setSysServiceProviderId("2088621497354212");
                  payModel.setExtendParams(extendParams);
                  payModel.setScene("security_code");
                  payModel.setBusinessParams((new BusinessParamsReq()).setIot_pay_action("online_face_pay"));
               }

               alipayTradePayRequest.setBizModel(payModel);
               log.info("支付宝同步代扣请求参数:{}", JSON.toJSONString(alipayTradePayRequest));

               try {
                  this.payCustomAlipayBusiness.beforeHoldingPay(alipayTradePayRequest, param);
                  PayClient client = this.getAliPayClient(param.getCanteenId(), param.getPayType());
                  AlipayTradePayResponse response = (AlipayTradePayResponse)this.execute(client, alipayTradePayRequest);
                  log.info("支付宝同步代扣响应:{}", JSON.toJSONString(response));
                  if (response.isSuccess()) {
                     if (!AliPayTradeStatusEnum.BUSINESS_CODE_INPROCESS.getKey().equals(response.getCode()) && !AliPayTradeStatusEnum.BUSINESS_CODE_EXCEPTION.getKey().equals(response.getCode())) {
                        if (AliPayTradeStatusEnum.REQUEST_CODE_SUCCESS.getKey().equals(response.getCode())) {
                           offlinePayVO.setCode(PayStateEnum.PAY_SUCC.getKey());
                           offlinePayVO.setMsg(PayStateEnum.PAY_SUCC.getDesc());
                        } else {
                           offlinePayVO.setCode(PayStateEnum.PAY_FAIL.getKey());
                           offlinePayVO.setMsg(response.getSubMsg());
                        }
                     } else {
                        offlinePayVO.setCode(PayStateEnum.PAY_INPROCESS.getKey());
                        offlinePayVO.setMsg(PayStateEnum.PAY_INPROCESS.getDesc());
                     }

                     offlinePayVO.setOutTradeNo(response.getTradeNo());
                  } else {
                     Logger var10000 = log;
                     String var10001 = response.getMsg();
                     var10000.info("支付宝同步代扣失败，原因：" + var10001 + "，" + response.getSubMsg());
                     offlinePayVO.setMsg("支付宝代扣失败," + response.getSubMsg());
                  }
               } catch (AlipayApiException var10) {
                  log.info("[支付宝]代扣异常明细:", var10);
                  offlinePayVO.setMsg("支付宝代扣异常");
               }

               return offlinePayVO;
            }
         }
      }
   }
//
//   public AndroidPayVO faceToFaceAliPay(AndroidPayDTO androidPayDTO) {
//      log.info("[支付宝]扫码支付_上传参数：{}", JSONObject.toJSONString(androidPayDTO));
//      AlipayTradePayRequest payRequest = new AlipayTradePayRequest();
//      AlipayTradePayModel payModel = new AlipayTradePayModel();
//      payModel.setAuthCode(androidPayDTO.getAuthCode());
//      payModel.setOutTradeNo(String.valueOf(androidPayDTO.getTradeId()));
//      payModel.setTotalAmount(this.centConvertDollarToStr(androidPayDTO.getAmount()));
//      payModel.setSubject(androidPayDTO.isIfRecharge() ? "充值" : androidPayDTO.getCanteenName() + PayTypeEnum.ALI_QRCODE.getDesc() + ": 消费");
//      payModel.setScene("bar_code");
//      AndroidPayVO androidPayVO = new AndroidPayVO();
//      androidPayVO.setCode(PayStateEnum.PAY_FAIL.getKey());
//      androidPayVO.setMsg(PayStateEnum.PAY_FAIL.getDesc());
//      ExtendParams extendParams = new ExtendParams();
//      extendParams.setSysServiceProviderId("2088621497354212");
//      payModel.setExtendParams(extendParams);
//      if (PayTypeEnum.ALI_FACE.getKey().equals(androidPayDTO.getPayType())) {
//         payModel.setProductCode("FACE_TO_FACE_PAYMENT");
//         payModel.setScene("security_code");
//         payModel.setSubject("刷脸支付");
//         payModel.setSubject(PayTypeEnum.ALI_FACE.getDesc());
//         payModel.setTerminalParams(androidPayDTO.getTerminalParams());
//      }
//
//      payRequest.setBizModel(payModel);
//
//      try {
//         this.payCustomAlipayBusiness.beforeFacePay(payRequest, androidPayDTO);
//         PayClient client = this.getAliPayClient(androidPayDTO.getCanteenId(), androidPayDTO.getPayType());
//         AlipayTradePayResponse payResponse = (AlipayTradePayResponse)this.execute(client, payRequest);
//         log.info("[支付宝]扫码支付返回结果：{}", payResponse.getBody());
//         if (AliPayTradeStatusEnum.REQUEST_CODE_SUCCESS.getKey().equals(payResponse.getCode())) {
//            this.paySuccResultHandler(androidPayVO, androidPayDTO, payResponse.getTradeNo());
//         } else if (AliPayTradeStatusEnum.BUSINESS_CODE_INPROCESS.getKey().equals(payResponse.getCode())) {
//            androidPayVO.setCode(PayStateEnum.PAY_INPROCESS.getKey());
//            androidPayVO.setMsg(PayStateEnum.PAY_INPROCESS.getDesc());
//            androidPayVO.setOutTradeNo(payResponse.getTradeNo());
//         } else if (AliPayTradeStatusEnum.BUSINESS_CODE_FAIL.getKey().equals(payResponse.getCode()) && AliPayTradeStatusEnum.BUSINESS_STATUS_SUCCESS.getKey().equals(payResponse.getSubCode())) {
//            this.paySuccResultHandler(androidPayVO, androidPayDTO, payResponse.getTradeNo());
//         } else {
//            androidPayVO.setMsg(payResponse.getSubMsg());
//         }
//      } catch (AlipayApiException var8) {
//         log.error("[支付宝]扫码支付异常：", var8);
//         androidPayVO.setMsg("扫码支付异常");
//      }
//
//      androidPayVO.setPayChannel(PayChannelEnum.ALI.getKey());
//      return androidPayVO;
//   }

   private String getBizInfo(String groupId) {
      IdentityPayBizInfo bizInfo = new IdentityPayBizInfo();
      bizInfo.setGroupId(groupId);
      bizInfo.setBizGroupId(groupId);
      return JSON.toJSONString(bizInfo);
   }

   private String getEnterprisePayInfo() {
      EnterprisePayInfo payInfo = new EnterprisePayInfo();
      return JSON.toJSONString(payInfo);
   }

   private void appletPay(MobilePayDTO mobilePayDTO, MobilePayVO mobilePayVO) {
      PayClient client = this.getAliPayClient(mobilePayDTO.getCanteenId(), mobilePayDTO.getPayType());
      AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
      AlipayTradeCreateModel createModel = new AlipayTradeCreateModel();
      createModel.setOutTradeNo(mobilePayDTO.getTradeId().toString());
      createModel.setTotalAmount(this.centConvertDollarToStr(mobilePayDTO.getAmount()));
      createModel.setSubject(mobilePayDTO.isIfRecharge() ? "充值" : mobilePayDTO.getCanteenName() + PayTypeEnum.ALI_NATIVE.getDesc() + ": 消费");
      createModel.setPassbackParams(mobilePayDTO.getAttach());
      createModel.setBuyerId(mobilePayDTO.getOpenid());
      createModel.setProductCode("JSAPI_PAY");
      request.setNotifyUrl(this.queryUnifyNotifyHost() + notifyUrl);
      request.setBizModel(createModel);

      try {
         this.payCustomAlipayBusiness.beforeAppletPay(request, mobilePayDTO);
         AlipayTradeCreateResponse response = (AlipayTradeCreateResponse)this.execute(client, request);
         if (response.isSuccess()) {
            log.info("[支付宝]小程序支付,返回参数{}", response.getBody());
            mobilePayVO.setCode(PayStateEnum.PAY_SUCC.getKey());
            mobilePayVO.setMsg(PayStateEnum.PAY_SUCC.getDesc());
            mobilePayVO.setPayParamStr(response.getTradeNo());
            return;
         }

         mobilePayVO.setMsg(response.getSubMsg());
      } catch (AlipayApiException var7) {
         log.error("[支付宝]小程序支付,支付异常：", var7);
         mobilePayVO.setMsg("支付宝支付异常");
      }

   }

   private void appPay(MobilePayDTO mobilePayDTO, MobilePayVO mobilePayVO) {
      PayClient client = this.getAliPayClient(mobilePayDTO.getCanteenId(), mobilePayDTO.getPayType());
      AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
      AlipayTradeAppPayModel payModel = new AlipayTradeAppPayModel();
      payModel.setOutTradeNo(String.valueOf(mobilePayDTO.getTradeId()));
      payModel.setTotalAmount(this.centConvertDollarToStr(mobilePayDTO.getAmount()));
      payModel.setSubject(mobilePayDTO.isIfRecharge() ? "充值" : mobilePayDTO.getCanteenName() + PayTypeEnum.ALI_APP_PAY.getDesc() + ": 消费");
      payModel.setPassbackParams(mobilePayDTO.getAttach());
      payModel.setProductCode("QUICK_MSECURITY_PAY");
      request.setNotifyUrl(this.queryUnifyNotifyHost() + notifyUrl);
      request.setBizModel(payModel);

      try {
         this.payCustomAlipayBusiness.beforeAppPay(request, mobilePayDTO);
         AlipayTradeAppPayResponse response = (AlipayTradeAppPayResponse)this.sdkExecute(client, request);
         if (response.isSuccess()) {
            log.info("[支付宝]app支付,返回参数{}", response.getBody());
            mobilePayVO.setCode(PayStateEnum.PAY_SUCC.getKey());
            mobilePayVO.setMsg(PayStateEnum.PAY_SUCC.getDesc());
            mobilePayVO.setPayParamStr(response.getBody());
            return;
         }

         mobilePayVO.setMsg(response.getSubMsg());
      } catch (AlipayApiException var7) {
         log.error("[支付宝]app支付,支付异常：", var7);
         mobilePayVO.setMsg("支付宝支付异常");
      }

   }

   private void h5Pay(MobilePayDTO mobilePayDTO, MobilePayVO mobilePayVO) {
      PayClient client = this.getAliPayClient(mobilePayDTO.getCanteenId(), mobilePayDTO.getPayType());
      AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
      AlipayTradeWapPayModel createModel = new AlipayTradeWapPayModel();
      createModel.setOutTradeNo(mobilePayDTO.getTradeId().toString());
      createModel.setTotalAmount(this.centConvertDollarToStr(mobilePayDTO.getAmount()));
      createModel.setSubject(mobilePayDTO.isIfRecharge() ? "充值" : mobilePayDTO.getCanteenName() + PayTypeEnum.ALI_H5_PAY.getDesc() + ": 消费");
      createModel.setPassbackParams(mobilePayDTO.getAttach());
      createModel.setProductCode("QUICK_WAP_WAY");
      request.setNotifyUrl(this.queryUnifyNotifyHost() + notifyUrl);
      request.setBizModel(createModel);

      try {
         this.payCustomAlipayBusiness.beforeAppletPay(request, mobilePayDTO);
         AlipayTradeWapPayResponse response = (AlipayTradeWapPayResponse)this.pageExecute(client, request);
         if (response.isSuccess()) {
            log.info("[支付宝]h5支付,返回参数{}", response.getBody());
            mobilePayVO.setCode(PayStateEnum.PAY_SUCC.getKey());
            mobilePayVO.setMsg(PayStateEnum.PAY_SUCC.getDesc());
            mobilePayVO.setPayParamStr(response.getBody());
            return;
         }

         mobilePayVO.setMsg(response.getSubMsg());
      } catch (AlipayApiException var7) {
         log.error("[支付宝]h5支付,支付异常：", var7);
         mobilePayVO.setMsg("h5支付异常");
      }

   }

   private String queryUnifyNotifyHost() {
      return this.allocPayMetadataApi.queryUnifyNotifyHost();
   }

   private void paySuccResultHandler(AndroidPayVO androidPayVO, AndroidPayDTO androidPayDTO, String outTradeNo) {
      androidPayVO.setCode(PayStateEnum.PAY_SUCC.getKey());
      androidPayVO.setMsg(PayStateEnum.PAY_SUCC.getDesc());
      androidPayVO.setOutTradeNo(outTradeNo);
      androidPayVO.setTradeId(androidPayDTO.getTradeId());
      androidPayVO.setAmount(androidPayDTO.getAmount());
      androidPayVO.setRealAmount(androidPayDTO.getAmount());
   }

   private void refundSuccResultHandler(PayRefundVO payRefundVO, PayRefundDTO payRefundDTO, String outTradeNo) {
      payRefundVO.setCode(PayStateEnum.PAY_SUCC.getKey());
      payRefundVO.setMsg("退款成功");
      payRefundVO.setAmount(payRefundDTO.getAmount());
      payRefundVO.setRefundAmount(payRefundDTO.getRefundAmount());
      payRefundVO.setOutTradeNo(outTradeNo);
      payRefundVO.setTradeId(payRefundDTO.getRefundTradeId());
   }

   private String centConvertDollarToStr(BigDecimal amount) {
      return amount == null ? null : amount.divide(new BigDecimal(100), 2, 4).toPlainString();
   }
//
//   private BigDecimal dollarConvertCentBigDecimal(String dollarMoney) {
//      return dollarMoney == null ? null : (new BigDecimal(dollarMoney)).multiply(new BigDecimal(100)).setScale(0, 4);
//   }

   private void handleMixPay(PayChannelSelectDTO payChannelSelectDTO, PayChannelSelectResultVO resultVO, AllocPayModel merchantPayModel) {
      if ("1".equals(merchantPayModel.getIfOpenAlipayWithhold()) && "1".equals(merchantPayModel.getIfOpenAlipayWithholdPayMix()) && resultVO.getCustPayVO() != null && resultVO.containsPayChannel(PayChannelEnum.ACC.getKey()) && !resultVO.containsPayChannel(PayChannelEnum.ALI.getKey())) {
         CustCasual custCasual = this.custCasualApi.getCustCasualByCustIdAndSourceType(resultVO.getCustPayVO().getCustId(), SourceTypeEnum.ALI_LIFE_CODE.getKey());
         resultVO.setOpenId(custCasual == null ? null : custCasual.getOpenid());
         this.fillAliContractNumIfNecessary(resultVO);
         if (CharSequenceUtil.isNotBlank(resultVO.getAlipayContractNum())) {
            resultVO.addPayChannelSplit(PayTypeEnum.ALI_PAY_WITHHOLD.getKey(), PayChannelEnum.ALI.getKey());
         } else {
            log.warn("账户支付+支付宝代扣混合支付，未找到用户的代扣协议");
         }
      }

   }

   private void handleAliEnterprise(PayChannelSelectEnum selectType, PayChannelSelectDTO payChannelSelectDTO, PayChannelSelectResultVO resultVO) {
      if (!PayChannelSelectEnum.isRecharge(selectType.getKey())) {
         boolean ifUseAliEnterprise = "1".equals(this.allocMetadataApi.getMetadataValue(MetadataModelTypeEnum.PAY, "ifOpenAlipayEnterpriseCode"));
         boolean enterpriseCodeEnabled = AliEnterpriseCodeUtil.isEnterpriseCodeEnabled();
         log.info("企业是否开通企业码: {} 是否激活企业码: {}", ifUseAliEnterprise, enterpriseCodeEnabled);
         if (ifUseAliEnterprise && enterpriseCodeEnabled) {
            boolean isAliPayCode = LeCodeUtil.isAliPayCode(payChannelSelectDTO.getAuthCode());
            if (CharSequenceUtil.isBlank(payChannelSelectDTO.getOpenId()) && isAliPayCode) {
               payChannelSelectDTO.setOpenId(this.parseOpenIdFromAuthCode(payChannelSelectDTO.getAuthCode(), payChannelSelectDTO.getCanteenId()));
               resultVO.setOpenId(payChannelSelectDTO.getOpenId());
            }

            if (CharSequenceUtil.isNotBlank(payChannelSelectDTO.getOpenId()) && resultVO.getCustPayVO() == null) {
               this.channelBusiness.fillCustPayVO(payChannelSelectDTO, resultVO, false);
            }

            if (resultVO.getCustPayVO() == null) {
               log.warn("支付宝企业码支付时，未查询到人员信息，不处理企业码支付");
            } else {
               if (!isAliPayCode) {
                  CustCasual custCasual = this.custCasualApi.getCustCasualByCustIdAndSourceType(resultVO.getCustPayVO().getCustId(), SourceTypeEnum.ALI_LIFE_CODE.getKey());
                  resultVO.setOpenId(custCasual == null ? null : custCasual.getOpenid());
               }

               if (CharSequenceUtil.isBlank(resultVO.getOpenId())) {
                  log.warn("支付宝企业码支付时，未查询到人员关联的支付宝openId，不处理企业码支付");
               } else {
                  boolean isBusFaceMachine = SourceTypeEnum.ALI_BUS_FACE_MACHINE.getKey().equals(payChannelSelectDTO.getSourceType());
                  boolean joined = AliEnterpriseCodeUtil.isEmployeeJoined(resultVO.getOpenId());
                  if (joined) {
                     this.fillAliContractNumIfNecessary(resultVO);
                  }

                  log.info("用户openid: {} 是否班车刷脸: {} 是否已加入企业: {} 协议号: {}", new Object[]{resultVO.getOpenId(), isBusFaceMachine, joined, resultVO.getAlipayContractNum()});
                  if (joined && CharSequenceUtil.isNotBlank(resultVO.getAlipayContractNum())) {
                     if (isBusFaceMachine) {
                        resultVO.addPayChannelSplit(PayTypeEnum.ALI_ENTERPRISE_WITHHOLD.getKey(), PayChannelEnum.ALI.getKey());
                     } else if (resultVO.containsPayChannel(PayChannelEnum.ACC.getKey())) {
                        resultVO.addPayChannelSplit(PayTypeEnum.ALI_ENTERPRISE_WITHHOLD.getKey(), PayChannelEnum.ALI.getKey());
                     } else if (resultVO.containsPayType(PayTypeEnum.ALI_QRCODE.getKey())) {
                        resultVO.addPayChannelSplitFirst(PayTypeEnum.MEAL_CARD.getKey(), PayChannelEnum.ACC.getKey());
                        resultVO.addPayChannelSplit(PayTypeEnum.ALI_ENTERPRISE_QRCODE.getKey(), PayChannelEnum.ALI.getKey());
                     }
                  } else if (isBusFaceMachine) {
                     throw new ServiceException("人员并未加入到企业码里，不能使用班车.....");
                  }

               }
            }
         }
      }
   }

   protected Long parseTenantIdInPassbackParams(String passbackParams) {
      List<String> attachArr = StrUtil.split(passbackParams, "_");
      return Long.parseLong((String)attachArr.get(0));
   }

   protected Long parseCanteenIdInPassbackParams(String passbackParams) {
      List<String> attachArr = StrUtil.split(passbackParams, "_");
      return NumberUtil.isNumber((CharSequence)attachArr.get(1)) ? NumberUtil.parseLong((String)attachArr.get(1)) : null;
   }

   protected String queryAliContractNumIfNecessary(String alipayContractNum, String openId) {
      return CharSequenceUtil.isNotBlank(alipayContractNum) ? alipayContractNum : this.aliPayApi.userAgreementQuerySelect(openId);
   }

   protected void fillAliContractNumIfNecessary(PayChannelSelectResultVO resultVO) {
      if (!resultVO.isQueriedAliContractNum()) {
         if (CharSequenceUtil.isBlank(resultVO.getOpenId()) && resultVO.getCustPayVO() != null) {
            CustCasual custCasual = this.custCasualApi.getCustCasualByCustIdAndSourceType(resultVO
                    .getCustPayVO().getCustId(), SourceTypeEnum.ALI_LIFE_CODE.getKey());
            resultVO.setOpenId(custCasual == null ? null : custCasual.getOpenid());
         }

         if (CharSequenceUtil.isNotBlank(resultVO.getOpenId())) {
            String aliContractNum = this.aliPayApi.userAgreementQuerySelect(resultVO.getOpenId());
            resultVO.setAlipayContractNum(aliContractNum);
            resultVO.setQueriedAliContractNum(true);
         }

      }
   }

   private PayClient getAliPayClient(Long canteenId, Integer payType) {
      PayClientType payClientType = this.getPayClientType(payType);
      PayClient payClient;
      AlipayConfig clientParams;
      if (payClientType == PayClientType.ENTERPRISE_CODE) {
         clientParams = this.aliPayUtil.getClientParams();
         payClient = new PayClient(this.thirdApiUrlProperties.getApialipay(), clientParams.getAppId(), clientParams.getPrivateKey(), clientParams.getAlipayPublicKey());
         payClient.setAuthToken(this.allocMetadataApi.getMetadataValue(MetadataModelTypeEnum.PAY, "offLineAlipayAppAuthToken"));
      } else if (payClientType == PayClientType.HOLDING) {
         clientParams = this.aliPayUtil.getClientParams();
         payClient = new PayClient(this.thirdApiUrlProperties.getApialipay(), clientParams.getAppId(), clientParams.getPrivateKey(), clientParams.getAlipayPublicKey());
         payClient.setAuthToken(this.allocMetadataApi.getMetadataValue(MetadataModelTypeEnum.MOBILE, "alipayAppAuthToken"));
      } else {
         AllocPayModel allocPayModel;
         if (payClientType == PayClientType.ONLINE) {
            allocPayModel = this.allocMetadataApi.payApi().queryAvailablePayModel((Long)null);
            payClient = new PayClient(this.thirdApiUrlProperties.getApialipay(), allocPayModel.getAlipayAppletAppId(), allocPayModel.getOnlineAliAppPayPrivateKey(), allocPayModel.getOnlineAliPayPublicKey());
         } else {
            allocPayModel = this.allocMetadataApi.payApi().queryAvailablePayModel(canteenId);
            payClient = new PayClient(this.thirdApiUrlProperties.getApialipay(), allocPayModel.getAliPayAppId(), allocPayModel.getAliAppPayKsecret(), allocPayModel.getAliPayPublicKey());
         }
      }

      payClient.alipayClient = this.payCustomAlipayBusiness.didCreateClient(canteenId, payType, payClient.alipayClient);
      return payClient;
   }

   protected PayClientType getPayClientType(Integer payType) {
      boolean openEnterpriseCode = "1".equals(this.allocMetadataApi.getMetadataValue(MetadataModelTypeEnum.PAY, "ifOpenAlipayEnterpriseCode"));
      if (!PayTypeEnum.ALI_ENTERPRISE_QRCODE.getKey().equals(payType) && !PayTypeEnum.ALI_ENTERPRISE_WITHHOLD.getKey().equals(payType)) {
         if (PayTypeEnum.ALI_QRCODE.getKey().equals(payType) && openEnterpriseCode) {
            return PayClientType.DEVICE_QRCODE_DECODED;
         } else if (PayTypeEnum.ALI_PAY_WITHHOLD.getKey().equals(payType)) {
            return PayClientType.HOLDING;
         } else {
            return !PayTypeEnum.ALI_APP_PAY.getKey().equals(payType) && !PayTypeEnum.ALI_NATIVE.getKey().equals(payType) && !PayTypeEnum.ALI_SCAN.getKey().equals(payType) ? PayClientType.DEVICE : PayClientType.ONLINE;
         }
      } else {
         return PayClientType.ENTERPRISE_CODE;
      }
   }

   protected <T extends AlipayResponse> T execute(PayClient payClient, AlipayRequest<T> request) throws AlipayApiException {
      T customRsp = this.payCustomAlipayBusiness.willExecute(payClient, request, false);
      return customRsp != null ? customRsp : payClient.execute(request);
   }

   protected <T extends AlipayResponse> T sdkExecute(PayClient payClient, AlipayRequest<T> request) throws AlipayApiException {
      T customRsp = this.payCustomAlipayBusiness.willExecute(payClient, request, true);
      return customRsp != null ? customRsp : payClient.sdkExecute(request);
   }

   protected <T extends AlipayResponse> T pageExecute(PayClient payClient, AlipayRequest<T> request) throws AlipayApiException {
      T customRsp = this.payCustomAlipayBusiness.willExecute(payClient, request, true);
      return customRsp != null ? customRsp : payClient.pageExecute(request);
   }

   public static class PayClient {
      private AlipayClient alipayClient;
      private String url;
      private String appId;
      private String privateKey;
      private String publicKey;
      private String authToken;

      public PayClient(String url, String appId, String privateKey, String publicKey) {
         this.url = url;
         this.appId = appId;
         this.privateKey = privateKey;
         this.publicKey = publicKey;
         this.createClient();
      }

      public void createClient() {
         this.alipayClient = new DefaultAlipayClient(this.url, this.appId, this.privateKey, "json", "UTF-8", this.publicKey, "RSA2");
      }

      public <T extends AlipayResponse> T execute(AlipayRequest<T> request) throws AlipayApiException {
         return this.alipayClient.execute(request, (String)null, CharSequenceUtil.isNotBlank(this.authToken) ? this.authToken : null);
      }

      public <T extends AlipayResponse> T sdkExecute(AlipayRequest<T> request) throws AlipayApiException {
         return this.alipayClient.sdkExecute(request);
      }

      public <T extends AlipayResponse> T pageExecute(AlipayRequest<T> request) throws AlipayApiException {
         return this.alipayClient.pageExecute(request);
      }

      public AlipayClient getAlipayClient() {
         return this.alipayClient;
      }

      public String getUrl() {
         return this.url;
      }

      public String getAppId() {
         return this.appId;
      }

      public String getPrivateKey() {
         return this.privateKey;
      }

      public String getPublicKey() {
         return this.publicKey;
      }

      public String getAuthToken() {
         return this.authToken;
      }

      public void setAlipayClient(final AlipayClient alipayClient) {
         this.alipayClient = alipayClient;
      }

      public void setUrl(final String url) {
         this.url = url;
      }

      public void setAppId(final String appId) {
         this.appId = appId;
      }

      public void setPrivateKey(final String privateKey) {
         this.privateKey = privateKey;
      }

      public void setPublicKey(final String publicKey) {
         this.publicKey = publicKey;
      }

      public void setAuthToken(final String authToken) {
         this.authToken = authToken;
      }
   }

   private static class IdentityPayBizInfo {
      private String identityPayBizScene = "ENTERPRISE_CODE";
      private String identityPaySubBizScene = "ISV_PAY";
      private String groupId;
      private String bizGroupId;

      public IdentityPayBizInfo() {
      }

      public String getIdentityPayBizScene() {
         return this.identityPayBizScene;
      }

      public String getIdentityPaySubBizScene() {
         return this.identityPaySubBizScene;
      }

      public String getGroupId() {
         return this.groupId;
      }

      public String getBizGroupId() {
         return this.bizGroupId;
      }

      public void setIdentityPayBizScene(final String identityPayBizScene) {
         this.identityPayBizScene = identityPayBizScene;
      }

      public void setIdentityPaySubBizScene(final String identityPaySubBizScene) {
         this.identityPaySubBizScene = identityPaySubBizScene;
      }

      public void setGroupId(final String groupId) {
         this.groupId = groupId;
      }

      public void setBizGroupId(final String bizGroupId) {
         this.bizGroupId = bizGroupId;
      }

   }

   private static class EnterprisePayInfo {
      private String solutionName = "CARD_PAY";
      private String solutionScene = "GROUP_MEAL";

      public EnterprisePayInfo() {
      }

      public String getSolutionName() {
         return this.solutionName;
      }

      public String getSolutionScene() {
         return this.solutionScene;
      }

      public void setSolutionName(final String solutionName) {
         this.solutionName = solutionName;
      }

      public void setSolutionScene(final String solutionScene) {
         this.solutionScene = solutionScene;
      }
   }

   private static enum PayClientType {
      DEVICE,
      DEVICE_QRCODE_DECODED,
      ONLINE,
      ENTERPRISE_CODE,
      HOLDING;

      // $FF: synthetic method
      private static PayClientType[] $values() {
         return new PayClientType[]{DEVICE, DEVICE_QRCODE_DECODED, ONLINE, ENTERPRISE_CODE, HOLDING};
      }
   }

   private static class PayAsset {
      private String asset_name = "enterprisePay";

      public PayAsset() {
      }

      public String getAsset_name() {
         return this.asset_name;
      }

      public void setAsset_name(final String asset_name) {
         this.asset_name = asset_name;
      }
   }
}
