@Override
 public boolean signUp(Device device) throws TransferFailedException {
   boolean isSignUpSuccess = false;
   CupsTrmnl cupsTrmnl = cupsTrmnlService.findById(device.getBindTransId());
   if (cupsTrmnl == null) {
     throw new TransferFailedException(
         AppExCode.TERMINAL_NOT_EXIST, "goodee signup failed,not find CupsTrmnl");
   }
   PaySignUp paySignUp =
       paySignUpService.findPaySignUpByMrchNoAndTrmnlNo(
           cupsTrmnl.getMrchNo(), cupsTrmnl.getTrmnlNo());
   if (paySignUp != null) {
     if (StringUtils.isNotBlank(paySignUp.getRespCode())
         && Const.ISO_RESPCODE_OK.equals(paySignUp.getRespCode())) {
       long workingKeyTimeout = paySignUp.getUpdTime().getTime() + Const.WORKING_KEY_TIMEOUT;
       long nowTime = (new Date()).getTime();
       if (workingKeyTimeout > nowTime) {
         isSignUpSuccess = true;
       }
     }
   }
   if (!isSignUpSuccess) {
     signUpProcess.process(cupsTrmnl);
     isSignUpSuccess = true;
   }
   return isSignUpSuccess;
 }
  @Override
  public boolean icScriptUpload(ICScriptUploadRequest request) {
    boolean isIcScriptUloadSuccess = false;
    List<ICScript> lists = request.getIcScripts();
    for (ICScript temp : lists) {
      if (temp == null) {
        continue;
      }
      // 获取原始交易信息
      String originalPayNo = temp.getTransRefNo();
      if (StringUtils.isEmpty(originalPayNo)) {
        throw new TransferFailedException(
            AppExCode.ILLEGAL_PARAMS,
            "goodee isScript upload failed! not find original payNo[" + originalPayNo + "]");
      }
      PayCups originalPayCups = payCupsService.findPayCups(originalPayNo);
      if (originalPayCups == null) {
        throw new TransferFailedException(
            AppExCode.TRANS_NOT_EXIST,
            "goodee isScript upload failed! not find original payNo[" + originalPayNo + "]");
      }
      int transTypeInt = originalPayCups.getTransType();
      if (!(TransType.CONSUME.getOrdinal() == transTypeInt
          || TransType.BALANCE.getOrdinal() == transTypeInt)) {
        throw new TransferFailedException(
            AppExCode.NOT_SUPPORTED_OPERATION,
            getDescription()
                + " channel not support icsSriptUpload["
                + transTypeInt
                + "] operation");
      }
      CupsTrmnl cupsTrmnl =
          cupsTrmnlService.findByTrmnlNoAndMrchNo(
              originalPayCups.getTrmnlNo(), originalPayCups.getTrmnlMrchNo());
      PaySignUp paySignUp =
          paySignUpService.findPaySignUpByMrchNoAndTrmnlNo(
              originalPayCups.getTrmnlMrchNo(), originalPayCups.getTrmnlNo());
      CupsKeyManage cupsKeyManage = new CupsKeyManage();
      cupsKeyManage.setTrmnlMacKey(paySignUp.getTrmnlMacKey());
      // 保存二次授权数据
      JSONObject json = JSONObject.fromObject(temp);
      originalPayCups.setIcScriptRlst(json.toString());
      originalPayCups = payCupsService.updatePayCups(originalPayCups);

      // 如果二次授权失败,则发起冲正交易,成功则保存二次授权数据,并且如果有脚本则上送脚本交易
      if (temp.getSecondAuthRlst() != null && temp.getSecondAuthRlst() == false) {
        // reversalProcess.process(cupsTrmnl, originalPayCups);
      } else {
        if (StringUtils.isNotEmpty(temp.getScriptExecuteRslt())) {
          CupsRequestInfo requestInfo = new CupsRequestInfo();
          requestInfo.setOriginalPayNo(temp.getTransRefNo());
          requestInfo.setIcScript(temp);
          try {
            icScriptUploadProcess.process(cupsTrmnl, cupsKeyManage, requestInfo);
          } catch (TransferFailedException e) {
            throw e;
          }
        }
      }
    }
    isIcScriptUloadSuccess = true;
    return isIcScriptUloadSuccess;
  }
  @Override
  public CardInfo balance(Device device, BalanceRequest request) throws TransferFailedException {
    logger.info("entryMode:" + request.getEntryMode());
    logger.info("Pinblock is not null:" + StringUtils.isNotBlank(request.getPinblock()));
    logger.info("EmvTransInfo is not null:" + StringUtils.isNotBlank(request.getEmvTransInfo()));

    // 校验数据
    if (StringUtils.isBlank(request.getCardNo())) {
      throw new TransferFailedException(
          AppExCode.ILLEGAL_PARAMS, "goodee balance failed,cardNo null");
    }
    if (StringUtils.isBlank(request.getTrack2Data())
        && StringUtils.isBlank(request.getTrackData())) {
      throw new TransferFailedException(
          AppExCode.ILLEGAL_PARAMS, "goodee banlance failed,track2data or trackData null");
    }
    // 卡输入方式
    if (StringUtils.isNotBlank(request.getEntryMode())) {
      boolean isOk =
          isEntryModeOk(request.getEntryMode(), request.getPinblock(), request.getEmvTransInfo());
      if (!isOk) {
        throw new TransferFailedException(
            AppExCode.ILLEGAL_PARAMS,
            "goodee balance failed,entryMode is "
                + request.getEntryMode()
                + " but pinBlock is not null:"
                + StringUtils.isNotBlank(request.getPinblock())
                + " ,emvTransInfo is not null:"
                + StringUtils.isNotBlank(request.getEmvTransInfo()));
      }
    }
    // 获取当前设备的终端信息
    CupsTrmnl cupsTrmnl = cupsTrmnlService.findById(device.getBindTransId());
    if (cupsTrmnl == null) {
      throw new TransferFailedException(
          AppExCode.TERMINAL_NOT_EXIST, "goodee banlance failed,not find CupsTrmnl");
    }
    // 获取密钥信息
    DeviceKeymanage deviceKeymanage =
        deviceKeymanageService.findDeviceKeymanageByDevId(device.getDevId());
    if (deviceKeymanage == null) {
      throw new TransferFailedException(
          AppExCode.DEVICE_KEY_NOT_EXIST, "goodee balance failed,not find deviceKeymanage info");
    }
    PaySignUp paySignUp =
        paySignUpService.findPaySignUpByMrchNoAndTrmnlNo(
            cupsTrmnl.getMrchNo(), cupsTrmnl.getTrmnlNo());
    if (paySignUp == null) {
      throw new TransferFailedException(
          AppExCode.TERMINAL_KEY_NOT_EXIST, "goodee pay failed,not find cups signUp info");
    }
    // 密钥体系转换
    CupsKeyManage cupsKeyManage = new CupsKeyManage();
    cupsKeyManage.setDevPinKey(deviceKeymanage.getPinkey());
    cupsKeyManage.setTrmnlPinKey(paySignUp.getTrmnlPinKey());
    cupsKeyManage.setTrmnlMacKey(paySignUp.getTrmnlMacKey());
    // CUPS请求信息
    CupsRequestInfo requestInfo = new CupsRequestInfo();
    requestInfo.setPinblock(request.getPinblock());
    requestInfo.setEmvTransInfo(request.getEmvTransInfo());
    requestInfo.setCardSeqNum(request.getCardSeqNum());
    requestInfo.setCurrency(request.getCurrency().getCodeN());
    try {
      TrackContext trackContext =
          getTrackData(deviceKeymanage.getDatakey(), request.getTrackData());
      requestInfo.setCardNo(trackContext.getTrack2Data().split("=")[0]);
      requestInfo.setTrack2Data(trackContext.getTrack2Data());
      requestInfo.setTrack3Data(trackContext.getTrack3Data());
    } catch (HSMException e) {
      String hsmRespCode = XPOSPClientUtils.getCode(e);
      if (!AppExCode.UNKNOWN.equals(hsmRespCode)) {
        hsmRespCode = Const.TP_BEGIN_HSM + hsmRespCode;
      }
      throw new TransferFailedException(
          hsmRespCode,
          "goodee balance failed, when descrypt track data form hsm error code["
              + hsmRespCode
              + "]");
    }
    CupsResponseInfo cupsResponseInfo = new CupsResponseInfo();
    try {
      cupsResponseInfo = balanceProcess.process(cupsTrmnl, cupsKeyManage, requestInfo);
    } catch (TransferFailedException e) {
      String errorCode = XPOSPClientUtils.getCode(e);
      processErrorCode(errorCode, cupsTrmnl);
      throw e;
    }
    CardInfo cardInfo = new CardInfo();
    cardInfo.setTransRefNo(cupsResponseInfo.getPayNo());
    cardInfo.setTransCode(cupsResponseInfo.getTransCode());
    cardInfo.setCardNo(request.getCardNo()); // 返回的卡号需带有掩码
    cardInfo.setBalance(cupsResponseInfo.getBalance());
    cardInfo.setEmvTransInfo(cupsResponseInfo.getEmvTransInfo());
    return cardInfo;
  }
  @Override
  public void refund(Device device, PayRefund refund, RefundRequest request)
      throws TransferFailedException {
    logger.info("entryMode:" + request.getEntryMode());
    logger.info("Pinblock is not null:" + StringUtils.isNotBlank(request.getPinblock()));
    logger.info("EmvTransInfo is not null:" + StringUtils.isNotBlank(request.getEmvTransInfo()));

    // 校验数据
    if (StringUtils.isBlank(request.getTrack2Data())
        && StringUtils.isBlank(request.getTrackData())) {
      throw new TransferFailedException(
          AppExCode.ILLEGAL_PARAMS, "goodee refund failed,track2data or trackData null");
    }
    // 卡输入方式
    if (StringUtils.isNotBlank(request.getEntryMode())) {
      boolean isOk =
          isEntryModeOk(request.getEntryMode(), request.getPinblock(), request.getEmvTransInfo());
      if (!isOk) {
        throw new TransferFailedException(
            AppExCode.ILLEGAL_PARAMS,
            "goodee refund failed,entryMode is "
                + request.getEntryMode()
                + " but pinBlock is not null:"
                + StringUtils.isNotBlank(request.getPinblock())
                + " ,emvTransInfo is not null:"
                + StringUtils.isNotBlank(request.getEmvTransInfo()));
      }
    }
    // modify by zengyj 20140331 cancel by orginal trmnl not by device trmnl;
    // 获取当前设备的终端信息
    PayCups originalPayCups = payCupsService.findPayCups(request.getLastTransRefNo());
    if (originalPayCups == null) {
      throw new TransferFailedException(
          AppExCode.TRANS_NOT_EXIST, "goodee refund failed,not find originalPayCups");
    }
    CupsTrmnl cupsTrmnl =
        cupsTrmnlService.findByTrmnlNoAndMrchNo(
            originalPayCups.getTrmnlNo(), originalPayCups.getTrmnlMrchNo());
    if (cupsTrmnl == null) {
      throw new TransferFailedException(
          AppExCode.TERMINAL_NOT_EXIST, "goodee refund failed,not find CupsTrmnl");
    }
    // 获取密钥信息
    DeviceKeymanage deviceKeymanage =
        deviceKeymanageService.findDeviceKeymanageByDevId(device.getDevId());
    if (deviceKeymanage == null) {
      throw new TransferFailedException(
          AppExCode.DEVICE_KEY_NOT_EXIST, "goodee refund failed,not find deviceKeymanage info");
    }
    PaySignUp paySignUp =
        paySignUpService.findPaySignUpByMrchNoAndTrmnlNo(
            cupsTrmnl.getMrchNo(), cupsTrmnl.getTrmnlNo());
    if (paySignUp == null) {
      throw new TransferFailedException(
          AppExCode.TERMINAL_KEY_NOT_EXIST, "goodee refund failed,not find cups signUp info");
    }
    // 密钥体系转换
    CupsKeyManage cupsKeyManage = new CupsKeyManage();
    cupsKeyManage.setDevPinKey(deviceKeymanage.getPinkey());
    cupsKeyManage.setTrmnlPinKey(paySignUp.getTrmnlPinKey());
    cupsKeyManage.setTrmnlMacKey(paySignUp.getTrmnlMacKey());
    // CUPS请求信息
    CupsRequestInfo requestInfo = new CupsRequestInfo();
    requestInfo.setPayNo(refund.getPayrefundNo());
    requestInfo.setAmount(refund.getPayAmt());
    requestInfo.setOriginalPayNo(request.getLastTransRefNo());
    requestInfo.setPinblock(request.getPinblock());
    requestInfo.setEmvTransInfo(request.getEmvTransInfo());
    requestInfo.setCardSeqNum(request.getCardSeqNum());
    requestInfo.setExtFld01(request.getStoreNo());
    requestInfo.setOrderNo(request.getOrderNo());
    try {
      TrackContext trackContext =
          getTrackData(deviceKeymanage.getDatakey(), request.getTrackData());
      requestInfo.setCardNo(trackContext.getTrack2Data().split("=")[0]);
      requestInfo.setTrack2Data(trackContext.getTrack2Data());
      requestInfo.setTrack3Data(trackContext.getTrack3Data());
    } catch (HSMException e) {
      String hsmRespCode = XPOSPClientUtils.getCode(e);
      if (!AppExCode.UNKNOWN.equals(hsmRespCode)) {
        hsmRespCode = Const.TP_BEGIN_HSM + hsmRespCode;
      }
      throw new TransferFailedException(
          hsmRespCode,
          "goodee refund failed, when descrypt track data form hsm error code["
              + hsmRespCode
              + "]");
    }
    try {
      refundProcess.process(
          cupsTrmnl, cupsKeyManage, requestInfo, getAddress(refund.getAppAccessId()));
    } catch (TransferFailedException e) {
      String errorCode = XPOSPClientUtils.getCode(e);
      processErrorCode(errorCode, cupsTrmnl);
      throw e;
    }
    // 如果没有抛异常,则交易成功
    refund.setTransStatus(Const.TransStatus.SUCCESS);
  }
  @Override
  public void cashLoad(Device device, PayCashLoad cashLoad, CashLoadRequest request)
      throws TransferFailedException {
    logger.info("entryMode:" + request.getEntryMode());
    logger.info("Pinblock is not null:" + StringUtils.isNotBlank(request.getPinblock()));
    logger.info("EmvTransInfo is not null:" + StringUtils.isNotBlank(request.getEmvTransInfo()));

    // 校验数据
    if (StringUtils.isBlank(request.getCardNo())) {
      throw new TransferFailedException(AppExCode.ILLEGAL_PARAMS, "cash Load failed,cardNo null");
    }
    if (StringUtils.isBlank(request.getTrackData())) {
      throw new TransferFailedException(
          AppExCode.ILLEGAL_PARAMS, "cash Load failed,track2data or trackData null");
    }
    // 卡输入方式
    if (StringUtils.isNotBlank(request.getEntryMode())) {
      boolean isOk =
          isEntryModeOk(request.getEntryMode(), request.getPinblock(), request.getEmvTransInfo());
      if (!isOk) {
        throw new TransferFailedException(
            AppExCode.ILLEGAL_PARAMS,
            "cash PayCupsTransferChannel failed,entryMode is "
                + request.getEntryMode()
                + " but pinBlock is not null:"
                + StringUtils.isNotBlank(request.getPinblock())
                + " ,emvTransInfo is not null:"
                + StringUtils.isNotBlank(request.getEmvTransInfo()));
      }
    }
    // 获取当前设备的终端信息
    // CupsTrmnl cupsTrmnl = cupsTrmnlService.findById(device.getBindTransId());
    String trmnlNo = XpospSysProperty.getUlinkPlusQmf3TrmnlNo();
    String mrchNo = XpospSysProperty.getUlinkPlusQmf3MrchNo();
    logger.info("电子现金圈存交易 发到渠道的商户号[" + mrchNo + "],终端号[" + trmnlNo + "]");
    CupsTrmnl cupsTrmnl = cupsTrmnlService.findByTrmnlNoAndMrchNo(trmnlNo, mrchNo);
    if (cupsTrmnl == null) {
      throw new TransferFailedException(
          AppExCode.TERMINAL_NOT_EXIST, "cash Load failed,not find CupsTrmnl");
    }
    // 获取密钥信息
    DeviceKeymanage deviceKeymanage =
        deviceKeymanageService.findDeviceKeymanageByDevId(device.getDevId());
    if (deviceKeymanage == null) {
      throw new TransferFailedException(
          AppExCode.DEVICE_KEY_NOT_EXIST, "cash Load failed,not find deviceKeymanage info");
    }
    PaySignUp paySignUp =
        paySignUpService.findPaySignUpByMrchNoAndTrmnlNo(
            cupsTrmnl.getMrchNo(), cupsTrmnl.getTrmnlNo());
    if (paySignUp == null) {
      throw new TransferFailedException(
          AppExCode.TERMINAL_KEY_NOT_EXIST, "cash Load failed,not find cups signUp info");
    }
    // 密钥体系转换
    CupsKeyManage cupsKeyManage = new CupsKeyManage();
    cupsKeyManage.setDevPinKey(deviceKeymanage.getPinkey());
    cupsKeyManage.setTrmnlPinKey(paySignUp.getTrmnlPinKey());
    cupsKeyManage.setTrmnlMacKey(paySignUp.getTrmnlMacKey());
    // CUPS请求信息
    CupsRequestInfo requestInfo = new CupsRequestInfo();
    requestInfo.setPayNo(cashLoad.getCashLoadNo());
    requestInfo.setAmount(request.getAmount());
    requestInfo.setPinblock(request.getPinblock());
    requestInfo.setEmvTransInfo(request.getEmvTransInfo());
    requestInfo.setCardSeqNum(request.getCardSeqNum());
    requestInfo.setCurrency(request.getCurrency().getCodeN());
    requestInfo.setExtFld01(request.getStoreNo());
    requestInfo.setOrderNo(request.getOrderNo());
    try {
      TrackContext trackContext =
          getTrackData(deviceKeymanage.getDatakey(), request.getTrackData());

      requestInfo.setCardNo(trackContext.getTrack2Data().split("=")[0]);
      requestInfo.setTrack2Data(trackContext.getTrack2Data());
      requestInfo.setTrack3Data(trackContext.getTrack3Data());
    } catch (HSMException e) {
      String hsmRespCode = XPOSPClientUtils.getCode(e);
      if (!AppExCode.UNKNOWN.equals(hsmRespCode)) {
        hsmRespCode = Const.TP_BEGIN_HSM + hsmRespCode;
      }
      throw new TransferFailedException(
          hsmRespCode,
          "cash Load failed, when descrypt track data form hsm error code[" + hsmRespCode + "]");
    }

    CupsResponseInfo responseInfo = null;
    try {
      // 构建发起金融交易
      responseInfo = cashLoadProcess.process(cupsTrmnl, cupsKeyManage, requestInfo);
    } catch (TransferFailedException e) {
      String errorCode = XPOSPClientUtils.getCode(e);
      processErrorCode(errorCode, cupsTrmnl);
      throw e;
    }

    // 如果没有抛异常,则交易成功
    cashLoad.setTransStatus(Const.TransStatus.SUCCESS);
    cashLoad.setTransCode(responseInfo.getTransCode());
    cashLoad.setEmvTransInfo(responseInfo.getEmvTransInfo());
  }
  @Override
  public void cashPay(final Device device, final Payment payment, final PaymentRequest request)
      throws TransferFailedException {
    logger.info("entryMode:" + request.getEntryMode());
    logger.info("EmvTransInfo is not null :" + StringUtils.isNotBlank(request.getEmvTransInfo()));

    // 校验数据
    if (StringUtils.isBlank(request.getCardNo())) {
      throw new TransferFailedException(AppExCode.ILLEGAL_PARAMS, "pay failed ,cardNo null");
    }
    // 卡输入方式
    //		if(StringUtils.isNotBlank(request.getEntryMode())){
    //			boolean isOk=isEntryModeOk(request.getEntryMode(),request.getPinblock(),
    // request.getEmvTransInfo());
    //		   if(!isOk){
    //			   throw new TransferFailedException(AppExCode.ILLEGAL_PARAMS, "pay failed,entryMode is
    // "+request.getEntryMode()+" but pinBlock is not
    // null:"+StringUtils.isNotBlank(request.getPinblock())+" ,emvTransInfo is not
    // null:"+StringUtils.isNotBlank(request.getEmvTransInfo()));
    //		   }
    //		}
    // 非接交易时候,55域的tag“9F74”必须出现
    if (StringUtils.isBlank(request.getEmvTransInfo())) {
      throw new TransferFailedException(
          AppExCode.ILLEGAL_PARAMS, "pay failed,emvTransInfo is" + request.getEmvTransInfo());
    }

    // 获取当前设备的终端信息
    CupsTrmnl cupsTrmnl = cupsTrmnlService.findById(device.getBindTransId());
    if (cupsTrmnl == null) {
      throw new TransferFailedException(
          AppExCode.TERMINAL_NOT_EXIST, "pay failed,not find CupsTrmnl");
    }
    // 获取密钥信息
    DeviceKeymanage deviceKeymanage =
        deviceKeymanageService.findDeviceKeymanageByDevId(device.getDevId());
    if (deviceKeymanage == null) {
      throw new TransferFailedException(
          AppExCode.DEVICE_KEY_NOT_EXIST, "pay failed,not find deviceKeymanage info");
    }

    PaySignUp paySignUp =
        paySignUpService.findPaySignUpByMrchNoAndTrmnlNo(
            cupsTrmnl.getMrchNo(), cupsTrmnl.getTrmnlNo());
    if (paySignUp == null) {
      throw new TransferFailedException(
          AppExCode.TERMINAL_KEY_NOT_EXIST, "pay failed,not find cups signUp info");
    }

    // 当定时签到失败的时候,需要重新发起到银联签到
    // 密钥体系转换
    CupsKeyManage cupsKeyManage = new CupsKeyManage();
    cupsKeyManage.setDevPinKey(deviceKeymanage.getPinkey());
    cupsKeyManage.setTrmnlPinKey(paySignUp.getTrmnlPinKey());
    cupsKeyManage.setTrmnlMacKey(paySignUp.getTrmnlMacKey());
    // CUPS请求信息
    CupsRequestInfo requestInfo = new CupsRequestInfo();
    requestInfo.setPayNo(payment.getPayNo());
    requestInfo.setAmount(request.getAmount());
    requestInfo.setPinblock(request.getPinblock());
    requestInfo.setEmvTransInfo(request.getEmvTransInfo());
    requestInfo.setCardSeqNum(request.getCardSeqNum());
    requestInfo.setEntryMode(request.getEntryMode());
    requestInfo.setCurrency(request.getCurrency().getCodeN());
    requestInfo.setExtFld01(request.getStoreNo());
    requestInfo.setCardNo(request.getCardNo());
    requestInfo.setCardExpiryDay(request.getCardExpire());
    requestInfo.setOrderNo(request.getOrderNo());
    requestInfo.setIcScript(request.getIcScript());
    CupsResponseInfo responseInfo = null;
    try {
      responseInfo = cashConsumeProcess.process(cupsTrmnl, cupsKeyManage, requestInfo);
    } catch (TransferFailedException e) {
      String errorCode = XPOSPClientUtils.getCode(e);
      processErrorCode(errorCode, cupsTrmnl);
      throw e;
    }
    // 如果没有抛异常,则交易成功
    payment.setTransStatus(Const.TransStatus.SUCCESS);
    payment.setTransCode(responseInfo.getTransCode());
    payment.setEmvTransInfo(responseInfo.getEmvTransInfo());
  }