@Override
  @Transactional(rollbackFor = Exception.class)
  public void payForCompensation(RepayCompensation rc) throws InsufficientBalance {
    // FIXME:判断rc的状态,防止多次还款出现
    if (!rc.getStatus().equals(CompensationStatus.COMPENSATED)) {
      throw new RuntimeException("compensation status is " + rc.getStatus() + "!");
    }
    // 应还本金和利息和手续费
    double money =
        ArithUtil.add(
            rc.getLoanRepay().getCorpus(),
            rc.getLoanRepay().getInterest(),
            rc.getLoanRepay().getFee());
    // 逾期罚金
    double feeToSystem =
        feeConfigBO.getFee(
            FeePoint.OVERDUE_REPAY_SYSTEM,
            FeeType.PENALTY,
            null,
            null,
            ArithUtil.mul(
                money, DateUtil.getIntervalDays(rc.getLoanRepay().getRepayDay(), new Date())));
    // 给代偿方的罚金
    double feeToCompensator =
        feeConfigBO.getFee(
            FeePoint.OVERDUE_REPAY_INVESTOR,
            FeeType.PENALTY,
            null,
            null,
            ArithUtil.mul(
                money, DateUtil.getIntervalDays(rc.getLoanRepay().getRepayDay(), new Date())));

    userBillBO.transferOutFromBalance(
        rc.getLoanRepay().getLoan().getUser().getId(),
        ArithUtil.add(money, feeToCompensator, feeToSystem),
        OperatorInfo.PAY_COMPENSTATION,
        "代偿编号:" + rc.getId());
    userBillBO.transferIntoBalance(
        rc.getRepayer().getId(),
        ArithUtil.add(money, feeToCompensator),
        OperatorInfo.PAY_COMPENSTATION,
        "代偿编号:" + rc.getId());
    userBillBO.transferIntoBalance(
        rc.getRepayer().getId(), feeToSystem, OperatorInfo.PAY_COMPENSTATION, "代偿编号:" + rc.getId());
    // 状态改为完成
    rc.setStatus(CompensationStatus.COMPLETE);
    rc.setPayCompensationTime(new Date());
    ht.update(rc);
  }
 public void generateTransferRepay(
     List<InvestRepay> investRepays, Invest invest, double corpusRate) {
   for (Iterator iterator = investRepays.iterator(); iterator.hasNext(); ) {
     InvestRepay ir = (InvestRepay) iterator.next();
     if (ir.getStatus().equals(RepayStatus.WAIT_REPAY_VERIFY)
         || ir.getStatus().equals(RepayStatus.OVERDUE)
         || ir.getStatus().equals(RepayStatus.BAD_DEBT)) {
       throw new RuntimeException(
           "investRepay with status " + RepayStatus.WAIT_REPAY_VERIFY + "exist!");
     } else if (ir.getStatus().equals(RepayStatus.REPAYING)) {
       // 根据购买本金比例,生成债权还款信息
       InvestRepay irNew = new InvestRepay();
       try {
         BeanUtils.copyProperties(irNew, ir);
       } catch (Exception e) {
         throw new RuntimeException(e);
       }
       irNew.setId(IdGenerator.randomUUID());
       irNew.setCorpus(ArithUtil.mul(ir.getCorpus(), corpusRate, 2));
       irNew.setDefaultInterest(ArithUtil.mul(ir.getDefaultInterest(), corpusRate, 2));
       irNew.setFee(ArithUtil.mul(ir.getFee(), corpusRate, 2));
       irNew.setInterest(ArithUtil.mul(ir.getInterest(), corpusRate, 2));
       irNew.setInvest(invest);
       // 修改原投资的还款信息
       ir.setCorpus(ArithUtil.sub(ir.getCorpus(), irNew.getCorpus()));
       ir.setDefaultInterest(ArithUtil.sub(ir.getDefaultInterest(), irNew.getDefaultInterest()));
       ir.setFee(ArithUtil.sub(ir.getFee(), irNew.getFee()));
       ir.setInterest(ArithUtil.sub(ir.getInterest(), irNew.getInterest()));
       ht.merge(irNew);
       if (corpusRate == 1) {
         ht.delete(ir);
         iterator.remove();
       } else {
         ht.update(ir);
       }
     }
   }
 }
  @Override
  @Transactional(rollbackFor = Exception.class)
  public TrusteeshipOperation createOperation(Invest invest, FacesContext fc) throws IOException {
    String transferApplyId = invest.getTransferApply().getId();
    // 购买债权人的id
    String userId = invest.getUser().getId();
    // 购买的债权本金 transferCorpus(投资时填写的投资额)
    double transferCorpus = invest.getInvestMoney();
    double remainCorpus = transferService.calculateRemainCorpus(transferApplyId);
    if (transferCorpus <= 0 || transferCorpus > remainCorpus) {
      throw new YeePayOperationException("购买本金必须小于等于" + remainCorpus + "且大于0");
    }
    TransferApply ta = ht.get(TransferApply.class, transferApplyId);
    // 购买的本金占剩余本金的比例corpusRate
    double corpusRate = ArithUtil.div(transferCorpus, remainCorpus);
    // 购买的本金占所有转让本金的比例corpusRateInAll
    double corpusRateInAll = ArithUtil.div(transferCorpus, ta.getCorpus());
    // 投资人实际出的钱=债权的购买金额=债权转出价格*corpusRateInAll (债权转出价格=本金-折让金)
    double buyPrice = ArithUtil.mul(ta.getPrice(), corpusRateInAll, 2);

    if (buyPrice > userBillBO.getBalance(userId)) {
      throw new YeePayOperationException("余额不足。");
    }

    // 购买时候,扣除手续费,从转让人收到的金额中扣除。费用根据购买价格计算
    double fee = feeConfigBO.getFee(FeePoint.TRANSFER, FeeType.FACTORAGE, null, null, buyPrice);

    Invest investNew = new Invest();
    investNew.setId(IdGenerator.randomUUID());
    investNew.setMoney(transferCorpus);
    investNew.setStatus(InvestConstants.InvestStatus.CANCEL);
    investNew.setRate(ta.getInvest().getRate());
    investNew.setTransferApply(ta);
    investNew.setLoan(ta.getInvest().getLoan());
    investNew.setTime(new Date());
    investNew.setUser(new User(userId));
    investNew.setInvestMoney(transferCorpus);
    // 在这里添加投标状态是手动投标
    investNew.setIsAutoInvest(false);
    ht.save(investNew);
    ht.update(ta);

    DecimalFormat currentNumberFormat = new DecimalFormat("#0.00");
    // 构建投资参数实体
    CPTransaction cp = new CPTransaction();
    cp.setNotifyUrl(
        YeePayConstants.ResponseS2SUrl.PRE_RESPONSE_URL + YeePayConstants.OperationType.TRANSFER);
    cp.setCallbackUrl(
        YeePayConstants.ResponseWebUrl.PRE_RESPONSE_URL + YeePayConstants.OperationType.TRANSFER);
    // cp.setExpired(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.addMinute(new
    // Date(), 10)));
    cp.setRequestNo(YeePayConstants.RequestNoPre.TRANSFER + investNew.getId());
    cp.setPlateformNo(YeePayConstants.Config.MER_CODE);
    cp.setPlatformUserNo(userId);
    cp.setBizType(YeepayCpTransactionConstant.CREDIT_ASSIGNMENT.name());
    cp.setUserType("MEMBER");

    // 资金明细
    FundDetail fd = new FundDetail();
    // 给转让债权的人的钱
    fd.setAmount(currentNumberFormat.format(buyPrice - fee));
    fd.setTargetPlatformUserNo(ta.getInvest().getUser().getId());
    fd.setTargetUserType("MEMBER");
    fd.setBizType(YeepayCpTransactionConstant.CREDIT_ASSIGNMENT.name());
    cp.getFundDetails().add(fd);

    // 平台分润
    if (fee > 0.0) {
      fd = new FundDetail();
      // 投资人给平台的钱=fee
      fd.setAmount(currentNumberFormat.format(fee));
      fd.setTargetPlatformUserNo(YeePayConstants.Config.MER_CODE);
      fd.setTargetUserType("MERCHANT");
      fd.setBizType(YeepayCpTransactionConstant.COMMISSION.name());
      cp.getFundDetails().add(fd);
    }

    // 扩展参数
    Extend extend = new Extend();
    Loan loan = ta.getInvest().getLoan();
    extend.setTenderOrderNo(loan.getId());
    extend.setCreditorPlatformUserNo(ta.getInvest().getUser().getId());
    // 判断购买的债券是否是自动投标
    if (ta.getInvest().getIsAutoInvest()) {
      extend.setOriginalRequestNo(
          YeePayConstants.RequestNoPre.AUTO_INVEST + ta.getInvest().getId());
    } else {
      extend.setOriginalRequestNo(YeePayConstants.RequestNoPre.INVEST + ta.getInvest().getId());
    }
    cp.setExtend(extend);
    log.debug(cp.toString());

    Map<String, String> params = new HashMap<String, String>();
    params.put("req", cp.toString());
    String sign = CFCASignUtil.sign(cp.toString());
    params.put("sign", sign);

    // 保存本地
    TrusteeshipOperation to = new TrusteeshipOperation();
    to.setId(IdGenerator.randomUUID());
    to.setMarkId(investNew.getId());
    to.setOperator(Double.toString(buyPrice) + "&" + Double.toString(corpusRate) + "&" + userId);
    to.setRequestUrl(YeePayConstants.RequestUrl.TRANSFER);
    to.setRequestData(MapUtil.mapToString(params));
    to.setStatus(TrusteeshipConstants.Status.UN_SEND);
    to.setType(YeePayConstants.OperationType.TRANSFER);
    to.setTrusteeship("yeepay");
    trusteeshipOperationBO.save(to);
    try {
      // 发送信息
      sendOperation(to.getId(), "utf-8", fc);
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }