shiyunteng
2026-08-25 dd4284136cb12dc3c2e498e0f0ff002d553763af
platformx-business-finance-biz/src/main/java/com/by4cloud/platformx/business/service/impl/ContractInvoiceServiceImpl.java
@@ -5,10 +5,12 @@
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.StreamProgress;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@@ -22,6 +24,7 @@
import com.by4cloud.platformx.business.dto.ContractInvoiceQueryDTO;
import com.by4cloud.platformx.business.dto.ContractQueryDTO;
import com.by4cloud.platformx.business.dto.GenInvoiceInfoDTO;
import com.by4cloud.platformx.business.dto.InvoiceQueryDTO;
import com.by4cloud.platformx.business.entity.*;
import com.by4cloud.platformx.business.mapper.*;
import com.by4cloud.platformx.business.service.ContractInvoiceService;
@@ -38,6 +41,9 @@
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
@@ -80,6 +86,9 @@
   @Value("${bip.appSecret}")
   private String appSecret;
   @Value("${file.path}")
   private String localPath;
   @Override
   public R getContractOutBound(Long contractId) {
@@ -91,11 +100,11 @@
         invoiceOutBoundVoList.stream().forEach(contractInvoiceOutBoundVo -> {
            contractInvoiceOutBoundVo.setInvoiceNum(contractInvoiceOutBoundVo.getOutBoundNum().subtract(contractInvoiceOutBoundVo.getInvoiceNum()));
            ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery().eq(ContractSubjectMatter::getContractId,contractId)
                  .eq(ContractSubjectMatter::getMaterialCode,contractInvoiceOutBoundVo.getSubjectMatterCode())
                  .eq(StrUtil.isNotBlank(contractInvoiceOutBoundVo.getLineNo()),ContractSubjectMatter::getLineNo,contractInvoiceOutBoundVo.getLineNo())
            ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery().eq(ContractSubjectMatter::getContractId, contractId)
                  .eq(ContractSubjectMatter::getMaterialCode, contractInvoiceOutBoundVo.getSubjectMatterCode())
                  .eq(StrUtil.isNotBlank(contractInvoiceOutBoundVo.getLineNo()), ContractSubjectMatter::getLineNo, contractInvoiceOutBoundVo.getLineNo())
                  .last("limit 1"));
            if (ObjUtil.isNotNull(subjectMatter)&&subjectMatter.getAdvanceNum().compareTo(new BigDecimal("0"))>0){
            if (ObjUtil.isNotNull(subjectMatter) && subjectMatter.getAdvanceNum().compareTo(new BigDecimal("0")) > 0) {
               contractInvoiceOutBoundVo.setInvoiceNum(contractInvoiceOutBoundVo.getOutBoundNum().subtract(subjectMatter.getAdvanceNum()));
            }
            contractInvoiceOutBoundVo.setToInvoiceNum(contractInvoiceOutBoundVo.getInvoiceNum());
@@ -141,7 +150,7 @@
      //预收款开票
      if (StrUtil.isNotBlank(genInvoiceInfoDTO.getContractId())) {
         ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectOne(Wrappers.<ContractPaymentSchedule>lambdaQuery()
               .eq(ContractPaymentSchedule::getStageName, "合同签订").eq(ContractPaymentSchedule::getContractId,genInvoiceInfoDTO.getContractId())
               .eq(ContractPaymentSchedule::getStageName, "合同签订").eq(ContractPaymentSchedule::getContractId, genInvoiceInfoDTO.getContractId())
               .last("limit 1"));
         if (ObjUtil.isNull(schedule)) {
            return R.failed("合同预收款阶段异常,请联系技术人员");
@@ -162,8 +171,8 @@
               advanceAmount = advanceAmount.add(contractOutBoundInvoiceVo.getInvoiceNum().multiply(subjectMatter.getUnitPrice()));
            }
         }
         log.info("advanceAmount:{}",advanceAmount);
         log.info("schedule.getPlannedAmount:{}",schedule.getPlannedAmount());
         log.info("advanceAmount:{}", advanceAmount);
         log.info("schedule.getPlannedAmount:{}", schedule.getPlannedAmount());
         if (advanceAmount.compareTo(schedule.getPlannedAmount()) > 0) {
            return R.failed("开票金额超出合同签订阶段应收金额:" + schedule.getPlannedAmount() + ",请调整开票数量");
         }
@@ -190,22 +199,22 @@
      }
      SysDept b = r.getData();
      //机动车开票
      if (StrUtil.equals(genInvoiceInfoDTO.getInvoiceType(),"3")||StrUtil.equals(genInvoiceInfoDTO.getInvoiceType(),"4")){
         if (StrUtil.isBlank(genInvoiceInfoDTO.getVehicleNo())){
      if (StrUtil.equals(genInvoiceInfoDTO.getInvoiceType(), "3") || StrUtil.equals(genInvoiceInfoDTO.getInvoiceType(), "4")) {
         if (StrUtil.isBlank(genInvoiceInfoDTO.getVehicleNo())) {
            return R.failed("机动车开票请输入车架号");
         }
         BigDecimal invoiceNumSum = genInvoiceInfoDTO.getOutBoundInvoiceList().stream().map(item->item.getInvoiceNum()).reduce(BigDecimal.ZERO,BigDecimal::add);
         if (invoiceNumSum.compareTo(new BigDecimal("1"))>0){
         BigDecimal invoiceNumSum = genInvoiceInfoDTO.getOutBoundInvoiceList().stream().map(item -> item.getInvoiceNum()).reduce(BigDecimal.ZERO, BigDecimal::add);
         if (invoiceNumSum.compareTo(new BigDecimal("1")) > 0) {
            return R.failed("机动车开票只能1次开1辆");
         }
         JSONObject request = genQueryVinParam(genInvoiceInfoDTO.getVehicleNo(),b);
         JSONObject request = genQueryVinParam(genInvoiceInfoDTO.getVehicleNo(), b);
         R r1 = requestQueryVehicleNo(request);
         if (!r1.isOk()){
         if (!r1.isOk()) {
            return r1;
         }
         JSONObject request1 = genQueryVehDetailParam(genInvoiceInfoDTO.getVehicleNo(),b);
         JSONObject request1 = genQueryVehDetailParam(genInvoiceInfoDTO.getVehicleNo(), b);
         R r2 = requestQueryVehicleDetail(request1);
         if (!r2.isOk()){
         if (!r2.isOk()) {
            return r2;
         }
         genInvoiceInfoDTO.setVehicleData(r2.getData().toString());
@@ -220,16 +229,16 @@
      String requestId = IdUtil.fastUUID();
      log.info("机动车合格证查询接口入参:{},", request.toJSONString());
      String result = HttpUtil.post(bwUrl+"method=baiwang.output.invoice.queryVinDetail&version=1.0&request_id=" + requestId, request.toJSONString());
      String result = HttpUtil.post(bwUrl + "method=baiwang.output.invoice.queryVinDetail&version=1.0&request_id=" + requestId, request.toJSONString());
      log.info("机动车合格证查询接口回参:{},", result);
      saveBwRequestRecord("baiwang.output.invoice.queryVinDetail", requestId, request.toJSONString(), result);
      JSONObject resultObj = JSONObject.parseObject(result);
      if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) &&
            !resultObj.getBoolean("success")) {
         return R.failed("机动车合格证查询失败",result);
         return R.failed("机动车合格证查询失败", result);
      }
      JSONArray models = resultObj.getJSONArray("model");
      if (CollUtil.isNotEmpty(models)){
      if (CollUtil.isNotEmpty(models)) {
         JSONObject model = (JSONObject) models.get(0);
         return R.ok(model);
      }
@@ -238,10 +247,10 @@
   private JSONObject genQueryVehDetailParam(String vehicleNo, SysDept b) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("taxNo",b.getOrgCode());
      jsonObject.put("taxNo", b.getOrgCode());
      JSONObject data = new JSONObject();
      data.put("vehicleNo", vehicleNo);
      jsonObject.put("data",data);
      jsonObject.put("data", data);
      return jsonObject;
   }
@@ -249,30 +258,30 @@
      String requestId = IdUtil.fastUUID();
      log.info("查询税局车架号码入参:{},", request.toJSONString());
      String result = HttpUtil.post(bwUrl+"method=baiwang.output.einvoice.queryvinlist&version=1.0&request_id=" + requestId, request.toJSONString());
      String result = HttpUtil.post(bwUrl + "method=baiwang.output.einvoice.queryvinlist&version=1.0&request_id=" + requestId, request.toJSONString());
      log.info("查询税局车架号码回参:{},", result);
      saveBwRequestRecord("baiwang.output.einvoice.queryvinlist", requestId, request.toJSONString(), result);
      JSONObject resultObj = JSONObject.parseObject(result);
      if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) &&
            !resultObj.getBoolean("success")) {
         return R.failed("查询税局车架号码失败",result);
         return R.failed("查询税局车架号码失败", result);
      }
      JSONArray models = resultObj.getJSONArray("model");
      if (CollUtil.isNotEmpty(models)){
      if (CollUtil.isNotEmpty(models)) {
         JSONObject model = (JSONObject) models.get(0);
         if (!model.getBoolean("isOpenInvoice")){
         if (!model.getBoolean("isOpenInvoice")) {
            return R.failed(model.getString("isNotOpenInvReason"));
         }
      }
      return R.ok();
   }
   private JSONObject genQueryVinParam(String vehicleNo,SysDept b) {
   private JSONObject genQueryVinParam(String vehicleNo, SysDept b) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("taxNo",b.getOrgCode());
      jsonObject.put("taxNo", b.getOrgCode());
      JSONObject data = new JSONObject();
      data.put("vinList", new ArrayList<String>(Arrays.asList(vehicleNo)));
      jsonObject.put("data",data);
      jsonObject.put("data", data);
      return jsonObject;
   }
@@ -517,12 +526,12 @@
      if (ArrayUtil.isEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList())) {
         return R.failed("请选择开票出库单后再操作");
      }
      if (StrUtil.equals(genInvoiceInfoDTO.getInvoiceType(),"3")||StrUtil.equals(genInvoiceInfoDTO.getInvoiceType(),"4")){
         if (StrUtil.isBlank(genInvoiceInfoDTO.getVehicleNo())){
      if (StrUtil.equals(genInvoiceInfoDTO.getInvoiceType(), "3") || StrUtil.equals(genInvoiceInfoDTO.getInvoiceType(), "4")) {
         if (StrUtil.isBlank(genInvoiceInfoDTO.getVehicleNo())) {
            return R.failed("机动车开票请输入车架号");
         }
         BigDecimal invoiceNumSum = genInvoiceInfoDTO.getOutBoundInvoiceList().stream().map(item->item.getInvoiceNum()).reduce(BigDecimal.ZERO,BigDecimal::add);
         if (invoiceNumSum.compareTo(new BigDecimal("1"))>0){
         BigDecimal invoiceNumSum = genInvoiceInfoDTO.getOutBoundInvoiceList().stream().map(item -> item.getInvoiceNum()).reduce(BigDecimal.ZERO, BigDecimal::add);
         if (invoiceNumSum.compareTo(new BigDecimal("1")) > 0) {
            return R.failed("机动车开票只能1次开1辆");
         }
      }
@@ -530,7 +539,7 @@
      if (StrUtil.isNotBlank(genInvoiceInfoDTO.getContractId())) {
         ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectOne(Wrappers.<ContractPaymentSchedule>lambdaQuery()
               .eq(ContractPaymentSchedule::getStageName, "合同签订").eq(ContractPaymentSchedule::getContractId,genInvoiceInfoDTO.getContractId())
               .eq(ContractPaymentSchedule::getStageName, "合同签订").eq(ContractPaymentSchedule::getContractId, genInvoiceInfoDTO.getContractId())
               .last("limit 1"));
         if (ObjUtil.isNull(schedule)) {
            return R.failed("合同预收款阶段异常,请联系技术人员");
@@ -539,9 +548,9 @@
         if (ObjUtil.isNull(contract)) {
            return R.failed("合同信息异常,请联系技术人员");
         }
         ContractInvoice lastInvoice = baseMapper.selectOne(Wrappers.<ContractInvoice>lambdaQuery().eq(ContractInvoice::getContractId,contract.getId())
         ContractInvoice lastInvoice = baseMapper.selectOne(Wrappers.<ContractInvoice>lambdaQuery().eq(ContractInvoice::getContractId, contract.getId())
               .orderByDesc(ContractInvoice::getCreateTime).last("limit 1"));
         if (ObjUtil.isNotNull(lastInvoice)&&StrUtil.equals(lastInvoice.getApprovalStatus(),"0")){
         if (ObjUtil.isNotNull(lastInvoice) && StrUtil.equals(lastInvoice.getApprovalStatus(), "0")) {
            return R.failed("请等待最近的发票审核完成后再进行预收开票");
         }
         R<SysDept> r = remoteDeptService.getById(contract.getPartyBId());
@@ -562,7 +571,7 @@
         }
         GenInvoiceInfoVo vo = genAdvanceInvoiceInfoVo(genInvoiceInfoDTO, contract, b);
         //发票保存
         ContractInvoice invoice = saveContractInvoice(vo, contract, genInvoiceInfoDTO.getOutBoundInvoiceList(), DateUtil.current() + "","1");
         ContractInvoice invoice = saveContractInvoice(vo, contract, genInvoiceInfoDTO.getOutBoundInvoiceList(), DateUtil.current() + "", "1");
         //启动流程
         ProcessInstanceParamDto dto = new ProcessInstanceParamDto();
         Map<String, Object> map = BeanUtil.beanToMap(invoice);
@@ -597,29 +606,29 @@
      }
      SysDept b = r.getData();
      //机动车开票
      if (StrUtil.equals(genInvoiceInfoDTO.getInvoiceType(),"3")||StrUtil.equals(genInvoiceInfoDTO.getInvoiceType(),"4")){
         if (StrUtil.isBlank(genInvoiceInfoDTO.getVehicleNo())){
      if (StrUtil.equals(genInvoiceInfoDTO.getInvoiceType(), "3") || StrUtil.equals(genInvoiceInfoDTO.getInvoiceType(), "4")) {
         if (StrUtil.isBlank(genInvoiceInfoDTO.getVehicleNo())) {
            return R.failed("机动车开票请输入车架号");
         }
         BigDecimal invoiceNumSum = genInvoiceInfoDTO.getOutBoundInvoiceList().stream().map(item->item.getInvoiceNum()).reduce(BigDecimal.ZERO,BigDecimal::add);
         if (invoiceNumSum.compareTo(new BigDecimal("1"))>0){
         BigDecimal invoiceNumSum = genInvoiceInfoDTO.getOutBoundInvoiceList().stream().map(item -> item.getInvoiceNum()).reduce(BigDecimal.ZERO, BigDecimal::add);
         if (invoiceNumSum.compareTo(new BigDecimal("1")) > 0) {
            return R.failed("机动车开票只能1次开1辆");
         }
         JSONObject request = genQueryVinParam(genInvoiceInfoDTO.getVehicleNo(),b);
         JSONObject request = genQueryVinParam(genInvoiceInfoDTO.getVehicleNo(), b);
         R r1 = requestQueryVehicleNo(request);
         if (!r1.isOk()){
         if (!r1.isOk()) {
            return r1;
         }
         JSONObject request1 = genQueryVehDetailParam(genInvoiceInfoDTO.getVehicleNo(),b);
         JSONObject request1 = genQueryVehDetailParam(genInvoiceInfoDTO.getVehicleNo(), b);
         R r2 = requestQueryVehicleDetail(request1);
         if (!r2.isOk()){
         if (!r2.isOk()) {
            return r2;
         }
         genInvoiceInfoDTO.setVehicleData(r2.getData().toString());
      }
      GenInvoiceInfoVo vo = genInvoiceInfoVo(genInvoiceInfoDTO, contract, b);
      //发票保存
      ContractInvoice invoice = saveContractInvoice(vo, contract, genInvoiceInfoDTO.getOutBoundInvoiceList(), DateUtil.current() + "","0");
      ContractInvoice invoice = saveContractInvoice(vo, contract, genInvoiceInfoDTO.getOutBoundInvoiceList(), DateUtil.current() + "", "0");
      //启动流程
      ProcessInstanceParamDto dto = new ProcessInstanceParamDto();
      Map<String, Object> map = BeanUtil.beanToMap(invoice);
@@ -663,7 +672,7 @@
      bwRequestRecordMapper.insert(bwRequestRecord);
   }
   private JSONObject genBlueInvoice(GenInvoiceInfoVo vo, String serialNo,SysDept dept) {
   private JSONObject genBlueInvoice(GenInvoiceInfoVo vo, String serialNo, SysDept dept) {
      JSONObject jsonObject = new JSONObject();
      //销方
      jsonObject.put("taxNo", vo.getPartyBOrgCode());//税号
@@ -688,9 +697,9 @@
         invoiceDetail.put("goodsUnit", invoiceItemVo.getUnit());
         invoiceDetail.put("goodsQuantity", invoiceItemVo.getQuantity());
//         invoiceDetail.put("goodsPrice", invoiceItemVo.getUnitPrice());
         if (StrUtil.equals(vo.getInvoiceVehicleType(),"3")){
         if (StrUtil.equals(vo.getInvoiceVehicleType(), "3")) {
            invoiceDetail.put("goodsSpecification", vo.getVehicleNo());
         }else {
         } else {
            invoiceDetail.put("goodsSpecification", invoiceItemVo.getSpecification());
         }
@@ -718,7 +727,7 @@
   }
   private ContractInvoice saveContractInvoice(GenInvoiceInfoVo genInvoiceInfoVo, Contract contract,
            List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList, String serialNo,String advanceFlag) {
                                    List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList, String serialNo, String advanceFlag) {
      ContractInvoice invoice = new ContractInvoice();
      invoice.setContractId(contract.getId());
      invoice.setInvoiceCategory("1");
@@ -846,7 +855,7 @@
      if (bwFlag) {
         List<ContractInvoice> contractInvoices = baseMapper.selectList(Wrappers.<ContractInvoice>lambdaQuery()
               .eq(ContractInvoice::getApprovalStatus, "1")
               .eq(ContractInvoice::getBwRequestResult,"1")
               .eq(ContractInvoice::getBwRequestResult, "1")
               .isNull(ContractInvoice::getInvoicePath));
         if (ArrayUtil.isNotEmpty(contractInvoices)) {
            contractInvoices.stream().forEach(contractInvoice -> {
@@ -856,11 +865,11 @@
               data.put("serialNo", contractInvoice.getSerialNo());
               data.put("returnType", "3");
               data.put("invoiceIssueMode", "1");
               request.put("data",data);
               request.put("data", data);
               String requestId = IdUtil.fastUUID();
               log.info("serial_no:{},发票查询入参:{},", contractInvoice.getSerialNo(), request.toJSONString());
               String result = HttpUtil.post(bwUrl+"method=baiwang.output.format.query&version=1.0&request_id=" + requestId, request.toJSONString());
               String result = HttpUtil.post(bwUrl + "method=baiwang.output.format.query&version=1.0&request_id=" + requestId, request.toJSONString());
               log.info("serial_no:{},发票查询回参:{},", contractInvoice.getSerialNo(), result);
               saveBwRequestRecord("baiwang.output.format.query", requestId, request.toJSONString(), result);
               JSONObject resultObj = JSONObject.parseObject(result);
@@ -869,11 +878,101 @@
                  contractInvoice.setInvoicePath(model.getString("queryData"));
                  contractInvoice.setInvoiceStatus("2");
                  baseMapper.updateById(contractInvoice);
                  //传输附件
                  pushBipInvoicePdf(contractInvoice);
               }
            });
         }
      }
      return R.ok();
   }
   private void pushBipInvoicePdf(ContractInvoice contractInvoice) {
      String accessToken = "";
      if (redisTemplate.hasKey("BIP_TOKEN")) {
         accessToken = (String) redisTemplate.opsForValue().get("BIP_TOKEN");
      } else {
         accessToken = paymentConfirmService.getAccessToken(accessToken);
      }
      if (StrUtil.isEmpty(accessToken)) {
         log.error("bip accessToken 获取异常");
         return;
      }
      String finalAccessToken = accessToken;
      String requestId = IdUtil.fastUUID();
      JSONObject request = new JSONObject();
      request.put("taxNo", contractInvoice.getTaxNo());
      JSONObject data = new JSONObject();
      data.put("serialNo", contractInvoice.getSerialNo());
      data.put("returnType", "2");
      data.put("invoiceIssueMode", "1");
      request.put("data", data);
      log.info("serial_no:{},发票查询入参:{},", contractInvoice.getSerialNo(), request.toJSONString());
      String result = HttpUtil.post(bwUrl + "method=baiwang.output.format.query&version=1.0&request_id=" + requestId, request.toJSONString());
      log.info("serial_no:{},发票查询回参:{},", contractInvoice.getSerialNo(), result);
      JSONObject resultObj = JSONObject.parseObject(result);
      String filePath = localPath + File.separator + DateUtil.today() + File.separator + IdUtil.fastUUID() + ".pdf";
      if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) && resultObj.getBoolean("success")) {
         JSONObject model = resultObj.getJSONObject("model");
         saveBase64ToFile(model.getString("queryData"), filePath);
      }
      File file = new File(filePath);
      if (file.exists()) {
         log.info("应收发票附件上传入参:{}", url + "/yonbip/uspace/iuap-apcom-file/rest/v1/file?access_token="
               + finalAccessToken + "&businessType=yonbip-fi-earapbill&businessId=" + contractInvoice.getBipId());
         HttpResponse response = HttpUtil.createPost(url + "/yonbip/uspace/iuap-apcom-file/rest/v1/file?access_token="
                     + finalAccessToken + "&businessType=yonbip-fi-earapbill&businessId=" + contractInvoice.getBipId())
               .header("Content-Type", "multipart/form-data")
               // 设置表单参数(文件),第一个参数为接口接收的参数名(如"file")
               .form("files", file)
               // 执行请求
               .execute();
         log.info("应收发票附件上传回参:{}", response.body());
         //保存请求记录
         paymentConfirmService.saveBipRequestRecord(request, "应收发票集成接口", response.body());
         JSONObject resultJson = JSONObject.parseObject(response.body());
         if (resultJson.containsKey("code") && resultJson.getString("code").equals("200")) {
            JSONObject datas = resultJson.getJSONObject("data");
            JSONArray arr = datas.getJSONArray("data");
            if (CollUtil.isNotEmpty(arr)) {
               JSONObject data0 = (JSONObject) arr.get(0);
               contractInvoice.setBipFileId(data0.getString("id"));
               baseMapper.updateById(contractInvoice);
            }
         }
      }
   }
   /**
    * 将 Base64 字符串转换为本地文件
    *
    * @param base64Str  Base64 编码的字符串
    * @param targetPath 目标文件路径(包含文件名和后缀,如 "D:/test.pdf")
    */
   public static void saveBase64ToFile(String base64Str, String targetPath) {
      if (base64Str == null || base64Str.isEmpty()) {
         throw new IllegalArgumentException("Base64 字符串不能为空");
      }
      // 1. 处理可能存在的 Data URI 前缀 (如: "data:application/pdf;base64,JVBERi...")
      if (base64Str.contains(",")) {
         base64Str = base64Str.split(",")[1];
      }
      // 2. 解码 Base64 为字节数组
      byte[] fileBytes = Base64.getDecoder().decode(base64Str);
      // 3. 将字节数组写入文件
      try (FileOutputStream fos = new FileOutputStream(new File(targetPath))) {
         fos.write(fileBytes);
         fos.flush();
         System.out.println("文件保存成功: " + targetPath);
      } catch (IOException e) {
         e.printStackTrace();
         throw new RuntimeException("文件保存失败", e);
      }
   }
   private void pushBipInvoice(ContractInvoice contractInvoice) {
@@ -902,14 +1001,21 @@
         log.error("查询单位信息异常");
         return;
      }
      SysDept dept = r.getData();
      SysDept comp = r.getData();
      R<SysDept> rDept = remoteDeptService.getById(SecurityUtils.getUser().getDeptId());
      if (!r.isOk()) {
         log.error("查询单位信息异常");
         return;
      }
      SysDept dept = rDept.getData();
      //蓝票
      if (StrUtil.equals(contractInvoice.getInvoiceCategory(), "1")) {
         JSONObject params = genBlueReceiveParams(contractInvoice, contract, customer, dept);
         JSONObject params = genBlueReceiveParams(contractInvoice, contract, customer, comp, dept);
         String finalAccessToken = accessToken;
         log.info("应收发票集成入参:{}", params.toJSONString());
         String result = HttpUtil.post(url + "/yonbip/EFI/receivable/save?access_token=" + finalAccessToken, params.toJSONString());
         String result = HttpUtil.post(url + "/yonbip/EFI/receivable/saveandsubmit?access_token=" + finalAccessToken, params.toJSONString());
         log.info("应收发票集成回参:{}", result);
         //保存请求记录
         paymentConfirmService.saveBipRequestRecord(params, "应收发票集成接口", result);
@@ -935,6 +1041,7 @@
         JSONObject resultJson = JSONObject.parseObject(result);
         if (resultJson.containsKey("code") && resultJson.getString("code").equals("200")) {
            contractInvoice.setBipPush("1");
            contractInvoice.setBipBody(resultJson.getString("data"));
            baseMapper.updateById(contractInvoice);
         }
      }
@@ -949,7 +1056,8 @@
      return jsonObject;
   }
   private JSONObject genBlueReceiveParams(ContractInvoice contractInvoice, Contract contract, BusinessCustomer customer, SysDept dept) {
   private JSONObject genBlueReceiveParams(ContractInvoice contractInvoice, Contract contract, BusinessCustomer customer
         , SysDept comp, SysDept dept) {
      JSONObject jsonObject = new JSONObject();
      JSONObject data = new JSONObject();
      if (contractInvoice.getInvoiceCategory().equals("1")) {
@@ -960,11 +1068,13 @@
      data.put("billDate", DateUtil.format(contractInvoice.getInvoiceTime(), DatePattern.NORM_DATETIME_FORMAT));
      data.put("exchangeRate", "1");//汇率
      data.put("exchangeRateDate", DateUtil.now());//汇率时间
      data.put("objectType", "1");
      data.put("objectType", "1");//往来对象类型(枚举值 1:客户; 2:员工;3:资金业务对象)
      data.put("deptCode", dept.getOrgCode());//部门编码 SS2
      data.put("staffCode", SecurityUtils.getUser().getNickname());//业务员编码
      data.put("customerCode", customer.getBipCode());//客户编码
      data.put("financeOrgCode", dept.getBipCode());//开票组织编码
      data.put("orgCode", dept.getBipCode());//业务组织编码
      data.put("bustypeCode", "");//交易类型编码 暂估默认ZGYSFP,销售默认MJHYXGLXT
      data.put("financeOrgCode", comp.getBipCode());//开票组织编码
      data.put("orgCode", comp.getBipCode());//业务组织编码
      data.put("bustypeCode", "ZBYXGLXT");//交易类型编码 暂估默认ZGYSFP,销售默认ZBYXGLXT
      data.put("contractNo", contract.getContractNo());
      data.put("oriCurrencyCode", "CNY");//币种
      data.put("_status", "Insert");
@@ -1034,7 +1144,7 @@
   public void takeEffect(Long id) {
      ContractInvoice invoice = baseMapper.selectById(id);
      R<SysDept> r = remoteDeptService.getById(SecurityUtils.getUser().getCompId());
      if (!r.isOk()){
      if (!r.isOk()) {
         log.error("单位信息查询异常");
         return;
      }
@@ -1049,8 +1159,8 @@
      //蓝票
      if (invoice.getInvoiceCategory().equals("1")) {
         // TODO 开蓝票接口机动车
         if (StrUtil.equals(vo.getInvoiceVehicleType(),"3")){
            JSONObject request = genBlueInvoiceVehicle(vo, invoice.getSerialNo(),dept);
         if (StrUtil.equals(vo.getInvoiceVehicleType(), "3")) {
            JSONObject request = genBlueInvoiceVehicle(vo, invoice.getSerialNo(), dept);
            String requestId = IdUtil.fastUUID();
            invoice.setBwRequestId(requestId);
            invoice.setBwRequestParam(request.toJSONString());
@@ -1075,7 +1185,7 @@
         }
         // TODO 开蓝票接口 非机动车
         JSONObject request = genBlueInvoice(vo, invoice.getSerialNo(),dept);
         JSONObject request = genBlueInvoice(vo, invoice.getSerialNo(), dept);
         if (bwFlag) {
            String requestId = IdUtil.fastUUID();
            invoice.setBwRequestId(requestId);
@@ -1103,7 +1213,7 @@
               }
            }
         }
         if (StrUtil.isNotBlank(vo.getAdvanceInvoice())){
         if (StrUtil.isNotBlank(vo.getAdvanceInvoice())) {
            contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
            contractMapper.updateById(contract);
            return;
@@ -1112,15 +1222,17 @@
            //合同状态
            if (StrUtil.equals(contract.getBillingStatus(), "2")) {
               contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
               if (contract.getBillingAmout().compareTo(contract.getAmount()) == 0) {
               if (contract.getBillingAmout().compareTo(contract.getAmount()) == 0 &&
                     contract.getPaidAmount().compareTo(contract.getAmount().subtract(contract.getDropAmount())) == 0) {
                  contract.setBillingStatus("3");
                  contract.setContractStatus(3);
               }
               if (contract.getBillingAmout().compareTo(contract.getAmount()) < 0) {
                  contract.setBillingStatus("1");
                  List<ContractOutBound> outBoundList = contractOutBoundMapper.selectList(Wrappers.<ContractOutBound>lambdaQuery()
                        .eq(ContractOutBound::getContractId,contract.getId())
                        .eq(ContractOutBound::getContractId, contract.getId())
                        .apply("invoice_num < out_bound_num"));
                  if (CollUtil.isNotEmpty(outBoundList)){
                  if (CollUtil.isNotEmpty(outBoundList)) {
                     contract.setBillingStatus("2");
                  }
@@ -1144,7 +1256,16 @@
               } else {
                  contract.setBillingStatus("2");
               }
               contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
               if (contract.getBillingAmout().compareTo(contract.getAmount()) == 0 &&
                     contract.getPaidAmount().compareTo(contract.getAmount().subtract(contract.getDropAmount())) == 0) {
                  contract.setBillingStatus("3");
                  contract.setContractStatus(3);
               }
               //防止重复审开票审核通过后 开票金额超出合同金额
               if (contract.getBillingAmout().compareTo(contract.getAmount()) > 0) {
                  contract.setBillingAmout(contract.getAmount());
               }
            } else {
               //判断是否有可开票记录
               List<ContractPaymentSchedule> scheduleList = contractPaymentScheduleMapper.selectList(Wrappers.<ContractPaymentSchedule>lambdaQuery()
@@ -1155,11 +1276,7 @@
                  contract.setBillingStatus("2");
               }
            }
            contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
            //防止重复审开票审核通过后 开票金额超出合同金额
            if (contract.getBillingAmout().compareTo(contract.getAmount()) > 0) {
               contract.setBillingAmout(contract.getAmount());
            }
            contractMapper.updateById(contract);
         }
         baseMapper.updateById(invoice);
@@ -1209,15 +1326,15 @@
         contractMapper.updateById(contract);
         blueInvoice.setRedReversal("1");
         baseMapper.updateById(blueInvoice);
         if (StrUtil.isNotBlank(vo.getAdvanceInvoice())){
         if (StrUtil.isNotBlank(vo.getAdvanceInvoice())) {
            //还原预开数量
            List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList = BeanUtil.copyToList(JSONArray.parseArray(blueInvoice.getInvoicePreviewParam()), ContractOutBoundInvoiceVo.class);
            if (ArrayUtil.isNotEmpty(outBoundInvoiceVoList)) {
               outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
                  ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
                  if (ObjUtil.isNotNull(subjectMatter)){
                  if (ObjUtil.isNotNull(subjectMatter)) {
                     subjectMatter.setAdvanceNum(subjectMatter.getAdvanceNum().subtract(contractOutBoundInvoiceVo.getInvoiceNum()));
                     if (subjectMatter.getAdvanceNum().compareTo(new BigDecimal("0"))<=0){
                     if (subjectMatter.getAdvanceNum().compareTo(new BigDecimal("0")) <= 0) {
                        subjectMatter.setAdvanceNum(new BigDecimal("0"));
                     }
                     contractSubjectMatterMapper.updateById(subjectMatter);
@@ -1256,7 +1373,7 @@
   }
   private JSONObject genBlueInvoiceVehicle(GenInvoiceInfoVo vo, String serialNo,SysDept dept) {
   private JSONObject genBlueInvoiceVehicle(GenInvoiceInfoVo vo, String serialNo, SysDept dept) {
      JSONObject vechicleData = JSONObject.parseObject(vo.getVehicleData());
      JSONObject jsonObject = new JSONObject();
      //销方
@@ -1275,13 +1392,13 @@
      JSONObject invoiceDetail = new JSONObject();
      invoiceDetail.put("vehicleNo", vo.getVehicleNo());
      invoiceDetail.put("manufacturingEnterprise","03");
      invoiceDetail.put("manufacturingEnterprise", "03");
      invoiceDetail.put("originPlace", vechicleData.getString("originPlace"));
      invoiceDetail.put("certificateNo",vo.getCertificateNo());
      invoiceDetail.put("engineNo",vechicleData.getString("engineNo"));
      invoiceDetail.put("tonnage",vechicleData.getString("tonnage"));
      invoiceDetail.put("passengersLimited",vechicleData.getString("passengersLimited"));
      invoiceDetail.put("brandModel",vechicleData.getString("brandModel"));
      invoiceDetail.put("certificateNo", vo.getCertificateNo());
      invoiceDetail.put("engineNo", vechicleData.getString("engineNo"));
      invoiceDetail.put("tonnage", vechicleData.getString("tonnage"));
      invoiceDetail.put("passengersLimited", vechicleData.getString("passengersLimited"));
      invoiceDetail.put("brandModel", vechicleData.getString("brandModel"));
      invoiceDetail.put("goodsCode", vo.getInvoiceItemList().get(0).getTaxCode());
      invoiceDetail.put("goodsTaxRate", vo.getInvoiceItemList().get(0).getTaxRate().divide(new BigDecimal("100")));
@@ -1430,4 +1547,171 @@
      baseMapper.updateById(invoice);
      return R.ok();
   }
   @Override
   public R bipPush(Long invoiceId) {
      ContractInvoice contractInvoice = baseMapper.selectById(invoiceId);
      String accessToken = "";
      if (redisTemplate.hasKey("BIP_TOKEN")) {
         accessToken = (String) redisTemplate.opsForValue().get("BIP_TOKEN");
      } else {
         accessToken = paymentConfirmService.getAccessToken(accessToken);
      }
      if (StrUtil.isEmpty(accessToken)) {
         log.error("bip accessToken 获取异常");
         return R.failed("bip accessToken 获取异常");
      }
      Contract contract = contractMapper.selectById(contractInvoice.getContractId());
      if (ObjUtil.isNull(contract)) {
         log.error("查询合同信息异常");
         return R.failed("查询合同信息异常");
      }
      BusinessCustomer customer = businessCustomerMapper.selectById(contract.getPartyAId());
      if (ObjUtil.isNull(customer) || StrUtil.isEmpty(customer.getBipCode())) {
         log.error("查询合同信息异常");
         return R.failed("查询合同信息异常");
      }
      R<SysDept> r = remoteDeptService.getById(contract.getPartyBId());
      if (!r.isOk()) {
         log.error("查询单位信息异常");
         return R.failed("查询单位信息异常");
      }
      SysDept comp = r.getData();
      R<SysDept> rDept = remoteDeptService.getById(SecurityUtils.getUser().getDeptId());
      if (!r.isOk()) {
         log.error("查询部门信息异常");
         return R.failed("查询部门信息异常");
      }
      SysDept dept = rDept.getData();
      //蓝票
      if (StrUtil.equals(contractInvoice.getInvoiceCategory(), "1")) {
         JSONObject params = genBlueReceiveParams(contractInvoice, contract, customer, comp, dept);
         String finalAccessToken = accessToken;
         log.info("应收发票集成入参:{}", params.toJSONString());
         String result = HttpUtil.post(url + "/yonbip/EFI/receivable/saveandsubmit?access_token=" + finalAccessToken, params.toJSONString());
         log.info("应收发票集成回参:{}", result);
         //保存请求记录
         paymentConfirmService.saveBipRequestRecord(params, "应收发票集成接口", result);
         JSONObject resultJson = JSONObject.parseObject(result);
         if (resultJson.containsKey("code") && resultJson.getString("code").equals("200")) {
            JSONObject data = resultJson.getJSONObject("data");
            contractInvoice.setBipPush("1");
            contractInvoice.setBipId(data.getLong("id"));
            contractInvoice.setBipBody(resultJson.getString("data"));
            baseMapper.updateById(contractInvoice);
            return R.ok();
         }
         return R.failed(resultJson, "应收发票集成失败");
      }
      //红票
      if (StrUtil.equals(contractInvoice.getInvoiceCategory(), "2")) {
         JSONObject params = genRedReceiveParams(contractInvoice);
         String finalAccessToken = accessToken;
         log.info("应收发票删除入参:{}", params.toJSONString());
         String result = HttpUtil.post(url + "/yonbip/EFI/receivable/delete?access_token=" + finalAccessToken, params.toJSONString());
         log.info("应收发票删除回参:{}", result);
         //保存请求记录
         paymentConfirmService.saveBipRequestRecord(params, "应收发票删除接口", result);
         JSONObject resultJson = JSONObject.parseObject(result);
         if (resultJson.containsKey("code") && resultJson.getString("code").equals("200")) {
            contractInvoice.setBipPush("1");
            contractInvoice.setBipBody(resultJson.getString("data"));
            baseMapper.updateById(contractInvoice);
            return R.ok();
         }
         return R.failed(resultJson, "应收发票删除失败");
      }
      return R.ok();
   }
   @Override
   public R queryInvoice(Page page, InvoiceQueryDTO queryDTO) {
      R<SysDept> r = remoteDeptService.getById(SecurityUtils.getUser().getCompId());
      if (!r.isOk()) {
         log.error("查询单位信息异常");
         return R.failed("查询单位信息异常");
      }
      SysDept comp = r.getData();
      JSONObject request = genQueryInvoiceParam(page, queryDTO, comp);
      String requestId = IdUtil.fastUUID();
      log.info("已开发票查询接口入参:{},", request.toJSONString());
      String result = HttpUtil.post(bwUrl + "method=baiwang.output.invoice.query&version=1.0&request_id=" + requestId, request.toJSONString());
      log.info("已开发票查询接口回参:{},", result);
      saveBwRequestRecord("baiwang.output.invoice.query", requestId, request.toJSONString(), result);
      JSONObject resultObj = JSONObject.parseObject(result);
      if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) &&
            !resultObj.getBoolean("success")) {
         return R.failed("已开发票查询", result);
      }
      JSONArray models = resultObj.getJSONArray("model");
      if (CollUtil.isNotEmpty(models)) {
         page.setRecords(models);
         page.setTotal(resultObj.getInteger("total"));
         return R.ok(page);
      }
      page.setTotal(0);
      page.setRecords(null);
      return R.ok(page);
   }
   private JSONObject genQueryInvoiceParam(Page page, InvoiceQueryDTO queryDTO, SysDept comp) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("taxNo", comp.getOrgCode());
      JSONObject data = new JSONObject();
      data.put("serialNo", StrUtil.isNotBlank(queryDTO.getSerialNo()) ? queryDTO.getSerialNo() : "");
      data.put("invoiceCode", StrUtil.isNotBlank(queryDTO.getInvoiceCode()) ? queryDTO.getInvoiceCode() : "");
      data.put("invoiceNo", StrUtil.isNotBlank(queryDTO.getInvoiceNo()) ? queryDTO.getInvoiceNo() : "");
      data.put("invoiceTypeCode", StrUtil.isNotBlank(queryDTO.getInvoiceTypeCode()) ? queryDTO.getInvoiceTypeCode() : "");
      data.put("invoiceTerminalCode", StrUtil.isNotBlank(queryDTO.getInvoiceTerminalCode()) ? queryDTO.getInvoiceTerminalCode() : "");
      data.put("sourceMark", StrUtil.isNotBlank(queryDTO.getSourceMark()) ? queryDTO.getSourceMark() : "");
      data.put("invoiceSpecialMark", StrUtil.isNotBlank(queryDTO.getInvoiceSpecialMark()) ? queryDTO.getInvoiceSpecialMark() : "");
      data.put("buyerTaxNo", StrUtil.isNotBlank(queryDTO.getBuyerTaxNo()) ? queryDTO.getBuyerTaxNo() : "");
      data.put("buyerName", StrUtil.isNotBlank(queryDTO.getBuyerName()) ? queryDTO.getBuyerName() : "");
      data.put("invoiceStatus", StrUtil.isNotBlank(queryDTO.getInvoiceStatus()) ? queryDTO.getInvoiceStatus() : "");
      data.put("invoiceType", StrUtil.isNotBlank(queryDTO.getInvoiceType()) ? queryDTO.getInvoiceType() : "");
      data.put("invoiceStartDate", StrUtil.isNotBlank(queryDTO.getInvoiceStartDate()) ? queryDTO.getInvoiceStartDate() : "");
      data.put("invoiceEndDate", StrUtil.isNotBlank(queryDTO.getInvoiceEndDate()) ? queryDTO.getInvoiceEndDate() : "");
      data.put("machineNo", StrUtil.isNotBlank(queryDTO.getMachineNo()) ? queryDTO.getMachineNo() : "");
      data.put("systemName", StrUtil.isNotBlank(queryDTO.getSystemName()) ? queryDTO.getSystemName() : "");
      data.put("systemId", StrUtil.isNotBlank(queryDTO.getSystemId()) ? queryDTO.getSystemId() : "");
      data.put("pageSize", page.getSize());
      data.put("pageNo", page.getCurrent());
      jsonObject.put("data", data);
      return jsonObject;
   }
   @Override
   public R add(ContractInvoice contractInvoice) {
      Contract contract = contractMapper.selectById(contractInvoice.getContractId());
      if (ObjUtil.isNull(contract)) {
         return R.failed("合同信息异常");
      }
      List<ContractInvoice> invoiceList = baseMapper.selectList(Wrappers.<ContractInvoice>lambdaQuery()
            .eq(ContractInvoice::getInvoiceNo, contractInvoice.getInvoiceNo()));
      if (CollUtil.isNotEmpty(invoiceList)) {
         return R.failed("发票已存在,请勿重复操作");
      }
      contractInvoice.setInvoiceStatus("2");
      contractInvoice.setInvoiceSource("1");
      contractInvoice.setRedReversal("0");
      contractInvoice.setApprovalStatus("1");
      baseMapper.insert(contractInvoice);
      contract.setBillingAmout(contract.getBillingAmout().add(contractInvoice.getInvoiceTotalPriceTax()));
      if (contract.getBillingAmout().compareTo(contract.getAmount()) >= 0) {
         contract.setBillingStatus("3");
      }
      contractMapper.updateById(contract);
      return R.ok();
   }
   public static void main(String[] args) {
      File file = new File("d://tmp//" + IdUtil.fastUUID() + ".pdf");
      HttpUtil.downloadFile("http://fp.baiwang.com/format/d?d=BB99645F8ED2AE7D2055E7D29330D366B7CAE92C278C6BB84D222610CEC2118D", file);
   }
}