From 6bbed1ea6b36af4eb0b234bec9d6e42d56f0cd00 Mon Sep 17 00:00:00 2001
From: shiyunteng <shiyunteng@example.com>
Date: 星期三, 30 九月 2026 16:12:49 +0800
Subject: [PATCH] feat:合同新增关联单位  开票可根据甲方或关联单位选择开票单位  收款去掉强制确认 收款只关联合同甲方或关联单位

---
 platformx-business-finance-biz/src/main/java/com/by4cloud/platformx/business/service/impl/ContractInvoiceServiceImpl.java | 2192 ++++++++++++++++++++++++++++++++++++++++++++++++++---------
 1 files changed, 1,855 insertions(+), 337 deletions(-)

diff --git a/platformx-business-finance-biz/src/main/java/com/by4cloud/platformx/business/service/impl/ContractInvoiceServiceImpl.java b/platformx-business-finance-biz/src/main/java/com/by4cloud/platformx/business/service/impl/ContractInvoiceServiceImpl.java
index 9d07ded..655f892 100644
--- a/platformx-business-finance-biz/src/main/java/com/by4cloud/platformx/business/service/impl/ContractInvoiceServiceImpl.java
+++ b/platformx-business-finance-biz/src/main/java/com/by4cloud/platformx/business/service/impl/ContractInvoiceServiceImpl.java
@@ -1,18 +1,20 @@
 package com.by4cloud.platformx.business.service.impl;
 
 import cn.hutool.core.bean.BeanUtil;
+import cn.hutool.core.collection.CollUtil;
 import cn.hutool.core.convert.Convert;
 import cn.hutool.core.date.DatePattern;
 import cn.hutool.core.date.DateUtil;
-import cn.hutool.core.util.ArrayUtil;
+import cn.hutool.core.lang.tree.Tree;
+import cn.hutool.core.lang.tree.TreeNode;
+import cn.hutool.core.lang.tree.TreeUtil;
 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.JSON;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
-import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@@ -20,9 +22,7 @@
 import com.by4cloud.platformx.admin.api.feign.RemoteDeptService;
 import com.by4cloud.platformx.business.api.feign.RemoteFlowProcessService;
 import com.by4cloud.platformx.business.constant.FlowNameEnum;
-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.*;
 import com.by4cloud.platformx.business.entity.*;
 import com.by4cloud.platformx.business.mapper.*;
 import com.by4cloud.platformx.business.service.ContractInvoiceService;
@@ -30,20 +30,19 @@
 import com.by4cloud.platformx.business.vo.*;
 import com.by4cloud.platformx.common.core.util.R;
 import com.by4cloud.platformx.common.data.datascope.DataScope;
-import com.by4cloud.platformx.common.data.mybatis.BaseModel;
 import com.by4cloud.platformx.common.security.util.SecurityUtils;
 import com.by4cloud.platformx.flow.task.dto.ProcessInstanceParamDto;
 import com.github.yulichang.wrapper.MPJLambdaWrapper;
-import io.swagger.v3.oas.annotations.Operation;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang3.StringUtils;
-import org.springdoc.core.annotations.ParameterObject;
+import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Value;
-import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.StringRedisTemplate;
 import org.springframework.stereotype.Service;
-import org.springframework.web.bind.annotation.GetMapping;
 
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
 import java.util.*;
@@ -55,6 +54,7 @@
 public class ContractInvoiceServiceImpl extends ServiceImpl<ContractInvoiceMapper, ContractInvoice> implements ContractInvoiceService {
 
 	private final ContractMapper contractMapper;
+	private final ContractSubjectMatterMapper contractSubjectMatterMapper;
 	private final BusinessCustomerMapper businessCustomerMapper;
 	private final ContractOutBoundMapper contractOutBoundMapper;
 	private final PaymentConfirmMapper paymentConfirmMapper;
@@ -67,7 +67,9 @@
 	private final RemoteDeptService remoteDeptService;
 	private final RemoteFlowProcessService remoteFlowProcessService;
 	private final PaymentConfirmService paymentConfirmService;
-	private final RedisTemplate redisTemplate;
+	private final StringRedisTemplate redisTemplate;
+	private final BipViewMapper bipViewMapper;
+	private final BipDictMapper bipDictMapper;
 
 
 	@Value("${BWInvoice.url}")
@@ -79,11 +81,32 @@
 	@Value("${bip.url}")
 	private String url;
 
-	@Value("${bip.appKey}")
-	private String appKey;
+	@Value("${dept.sgb}")
+	private String sgb;
 
-	@Value("${bip.appSecret}")
-	private String appSecret;
+	@Value("${dept.smj}")
+	private String smj;
+
+	@Value("${dept.smjzt}")
+	private String smjzt;
+
+	@Value("${dept.smjsc}")
+	private String smjsc;
+
+	@Value("${dept.smjhw}")
+	private String smjhw;
+
+	@Value("${dept.tfgs}")
+	private String tfgs;
+
+	@Value("${dept.jxc}")
+	private String jxc;
+
+	@Value("${dept.ymj}")
+	private String ymj;
+
+	@Value("${file.path}")
+	private String localPath;
 
 
 	@Override
@@ -92,13 +115,73 @@
 				.selectAll(ContractOutBound.class)
 				.eq(ContractOutBound::getContractId, contractId);
 		List<ContractInvoiceOutBoundVo> invoiceOutBoundVoList = contractOutBoundMapper.selectJoinList(ContractInvoiceOutBoundVo.class, wrapper);
-		if (ArrayUtil.isNotEmpty(invoiceOutBoundVoList.toArray())) {
+		if (CollUtil.isNotEmpty(invoiceOutBoundVoList)) {
 			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())
+						.last("limit 1"));
+				if (ObjUtil.isNotNull(subjectMatter)) {
+					contractInvoiceOutBoundVo.setUnitPrice(subjectMatter.getUnitPrice());
+					if (subjectMatter.getAdvanceNum().compareTo(new BigDecimal("0")) > 0) {
+						contractInvoiceOutBoundVo.setInvoiceNum(contractInvoiceOutBoundVo.getOutBoundNum().subtract(subjectMatter.getAdvanceNum()));
+					}
+				}
 				contractInvoiceOutBoundVo.setToInvoiceNum(contractInvoiceOutBoundVo.getInvoiceNum());
 			});
 		}
-		return R.ok(invoiceOutBoundVoList);
+		return R.ok(invoiceOutBoundVoList.stream().filter(item -> item.getUnitPrice().compareTo(new BigDecimal("0")) > 0).collect(Collectors.toList()));
+	}
+
+	@Override
+	public R getMergeContractOutBound(Long[] ids) {
+		if (CollUtil.isEmpty(Arrays.asList(ids))) {
+			return R.failed("璇烽�夋嫨鍚堝苟寮�绁ㄧ殑鍚堝悓");
+		}
+		MPJLambdaWrapper<ContractOutBound> wrapper = new MPJLambdaWrapper<ContractOutBound>()
+				.selectAll(ContractOutBound.class)
+				.in(ContractOutBound::getContractId, ids);
+		List<ContractInvoiceOutBoundVo> invoiceOutBoundVoList = contractOutBoundMapper.selectJoinList(ContractInvoiceOutBoundVo.class, wrapper);
+		if (CollUtil.isNotEmpty(invoiceOutBoundVoList)) {
+			invoiceOutBoundVoList.stream().forEach(contractInvoiceOutBoundVo -> {
+
+				contractInvoiceOutBoundVo.setInvoiceNum(contractInvoiceOutBoundVo.getOutBoundNum().subtract(contractInvoiceOutBoundVo.getInvoiceNum()));
+				ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery()
+						.in(ContractSubjectMatter::getContractId, ids)
+						.eq(ContractSubjectMatter::getMaterialCode, contractInvoiceOutBoundVo.getSubjectMatterCode())
+						.eq(StrUtil.isNotBlank(contractInvoiceOutBoundVo.getLineNo()), ContractSubjectMatter::getLineNo, contractInvoiceOutBoundVo.getLineNo())
+						.last("limit 1"));
+				if (ObjUtil.isNotNull(subjectMatter)) {
+					contractInvoiceOutBoundVo.setUnitPrice(subjectMatter.getUnitPrice());
+					if (subjectMatter.getAdvanceNum().compareTo(new BigDecimal("0")) > 0) {
+						contractInvoiceOutBoundVo.setInvoiceNum(contractInvoiceOutBoundVo.getOutBoundNum().subtract(subjectMatter.getAdvanceNum()));
+					}
+				}
+				contractInvoiceOutBoundVo.setToInvoiceNum(contractInvoiceOutBoundVo.getInvoiceNum());
+			});
+		}
+		return R.ok(invoiceOutBoundVoList.stream().filter(item -> item.getUnitPrice().compareTo(new BigDecimal("0")) > 0).collect(Collectors.toList()));
+
+	}
+
+	@Override
+	public R getContractAdvance(Long contractId) {
+		MPJLambdaWrapper<ContractSubjectMatter> wrapper = new MPJLambdaWrapper<ContractSubjectMatter>()
+				.selectAll(ContractSubjectMatter.class)
+				.selectAs(ContractSubjectMatter::getMaterialCode, "subjectMatterCode")
+				.selectAs(ContractSubjectMatter::getMaterialName, "subjectMatterName")
+				.selectAs(ContractSubjectMatter::getQuantity, "outBoundNum")
+				.eq(ContractSubjectMatter::getContractId, contractId);
+		List<ContractInvoiceOutBoundVo> invoiceOutBoundVoList = contractSubjectMatterMapper.selectJoinList(ContractInvoiceOutBoundVo.class, wrapper);
+		if (CollUtil.isNotEmpty(invoiceOutBoundVoList)) {
+			invoiceOutBoundVoList.stream().forEach(contractInvoiceOutBoundVo -> {
+				contractInvoiceOutBoundVo.setInvoiceNum(contractInvoiceOutBoundVo.getOutBoundNum().subtract(contractInvoiceOutBoundVo.getAdvanceNum()));
+				contractInvoiceOutBoundVo.setToInvoiceNum(contractInvoiceOutBoundVo.getInvoiceNum());
+			});
+		}
+		return R.ok(invoiceOutBoundVoList.stream().filter(item -> item.getUnitPrice().compareTo(new BigDecimal("0")) > 0).collect(Collectors.toList()));
 	}
 
 	@Override
@@ -113,14 +196,78 @@
 
 	@Override
 	public R genInvoiceInfo(GenInvoiceInfoDTO genInvoiceInfoDTO) {
-		if (ArrayUtil.isEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList())) {
+		if (CollUtil.isEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList())) {
 			return R.failed("璇烽�夋嫨寮�绁ㄥ嚭搴撳崟鍚庡啀鎿嶄綔");
 		}
+		genInvoiceInfoDTO.setOutBoundInvoiceList(genInvoiceInfoDTO.getOutBoundInvoiceList().stream().filter(item ->
+				item.getInvoiceNum().compareTo(new BigDecimal("0")) > 0).collect(Collectors.toList()));
+		if (CollUtil.isEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList())) {
+			return R.failed("璇烽�夋嫨寮�绁ㄥ嚭搴撳崟鍚庢垨璋冩暣寮�绁ㄦ暟閲忓啀鎿嶄綔");
+		}
 		Long contractId = null;
-		if (!StrUtil.equals(genInvoiceInfoDTO.getContractCategory(),"water_house")) {
+		//棰勬敹娆惧紑绁�
+		if (StrUtil.isNotBlank(genInvoiceInfoDTO.getContractId())) {
+			ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectOne(Wrappers.<ContractPaymentSchedule>lambdaQuery()
+					.eq(ContractPaymentSchedule::getStageName, "鍚堝悓绛捐").eq(ContractPaymentSchedule::getContractId, genInvoiceInfoDTO.getContractId())
+					.last("limit 1"));
+			if (ObjUtil.isNull(schedule)) {
+				return R.failed("鍚堝悓棰勬敹娆鹃樁娈靛紓甯革紝璇疯仈绯绘妧鏈汉鍛�");
+			}
+			Contract contract = contractMapper.selectById(genInvoiceInfoDTO.getContractId());
+			if (ObjUtil.isNull(contract)) {
+				return R.failed("鍚堝悓淇℃伅寮傚父锛岃鑱旂郴鎶�鏈汉鍛�");
+			}
+			R<SysDept> r = remoteDeptService.getById(contract.getPartyBId());
+			if (!r.isOk()) {
+				return R.failed("鑾峰彇寮�绁ㄥ崟浣嶅紓甯�");
+			}
+			SysDept b = r.getData();
+			BusinessCustomer customer = businessCustomerMapper.selectById(contract.getPartyAId());
+			if (ObjUtil.isNull(customer)) {
+				return R.failed("鑾峰彇璐柟鍗曚綅寮傚父");
+			}
+			BigDecimal advanceAmount = new BigDecimal("0");
+			for (ContractOutBoundInvoiceVo contractOutBoundInvoiceVo : genInvoiceInfoDTO.getOutBoundInvoiceList()) {
+				ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+				if (ObjUtil.isNotNull(subjectMatter)) {
+					advanceAmount = advanceAmount.add(contractOutBoundInvoiceVo.getInvoiceNum().multiply(subjectMatter.getUnitPrice()));
+				}
+				List<String> smjList = new ArrayList<>();
+				smjList.add(smj);
+				smjList.add(smjsc);
+				smjList.add(smjzt);
+				smjList.add(smjhw);
+				if (("" + SecurityUtils.getUser().getCompId()).equals(smj) || ("" + SecurityUtils.getUser().getCompId()).equals(smjsc) ||
+						("" + SecurityUtils.getUser().getCompId()).equals(smjzt) ||
+						("" + SecurityUtils.getUser().getCompId()).equals(smjhw)) {
+					Product product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, subjectMatter.getMaterialCode())
+							.in(Product::getCompId, smjList).last("limit 1"));
+					if (ObjUtil.isNull(product) || StrUtil.isBlank(product.getTaxClass()) || StrUtil.isBlank(product.getTaxCode())) {
+						return R.failed("璇峰湪浜у搧淇℃伅涓ˉ鍏呯◣鏀跺垎绫讳俊鎭�");
+					}
+				} else {
+					Product product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, subjectMatter.getMaterialCode())
+							.eq(Product::getCompId, SecurityUtils.getUser().getCompId()).last("limit 1"));
+					if (ObjUtil.isNull(product) || StrUtil.isBlank(product.getTaxClass()) || StrUtil.isBlank(product.getTaxCode())) {
+						return R.failed("璇峰湪浜у搧淇℃伅涓ˉ鍏呯◣鏀跺垎绫讳俊鎭�");
+					}
+				}
+			}
+			log.info("advanceAmount:{}", advanceAmount);
+			log.info("schedule.getPlannedAmount:{}", schedule.getPlannedAmount());
+			if (advanceAmount.compareTo(schedule.getPlannedAmount()) > 0) {
+				return R.failed("寮�绁ㄩ噾棰濊秴鍑哄悎鍚岀璁㈤樁娈靛簲鏀堕噾棰�:" + schedule.getPlannedAmount() + ",璇疯皟鏁村紑绁ㄦ暟閲�");
+			}
+			GenInvoiceInfoVo vo = genAdvanceInvoiceInfoVo(genInvoiceInfoDTO, contract, b);
+			vo = transBipVo(vo, b, customer);
+			return R.ok(vo);
+		}
+
+		//姝e父浜у搧寮�绁�
+		if (!StrUtil.equals(genInvoiceInfoDTO.getContractCategory(), "water_house")) {
 			ContractOutBound outBound = contractOutBoundMapper.selectById(genInvoiceInfoDTO.getOutBoundInvoiceList().get(0).getContractOutBoundId());
 			contractId = outBound.getContractId();
-		}else {
+		} else {
 			ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectById(genInvoiceInfoDTO.getOutBoundInvoiceList().get(0).getContractOutBoundId());
 			contractId = schedule.getContractId();
 		}
@@ -133,101 +280,487 @@
 			return R.failed("鑾峰彇寮�绁ㄥ崟浣嶅紓甯�");
 		}
 		SysDept b = r.getData();
-		GenInvoiceInfoVo vo = genInvoiceInfoVo(genInvoiceInfoDTO, contract, b);
+		BusinessCustomer customer = businessCustomerMapper.selectById(contract.getPartyAId());
+		if (ObjUtil.isNull(customer)) {
+			return R.failed("鑾峰彇璐柟鍗曚綅寮傚父");
+		}
+		for (ContractOutBoundInvoiceVo contractOutBoundInvoiceVo : genInvoiceInfoDTO.getOutBoundInvoiceList()) {
+			ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+			List<String> smjList = new ArrayList<>();
+			smjList.add(smj);
+			smjList.add(smjsc);
+			smjList.add(smjzt);
+			smjList.add(smjhw);
+			if (("" + SecurityUtils.getUser().getCompId()).equals(smj) || ("" + SecurityUtils.getUser().getCompId()).equals(smjsc) ||
+					("" + SecurityUtils.getUser().getCompId()).equals(smjzt)||
+					("" + SecurityUtils.getUser().getCompId()).equals(smjhw)) {
+				Product product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, contractOutBound.getSubjectMatterCode())
+						.in(Product::getCompId, smjList).last("limit 1"));
+				if (ObjUtil.isNull(product) || StrUtil.isBlank(product.getTaxClass()) || StrUtil.isBlank(product.getTaxCode())) {
+					return R.failed("璇峰湪浜у搧淇℃伅涓ˉ鍏呯◣鏀跺垎绫讳俊鎭�");
+				}
+			} else {
+				Product product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, contractOutBound.getSubjectMatterCode())
+						.eq(Product::getCompId, SecurityUtils.getUser().getCompId()).last("limit 1"));
+				if (ObjUtil.isNull(product) || StrUtil.isBlank(product.getTaxClass()) || StrUtil.isBlank(product.getTaxCode())) {
+					return R.failed("璇峰湪浜у搧淇℃伅涓ˉ鍏呯◣鏀跺垎绫讳俊鎭�");
+				}
+			}
 
+		}
+		//鏈哄姩杞﹀紑绁�
+		if (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) {
+				return R.failed("鏈哄姩杞﹀紑绁ㄥ彧鑳�1娆″紑1杈�");
+			}
+			JSONObject request = genQueryVinParam(genInvoiceInfoDTO.getVehicleNo(), b);
+			R r1 = requestQueryVehicleNo(request);
+			if (!r1.isOk()) {
+				return r1;
+			}
+			JSONObject request1 = genQueryVehDetailParam(genInvoiceInfoDTO.getVehicleNo(), b);
+			R<JSONObject> r2 = requestQueryVehicleDetail(request1, genInvoiceInfoDTO);
+			if (!r2.isOk()) {
+				return r2;
+			}
+			r2.getData().put("contact", b.getOrgContact());
+			genInvoiceInfoDTO.setVehicleData(r2.getData().toString());
+		}
+
+		GenInvoiceInfoVo vo = genInvoiceInfoVo(genInvoiceInfoDTO, contract, b);
+		vo = transBipVo(vo, b, customer);
 		return R.ok(vo);
+	}
+
+	@Override
+	public R genMergeInvoiceInfo(GenMergeInvoiceDTO mergeInvoiceDTO) {
+		R<SysDept> r = remoteDeptService.getById(SecurityUtils.getUser().getCompId());
+		if (!r.isOk()) {
+			return R.failed("鑾峰彇寮�绁ㄥ崟浣嶅紓甯�");
+		}
+		SysDept b = r.getData();
+		BusinessCustomer customer = businessCustomerMapper.selectById(mergeInvoiceDTO.getBusGuestId());
+		if (ObjUtil.isNull(customer)) {
+			return R.failed("鑾峰彇璐柟鍗曚綅寮傚父");
+		}
+		for (ContractOutBoundInvoiceVo contractOutBoundInvoiceVo : mergeInvoiceDTO.getOutBoundInvoiceList()) {
+			ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+			List<String> smjList = new ArrayList<>();
+			smjList.add(smj);
+			smjList.add(smjsc);
+			smjList.add(smjzt);
+			smjList.add(smjhw);
+			if (("" + SecurityUtils.getUser().getCompId()).equals(smj) || ("" + SecurityUtils.getUser().getCompId()).equals(smjsc) ||
+					("" + SecurityUtils.getUser().getCompId()).equals(smjzt) ||
+					("" + SecurityUtils.getUser().getCompId()).equals(smjhw)) {
+				Product product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, contractOutBound.getSubjectMatterCode())
+						.in(Product::getCompId, smjList).last("limit 1"));
+				if (ObjUtil.isNull(product) || StrUtil.isBlank(product.getTaxClass()) || StrUtil.isBlank(product.getTaxCode())) {
+					return R.failed("璇峰湪浜у搧淇℃伅涓ˉ鍏呯◣鏀跺垎绫讳俊鎭�");
+				}
+			} else {
+				Product product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, contractOutBound.getSubjectMatterCode())
+						.eq(Product::getCompId, SecurityUtils.getUser().getCompId()).last("limit 1"));
+				if (ObjUtil.isNull(product) || StrUtil.isBlank(product.getTaxClass()) || StrUtil.isBlank(product.getTaxCode())) {
+					return R.failed("璇峰湪浜у搧淇℃伅涓ˉ鍏呯◣鏀跺垎绫讳俊鎭�");
+				}
+			}
+
+		}
+		GenInvoiceInfoVo vo = genMergeInvoiceVo(mergeInvoiceDTO, customer, b);
+		vo = transBipVo(vo, b, customer);
+		return R.ok(vo);
+	}
+
+	private GenInvoiceInfoVo genMergeInvoiceVo(GenMergeInvoiceDTO mergeInvoiceDTO, BusinessCustomer customer, SysDept b) {
+		GenInvoiceInfoVo vo = new GenInvoiceInfoVo();
+		vo.setPartyA(customer.getCompanyName());
+		vo.setPartyAOrgCode(customer.getCreditCode());
+		vo.setPartyAOpenBank(customer.getBankName());
+		vo.setPartyABankAccount(customer.getBankAccount());
+		vo.setPartyB(b.getOrgName());
+		vo.setPartyBOrgCode(b.getOrgCode());
+		vo.setPartyBOpenBank(b.getOrgBank());
+		vo.setPartyBBankAccount(b.getOrgBankAccount());
+		vo.setInvoiceType(customer.getInvoiceType());
+		vo.setRemarks(mergeInvoiceDTO.getRemarks());
+		vo.setOutBoundInvoiceList(mergeInvoiceDTO.getOutBoundInvoiceList());
+		vo.setContractIds(mergeInvoiceDTO.getContractIds());
+		if (StrUtil.isNotBlank(mergeInvoiceDTO.getInvoiceType())) {
+			vo.setInvoiceVehicleType(mergeInvoiceDTO.getInvoiceType());
+		}
+
+		List<InvoiceItemVo> invoiceItemVoList = new ArrayList<>();
+		List<String> erpCode = new ArrayList<>();
+		List<ContractOutBoundMergeVo> mergeOutBounds = new ArrayList<>();
+
+		if (CollUtil.isNotEmpty(mergeInvoiceDTO.getOutBoundInvoiceList())) {
+			mergeInvoiceDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
+				ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+				ContractSubjectMatter subjectMatter = subjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery()
+						.eq(ContractSubjectMatter::getMaterialCode, contractOutBound.getSubjectMatterCode())
+						.eq(StrUtil.isNotBlank(contractOutBound.getLineNo()), ContractSubjectMatter::getLineNo, contractOutBound.getLineNo())
+						.eq(ContractSubjectMatter::getContractId, contractOutBound.getContractId()).last("limit 1"));
+				if (!CollUtil.contains(erpCode, contractOutBound.getSubjectMatterCode() + subjectMatter.getUnitPrice())) {
+					erpCode.add(contractOutBound.getSubjectMatterCode() + subjectMatter.getUnitPrice());
+					ContractOutBoundMergeVo mergeVo = new ContractOutBoundMergeVo();
+					mergeVo.setMaterialCode(contractOutBound.getSubjectMatterCode() + subjectMatter.getUnitPrice());
+					mergeVo.setMaterialInternalName(contractOutBound.getSubjectMatterName());
+					mergeVo.setQuantity(contractOutBoundInvoiceVo.getInvoiceNum());
+					Product product = new Product();
+					List<String> smjList = new ArrayList<>();
+					smjList.add(smj);
+					smjList.add(smjsc);
+					smjList.add(smjzt);
+					smjList.add(smjhw);
+					if (("" + SecurityUtils.getUser().getCompId()).equals(smj) || ("" + SecurityUtils.getUser().getCompId()).equals(smjsc) ||
+							("" + SecurityUtils.getUser().getCompId()).equals(smjzt) ||
+							("" + SecurityUtils.getUser().getCompId()).equals(smjhw)) {
+						product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, contractOutBound.getSubjectMatterCode())
+								.in(Product::getCompId, smjList).last("limit 1"));
+					} else {
+						product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, contractOutBound.getSubjectMatterCode())
+								.eq(Product::getCompId, SecurityUtils.getUser().getCompId()).last("limit 1"));
+					}
+
+					if (ObjUtil.isNotNull(product)) {
+						mergeVo.setTaxClass(product.getTaxClass());
+						mergeVo.setSpecification(product.getProductType());
+						mergeVo.setTaxRate(new BigDecimal(product.getTaxRate()));
+						mergeVo.setTaxCode(product.getTaxCode());
+					}
+					if (ObjUtil.isNotNull(subjectMatter)) {
+						mergeVo.setUnitPrice(subjectMatter.getUnitPrice());
+						mergeVo.setUnit(subjectMatter.getUnit());
+						if (StrUtil.equals(product.getErpCode(), "water_bill")) {
+							mergeVo.setItemName("*" + product.getTaxClass() + "*姘磋垂");
+						} else if (StrUtil.equals(product.getErpCode(), "electricity_bill")) {
+							mergeVo.setItemName("*" + product.getTaxClass() + "*鐢佃垂");
+						} else if (StrUtil.equals(product.getErpCode(), "house_rental")) {
+							mergeVo.setItemName("*" + product.getTaxClass() + "*鎴垮眿绉熻祦");
+						} else {
+							mergeVo.setItemName("*" + product.getTaxClass() + "*" + subjectMatter.getMaterialName());
+						}
+					}
+					mergeOutBounds.add(mergeVo);
+				} else {
+					List<ContractOutBoundMergeVo> filteredList = mergeOutBounds.stream()
+							.filter(item -> item.getMaterialCode().equals(subjectMatter.getMaterialCode() + subjectMatter.getUnitPrice())) // 闃叉绌烘寚閽堬紝寤鸿甯搁噺鍦ㄥ墠
+							.collect(Collectors.toList());
+					if (CollUtil.isNotEmpty(filteredList)) {
+						filteredList.get(0).setQuantity(filteredList.get(0).getQuantity().add(contractOutBound.getOutBoundNum()));
+					}
+				}
+			});
+			if (CollUtil.isNotEmpty(mergeOutBounds)) {
+				invoiceItemVoList = BeanUtil.copyToList(mergeOutBounds, InvoiceItemVo.class);
+				invoiceItemVoList.stream().filter(invoiceItem -> invoiceItem.getUnitPrice().compareTo(new BigDecimal("0")) > 0)
+						.forEach(invoiceItemVo -> {
+//				for (InvoiceItemVo invoiceItemVo:invoiceItemVoList) {
+							BigDecimal itemPrice = invoiceItemVo.getUnitPrice().multiply(invoiceItemVo.getQuantity());
+							BigDecimal itemPriceTax = itemPrice.divide(new BigDecimal("100").add(invoiceItemVo.getTaxRate()), 2, RoundingMode.HALF_UP).multiply(invoiceItemVo.getTaxRate());
+							invoiceItemVo.setPriceTax(itemPriceTax);
+							invoiceItemVo.setPriceNoTax(itemPrice.subtract(itemPriceTax));
+							invoiceItemVo.setPriceAndTax(itemPrice);
+						});
+				vo.setTotalPrice(invoiceItemVoList.stream().map(item -> item.getPriceAndTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
+				vo.setTotalTax(invoiceItemVoList.stream().map(item -> item.getPriceTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
+				vo.setInvoiceItemList(invoiceItemVoList);
+				vo.setPriceWords(Convert.digitToChinese(vo.getTotalPrice()));
+			}
+		}
+
+		return vo;
+	}
+
+	private GenInvoiceInfoVo transBipVo(GenInvoiceInfoVo vo, SysDept comp, BusinessCustomer customer) {
+		ContractInvoiceBipVo bipVo = new ContractInvoiceBipVo();
+		bipVo.setDjrq(DateUtil.today());
+		bipVo.setKpzz(comp.getBipCode());
+		bipVo.setYwzz(comp.getBipCode());
+		R<SysDept> rDept = remoteDeptService.getById(SecurityUtils.getUser().getDeptId());
+		if (rDept.isOk()) {
+			bipVo.setBm(rDept.getData().getOrgCode());
+			bipVo.setHsdy(rDept.getData().getOrgCode());
+		}
+		bipVo.setYwy(SecurityUtils.getUser().getNickname());
+		bipVo.setPzzdr(SecurityUtils.getUser().getNickname());
+		bipVo.setJylx("ZBYXGLXT");
+		bipVo.setWldxlx("1");
+		bipVo.setKh(customer.getCreditCode());
+		bipVo.setBz("CNY");
+		bipVo.setFjzs("1");
+		bipVo.setSfzy("1");
+		bipVo.setSfnbwl("1");
+		bipVo.setSfjyjs("0");
+		bipVo.setDjfx("1");
+		bipVo.setItemList(vo.getInvoiceItemList());
+		vo.setBipVo(bipVo);
+		return vo;
+	}
+
+	private R requestQueryVehicleDetail(JSONObject request, GenInvoiceInfoDTO invoiceInfoDTO) {
+		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());
+		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);
+		}
+		JSONArray models = resultObj.getJSONArray("model");
+		if (CollUtil.isNotEmpty(models)) {
+			JSONObject model = (JSONObject) models.get(0);
+			if (StrUtil.isNotBlank(invoiceInfoDTO.getOrigin())) {
+				model.put("origin", invoiceInfoDTO.getOrigin());
+			}
+			if (StrUtil.isNotBlank(invoiceInfoDTO.getTonnage())) {
+				model.put("tonnage", invoiceInfoDTO.getTonnage());
+			}
+			if (StrUtil.isNotBlank(invoiceInfoDTO.getPassengersLimited())) {
+				model.put("passengersLimited", invoiceInfoDTO.getPassengersLimited());
+			}
+			model.put("origin", invoiceInfoDTO.getOrigin());
+			model.put("vehicleNo", invoiceInfoDTO.getVehicleNo());
+			return R.ok(model);
+		}
+		return R.failed("鏈哄姩杞﹀悎鏍艰瘉鏌ヨ寮傚父");
+	}
+
+	private JSONObject genQueryVehDetailParam(String vehicleNo, SysDept b) {
+		JSONObject jsonObject = new JSONObject();
+		jsonObject.put("taxNo", b.getOrgCode());
+		JSONObject data = new JSONObject();
+		data.put("vehicleNo", vehicleNo);
+		jsonObject.put("data", data);
+		return jsonObject;
+	}
+
+	private R requestQueryVehicleNo(JSONObject request) {
+		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());
+		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);
+		}
+		JSONArray models = resultObj.getJSONArray("model");
+		if (CollUtil.isNotEmpty(models)) {
+			JSONObject model = (JSONObject) models.get(0);
+			if (!model.getBoolean("isOpenInvoice")) {
+				return R.failed(model.getString("isNotOpenInvReason"));
+			}
+		}
+		return R.ok();
+	}
+
+	private JSONObject genQueryVinParam(String vehicleNo, SysDept b) {
+		JSONObject jsonObject = new JSONObject();
+		jsonObject.put("taxNo", b.getOrgCode());
+		JSONObject data = new JSONObject();
+		data.put("vinList", new ArrayList<String>(Arrays.asList(vehicleNo)));
+		jsonObject.put("data", data);
+		return jsonObject;
 	}
 
 	private GenInvoiceInfoVo genInvoiceInfoVo(GenInvoiceInfoDTO genInvoiceInfoDTO, Contract contract, SysDept b) {
 		GenInvoiceInfoVo vo = new GenInvoiceInfoVo();
 		BusinessCustomer a = businessCustomerMapper.selectById(contract.getPartyAId());
-		vo.setPartyA(a.getRegisterName());
-		vo.setPartyAOrgCode(a.getCreditCode());
+		vo.setContractId(contract.getId());
+		vo.setPartyA(genInvoiceInfoDTO.getPartyA());
+		vo.setPartyAOrgCode(genInvoiceInfoDTO.getPartyAOrgCode());
 		vo.setPartyAOpenBank(a.getBankName());
 		vo.setPartyABankAccount(a.getBankAccount());
 		vo.setPartyB(b.getOrgName());
 		vo.setPartyBOrgCode(b.getOrgCode());
 		vo.setPartyBOpenBank(b.getOrgBank());
 		vo.setPartyBBankAccount(b.getOrgBankAccount());
+		vo.setInvoiceType(a.getInvoiceType());
+		vo.setRemarks(genInvoiceInfoDTO.getRemarks());
+		vo.setOutBoundInvoiceList(genInvoiceInfoDTO.getOutBoundInvoiceList());
+		if (StrUtil.isNotBlank(genInvoiceInfoDTO.getInvoiceType())) {
+			vo.setInvoiceVehicleType(genInvoiceInfoDTO.getInvoiceType());
+		}
+		if (StrUtil.isNotBlank(genInvoiceInfoDTO.getVehicleNo())) {
+			vo.setVehicleNo(genInvoiceInfoDTO.getVehicleNo());
+		}
+		if (StrUtil.isNotBlank(genInvoiceInfoDTO.getCertificateNo())) {
+			vo.setCertificateNo(genInvoiceInfoDTO.getCertificateNo());
+		}
+		if (StrUtil.isNotBlank(genInvoiceInfoDTO.getVehicleData())) {
+			vo.setVehicleData(genInvoiceInfoDTO.getVehicleData());
+		}
 		List<InvoiceItemVo> invoiceItemVoList = new ArrayList<>();
 		List<String> erpCode = new ArrayList<>();
 		List<ContractOutBoundMergeVo> mergeOutBounds = new ArrayList<>();
+		if (genInvoiceInfoDTO.getInvoiceType().equals("3")) {
+			String[] vehiclenNoList = genInvoiceInfoDTO.getVehicleNo().split(",");
+			for (int i = 0; i < vehiclenNoList.length; i++) {
+				ContractOutBound contractOutBound = contractOutBoundMapper.selectById(genInvoiceInfoDTO.getOutBoundInvoiceList().get(0).getContractOutBoundId());
+				ContractSubjectMatter subjectMatter = subjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery()
+						.eq(ContractSubjectMatter::getMaterialCode, contractOutBound.getSubjectMatterCode())
+						.eq(StrUtil.isNotBlank(contractOutBound.getLineNo()), ContractSubjectMatter::getLineNo, contractOutBound.getLineNo())
+						.eq(ContractSubjectMatter::getContractId, contract.getId()).last("limit 1"));
+				ContractOutBoundMergeVo mergeVo = new ContractOutBoundMergeVo();
+				mergeVo.setMaterialCode(contractOutBound.getSubjectMatterCode() + subjectMatter.getUnitPrice());
+				mergeVo.setMaterialInternalName(contractOutBound.getSubjectMatterName());
+				mergeVo.setQuantity(new BigDecimal("1"));
+				Product product = new Product();
+				List<String> smjList = new ArrayList<>();
+				smjList.add(smj);
+				smjList.add(smjsc);
+				smjList.add(smjzt);
+				smjList.add(smjhw);
+				if (("" + SecurityUtils.getUser().getCompId()).equals(smj) || ("" + SecurityUtils.getUser().getCompId()).equals(smjsc) ||
+						("" + SecurityUtils.getUser().getCompId()).equals(smjzt)||
+						("" + SecurityUtils.getUser().getCompId()).equals(smjhw)) {
+					product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, contractOutBound.getSubjectMatterCode())
+							.in(Product::getCompId, smjList).last("limit 1"));
+				} else {
+					product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, contractOutBound.getSubjectMatterCode())
+							.eq(Product::getCompId, SecurityUtils.getUser().getCompId()).last("limit 1"));
+				}
+
+				if (ObjUtil.isNotNull(product)) {
+					mergeVo.setTaxClass(product.getTaxClass());
+					mergeVo.setSpecification(vehiclenNoList[i]);
+					mergeVo.setTaxRate(new BigDecimal(product.getTaxRate()));
+					mergeVo.setTaxCode(product.getTaxCode());
+				}
+				if (ObjUtil.isNotNull(subjectMatter)) {
+					mergeVo.setUnitPrice(subjectMatter.getUnitPrice());
+					mergeVo.setUnit(subjectMatter.getUnit());
+					if (StrUtil.equals(product.getErpCode(), "water_bill")) {
+						mergeVo.setItemName("*" + product.getTaxClass() + "*姘磋垂");
+					} else if (StrUtil.equals(product.getErpCode(), "electricity_bill")) {
+						mergeVo.setItemName("*" + product.getTaxClass() + "*鐢佃垂");
+					} else if (StrUtil.equals(product.getErpCode(), "house_rental")) {
+						mergeVo.setItemName("*" + product.getTaxClass() + "*鎴垮眿绉熻祦");
+					} else {
+						mergeVo.setItemName("*" + product.getTaxClass() + "*" + subjectMatter.getMaterialName());
+					}
+				}
+				mergeOutBounds.add(mergeVo);
+			}
+			if (CollUtil.isNotEmpty(mergeOutBounds)) {
+				invoiceItemVoList = BeanUtil.copyToList(mergeOutBounds, InvoiceItemVo.class);
+				invoiceItemVoList.stream().filter(invoiceItem -> invoiceItem.getUnitPrice().compareTo(new BigDecimal("0")) > 0)
+						.forEach(invoiceItemVo -> {
+//				for (InvoiceItemVo invoiceItemVo:invoiceItemVoList) {
+							BigDecimal itemPrice = invoiceItemVo.getUnitPrice().multiply(invoiceItemVo.getQuantity());
+							BigDecimal itemPriceTax = itemPrice.divide(new BigDecimal("100").add(invoiceItemVo.getTaxRate()), 2, RoundingMode.HALF_UP).multiply(invoiceItemVo.getTaxRate());
+							invoiceItemVo.setPriceTax(itemPriceTax);
+							invoiceItemVo.setPriceNoTax(itemPrice.subtract(itemPriceTax));
+							invoiceItemVo.setPriceAndTax(itemPrice);
+						});
+				vo.setTotalPrice(invoiceItemVoList.stream().map(item -> item.getPriceAndTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
+				vo.setTotalTax(invoiceItemVoList.stream().map(item -> item.getPriceTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
+				vo.setInvoiceItemList(invoiceItemVoList);
+				vo.setPriceWords(Convert.digitToChinese(vo.getTotalPrice()));
+			}
+			return vo;
+		}
 //		List<ContractOutBound> outBounds = contractOutBoundMapper.selectList(Wrappers.<ContractOutBound>lambdaQuery()
 //				.in(ContractOutBound::getId, genInvoiceInfoDTO.getOutBoundInvoiceList().stream().map(item->item.getContractOutBoundId()).collect(Collectors.toList())));
-		if (!StrUtil.equals(contract.getContractCategory(), "water_house")){
-			if (ArrayUtil.isNotEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList().toArray())) {
+		if (!StrUtil.equals(contract.getContractCategory(), "water_house")) {
+			if (CollUtil.isNotEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList())) {
 				genInvoiceInfoDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
 					ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
-
-					if (!ArrayUtil.contains(erpCode.toArray(), contractOutBound.getSubjectMatterCode())) {
-						erpCode.add(contractOutBound.getSubjectMatterCode());
+					ContractSubjectMatter subjectMatter = subjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery()
+							.eq(ContractSubjectMatter::getMaterialCode, contractOutBound.getSubjectMatterCode())
+							.eq(StrUtil.isNotBlank(contractOutBound.getLineNo()), ContractSubjectMatter::getLineNo, contractOutBound.getLineNo())
+							.eq(ContractSubjectMatter::getContractId, contract.getId()).last("limit 1"));
+					if (!CollUtil.contains(erpCode, contractOutBound.getSubjectMatterCode() + subjectMatter.getUnitPrice())) {
+						erpCode.add(contractOutBound.getSubjectMatterCode() + subjectMatter.getUnitPrice());
 						ContractOutBoundMergeVo mergeVo = new ContractOutBoundMergeVo();
-						mergeVo.setMaterialCode(contractOutBound.getSubjectMatterCode());
+						mergeVo.setMaterialCode(contractOutBound.getSubjectMatterCode() + subjectMatter.getUnitPrice());
 						mergeVo.setMaterialInternalName(contractOutBound.getSubjectMatterName());
 						mergeVo.setQuantity(contractOutBoundInvoiceVo.getInvoiceNum());
-						Product product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, contractOutBound.getSubjectMatterCode())
-								.eq(Product::getCompId, SecurityUtils.getUser().getCompId()).last("limit 1"));
+						Product product = new Product();
+						List<String> smjList = new ArrayList<>();
+						smjList.add(smj);
+						smjList.add(smjsc);
+						smjList.add(smjzt);
+						smjList.add(smjhw);
+						if (("" + SecurityUtils.getUser().getCompId()).equals(smj) || ("" + SecurityUtils.getUser().getCompId()).equals(smjsc) ||
+								("" + SecurityUtils.getUser().getCompId()).equals(smjzt)||
+								("" + SecurityUtils.getUser().getCompId()).equals(smjhw)) {
+							product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, contractOutBound.getSubjectMatterCode())
+									.in(Product::getCompId, smjList).last("limit 1"));
+						} else {
+							product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, contractOutBound.getSubjectMatterCode())
+									.eq(Product::getCompId, SecurityUtils.getUser().getCompId()).last("limit 1"));
+						}
+
 						if (ObjUtil.isNotNull(product)) {
 							mergeVo.setTaxClass(product.getTaxClass());
 							mergeVo.setSpecification(product.getProductType());
 							mergeVo.setTaxRate(new BigDecimal(product.getTaxRate()));
 							mergeVo.setTaxCode(product.getTaxCode());
-							Product productClass = productMapper.selectById(product.getParentId());
-							if (ObjUtil.isNotNull(product)) {
-								if (StrUtil.equals(product.getErpCode(), "water_bill")) {
-									mergeVo.setItemName("*" + product.getTaxClass() + "*姘磋垂");
-								} else if (StrUtil.equals(product.getErpCode(), "electricity_bill")) {
-									mergeVo.setItemName("*" + product.getTaxClass() + "*鐢佃垂");
-								} else if (StrUtil.equals(product.getErpCode(), "house_rental")) {
-									mergeVo.setItemName("*" + product.getTaxClass() + "*鎴垮眿绉熻祦");
-								} else {
-									mergeVo.setItemName("*" + product.getTaxClass() + "*" + productClass.getProductName());
-								}
-
-							}
 						}
-						ContractSubjectMatter subjectMatter = subjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery()
-								.eq(ContractSubjectMatter::getMaterialCode, contractOutBound.getSubjectMatterCode())
-								.eq(ContractSubjectMatter::getContractId, contract.getId()).last("limit 1"));
 						if (ObjUtil.isNotNull(subjectMatter)) {
 							mergeVo.setUnitPrice(subjectMatter.getUnitPrice());
 							mergeVo.setUnit(subjectMatter.getUnit());
+							if (StrUtil.equals(product.getErpCode(), "water_bill")) {
+								mergeVo.setItemName("*" + product.getTaxClass() + "*姘磋垂");
+							} else if (StrUtil.equals(product.getErpCode(), "electricity_bill")) {
+								mergeVo.setItemName("*" + product.getTaxClass() + "*鐢佃垂");
+							} else if (StrUtil.equals(product.getErpCode(), "house_rental")) {
+								mergeVo.setItemName("*" + product.getTaxClass() + "*鎴垮眿绉熻祦");
+							} else {
+								mergeVo.setItemName("*" + product.getTaxClass() + "*" + subjectMatter.getMaterialName());
+							}
 						}
 						mergeOutBounds.add(mergeVo);
 					} else {
 						List<ContractOutBoundMergeVo> filteredList = mergeOutBounds.stream()
-								.filter(item -> contractOutBound.getSubjectMatterCode().equals(item.getMaterialCode())) // 闃叉绌烘寚閽堬紝寤鸿甯搁噺鍦ㄥ墠
+								.filter(item -> item.getMaterialCode().equals(subjectMatter.getMaterialCode() + subjectMatter.getUnitPrice())) // 闃叉绌烘寚閽堬紝寤鸿甯搁噺鍦ㄥ墠
 								.collect(Collectors.toList());
-						if (ArrayUtil.isNotEmpty(filteredList.toArray())) {
+						if (CollUtil.isNotEmpty(filteredList)) {
 							filteredList.get(0).setQuantity(filteredList.get(0).getQuantity().add(contractOutBound.getOutBoundNum()));
 						}
 					}
 				});
-				if (ArrayUtil.isNotEmpty(mergeOutBounds.toArray())) {
+				if (CollUtil.isNotEmpty(mergeOutBounds)) {
 					invoiceItemVoList = BeanUtil.copyToList(mergeOutBounds, InvoiceItemVo.class);
-					invoiceItemVoList.stream().forEach(invoiceItemVo -> {
+					invoiceItemVoList.stream().filter(invoiceItem -> invoiceItem.getUnitPrice().compareTo(new BigDecimal("0")) > 0)
+							.forEach(invoiceItemVo -> {
 //				for (InvoiceItemVo invoiceItemVo:invoiceItemVoList) {
-						BigDecimal itemPrice = invoiceItemVo.getUnitPrice().multiply(invoiceItemVo.getQuantity());
-						BigDecimal itemPriceTax = itemPrice.divide(new BigDecimal("100").add(invoiceItemVo.getTaxRate()), 2, RoundingMode.HALF_UP).multiply(invoiceItemVo.getTaxRate());
-						invoiceItemVo.setPriceTax(itemPriceTax);
-						invoiceItemVo.setPriceNoTax(itemPrice.subtract(itemPriceTax));
-					});
-					vo.setTotalPrice(invoiceItemVoList.stream().map(item -> item.getPriceTax().add(item.getPriceNoTax())).reduce(BigDecimal.ZERO, BigDecimal::add));
+								BigDecimal itemPrice = invoiceItemVo.getUnitPrice().multiply(invoiceItemVo.getQuantity());
+								BigDecimal itemPriceTax = itemPrice.divide(new BigDecimal("100").add(invoiceItemVo.getTaxRate()), 2, RoundingMode.HALF_UP).multiply(invoiceItemVo.getTaxRate());
+								invoiceItemVo.setPriceTax(itemPriceTax);
+								invoiceItemVo.setPriceNoTax(itemPrice.subtract(itemPriceTax));
+								invoiceItemVo.setPriceAndTax(itemPrice);
+							});
+					vo.setTotalPrice(invoiceItemVoList.stream().map(item -> item.getPriceAndTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
+					vo.setTotalTax(invoiceItemVoList.stream().map(item -> item.getPriceTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
 					vo.setInvoiceItemList(invoiceItemVoList);
 					vo.setPriceWords(Convert.digitToChinese(vo.getTotalPrice()));
 				}
 			}
-		}else {
-			if (ArrayUtil.isNotEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList().toArray())) {
+		} else {
+			if (CollUtil.isNotEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList())) {
 				genInvoiceInfoDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
 					ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
 
-					if (!ArrayUtil.contains(erpCode.toArray(), schedule.getSubjectMatterCode())) {
+					if (!CollUtil.contains(erpCode, schedule.getSubjectMatterCode())) {
 						erpCode.add(schedule.getSubjectMatterCode());
 						ContractOutBoundMergeVo mergeVo = new ContractOutBoundMergeVo();
 						mergeVo.setMaterialCode(schedule.getSubjectMatterCode());
 						mergeVo.setMaterialInternalName(schedule.getSubjectMatterName());
 						mergeVo.setPriceAndTax(schedule.getPlannedAmount());
+						mergeVo.setQuantity(schedule.getInvoiceNum());
 						Product product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, schedule.getSubjectMatterCode())
 								.eq(Product::getCompId, SecurityUtils.getUser().getCompId()).last("limit 1"));
 						if (ObjUtil.isNotNull(product)) {
@@ -235,45 +768,47 @@
 							mergeVo.setSpecification(product.getProductType());
 							mergeVo.setTaxRate(new BigDecimal(product.getTaxRate()));
 							mergeVo.setTaxCode(product.getTaxCode());
-							Product productClass = productMapper.selectById(product.getParentId());
-							if (ObjUtil.isNotNull(product)) {
-								if (StrUtil.equals(product.getErpCode(), "water_bill")) {
-									mergeVo.setItemName("*" + product.getTaxClass() + "*姘磋垂");
-								} else if (StrUtil.equals(product.getErpCode(), "electricity_bill")) {
-									mergeVo.setItemName("*" + product.getTaxClass() + "*鐢佃垂");
-								} else if (StrUtil.equals(product.getErpCode(), "house_rental")) {
-									mergeVo.setItemName("*" + product.getTaxClass() + "*鎴垮眿绉熻祦");
-								} else {
-									mergeVo.setItemName("*" + product.getTaxClass() + "*" + productClass.getProductName());
-								}
-
-							}
 						}
 						ContractSubjectMatter subjectMatter = subjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery()
 								.eq(ContractSubjectMatter::getMaterialCode, schedule.getSubjectMatterCode())
 								.eq(ContractSubjectMatter::getContractId, contract.getId()).last("limit 1"));
 						if (ObjUtil.isNotNull(subjectMatter)) {
 							mergeVo.setUnitPrice(subjectMatter.getUnitPrice());
+							if (StrUtil.equals(product.getErpCode(), "water_bill")) {
+								mergeVo.setItemName("*" + product.getTaxClass() + "*姘磋垂");
+								mergeVo.setUnit("鍚�");
+							} else if (StrUtil.equals(product.getErpCode(), "electricity_bill")) {
+								mergeVo.setItemName("*" + product.getTaxClass() + "*鐢佃垂");
+								mergeVo.setUnit("搴�");
+							} else if (StrUtil.equals(product.getErpCode(), "house_rental")) {
+								mergeVo.setItemName("*" + product.getTaxClass() + "*鎴垮眿绉熻祦");
+							} else {
+								mergeVo.setItemName("*" + product.getTaxClass() + "*" + subjectMatter.getMaterialName());
+							}
+
 						}
 						mergeOutBounds.add(mergeVo);
-					}else {
-						List<ContractOutBoundMergeVo> filterMergeVo = mergeOutBounds.stream().filter(item->item.getMaterialCode()
+					} else {
+						List<ContractOutBoundMergeVo> filterMergeVo = mergeOutBounds.stream().filter(item -> item.getMaterialCode()
 								.equals(schedule.getSubjectMatterCode())).collect(Collectors.toList());
-						if (ArrayUtil.isNotEmpty(filterMergeVo.toArray())){
+						if (CollUtil.isNotEmpty(filterMergeVo)) {
 							filterMergeVo.get(0).setPriceAndTax(schedule.getPlannedAmount().add(filterMergeVo.get(0).getPriceAndTax()));
 						}
 					}
 				});
-				if (ArrayUtil.isNotEmpty(mergeOutBounds.toArray())) {
+				if (CollUtil.isNotEmpty(mergeOutBounds)) {
 					invoiceItemVoList = BeanUtil.copyToList(mergeOutBounds, InvoiceItemVo.class);
-					invoiceItemVoList.stream().forEach(invoiceItemVo -> {
+					invoiceItemVoList.stream().filter(invoiceItem -> invoiceItem.getUnitPrice().compareTo(new BigDecimal("0")) > 0)
+							.forEach(invoiceItemVo -> {
 //				for (InvoiceItemVo invoiceItemVo:invoiceItemVoList) {
-						BigDecimal itemPrice = invoiceItemVo.getPriceAndTax();
-						BigDecimal itemPriceTax = itemPrice.divide(new BigDecimal("100").add(invoiceItemVo.getTaxRate()), 2, RoundingMode.HALF_UP).multiply(invoiceItemVo.getTaxRate());
-						invoiceItemVo.setPriceTax(itemPriceTax);
-						invoiceItemVo.setPriceNoTax(itemPrice.subtract(itemPriceTax));
-					});
+								BigDecimal itemPrice = invoiceItemVo.getPriceAndTax();
+								BigDecimal itemPriceTax = itemPrice.divide(new BigDecimal("100").add(invoiceItemVo.getTaxRate()), 2, RoundingMode.HALF_UP).multiply(invoiceItemVo.getTaxRate());
+								invoiceItemVo.setPriceTax(itemPriceTax);
+								invoiceItemVo.setPriceNoTax(itemPrice.subtract(itemPriceTax));
+
+							});
 					vo.setTotalPrice(invoiceItemVoList.stream().map(item -> item.getPriceAndTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
+					vo.setTotalTax(invoiceItemVoList.stream().map(item -> item.getPriceTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
 					vo.setInvoiceItemList(invoiceItemVoList);
 					vo.setPriceWords(Convert.digitToChinese(vo.getTotalPrice()));
 				}
@@ -282,36 +817,147 @@
 		return vo;
 	}
 
+	private GenInvoiceInfoVo genAdvanceInvoiceInfoVo(GenInvoiceInfoDTO genInvoiceInfoDTO, Contract contract, SysDept b) {
+		GenInvoiceInfoVo vo = new GenInvoiceInfoVo();
+		BusinessCustomer a = businessCustomerMapper.selectById(contract.getPartyAId());
+		vo.setContractId(contract.getId());
+		vo.setAdvanceInvoice("111");
+		vo.setPartyA(genInvoiceInfoDTO.getPartyA());
+		vo.setPartyAOrgCode(genInvoiceInfoDTO.getPartyAOrgCode());
+		vo.setPartyAOpenBank(a.getBankName());
+		vo.setPartyABankAccount(a.getBankAccount());
+		vo.setPartyB(b.getOrgName());
+		vo.setPartyBOrgCode(b.getOrgCode());
+		vo.setPartyBOpenBank(b.getOrgBank());
+		vo.setPartyBBankAccount(b.getOrgBankAccount());
+		vo.setRemarks(genInvoiceInfoDTO.getRemarks());
+		vo.setOutBoundInvoiceList(genInvoiceInfoDTO.getOutBoundInvoiceList());
+		List<InvoiceItemVo> invoiceItemVoList = new ArrayList<>();
+		List<String> erpCode = new ArrayList<>();
+		List<ContractOutBoundMergeVo> mergeOutBounds = new ArrayList<>();
+
+		if (CollUtil.isNotEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList())) {
+			genInvoiceInfoDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
+				ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+				if (ObjUtil.isNotNull(subjectMatter)) {
+					if (!CollUtil.contains(erpCode, subjectMatter.getMaterialCode() + subjectMatter.getUnitPrice())) {
+						erpCode.add(subjectMatter.getMaterialCode());
+						ContractOutBoundMergeVo mergeVo = new ContractOutBoundMergeVo();
+						mergeVo.setMaterialCode(subjectMatter.getMaterialCode());
+						mergeVo.setMaterialInternalName(subjectMatter.getMaterialName());
+						mergeVo.setQuantity(contractOutBoundInvoiceVo.getInvoiceNum());
+						Product product = productMapper.selectOne(Wrappers.<Product>lambdaQuery().eq(Product::getErpCode, subjectMatter.getMaterialCode())
+								.eq(Product::getCompId, SecurityUtils.getUser().getCompId()).last("limit 1"));
+						if (ObjUtil.isNotNull(product)) {
+							mergeVo.setTaxClass(product.getTaxClass());
+							mergeVo.setSpecification(product.getProductType());
+							mergeVo.setTaxRate(new BigDecimal(product.getTaxRate()));
+							mergeVo.setTaxCode(product.getTaxCode());
+						}
+						if (ObjUtil.isNotNull(product)) {
+							if (StrUtil.equals(product.getErpCode(), "water_bill")) {
+								mergeVo.setItemName("*" + product.getTaxClass() + "*姘磋垂");
+								mergeVo.setUnit("鍚�");
+							} else if (StrUtil.equals(product.getErpCode(), "electricity_bill")) {
+								mergeVo.setItemName("*" + product.getTaxClass() + "*鐢佃垂");
+								mergeVo.setUnit("搴�");
+							} else if (StrUtil.equals(product.getErpCode(), "house_rental")) {
+								mergeVo.setItemName("*" + product.getTaxClass() + "*鎴垮眿绉熻祦");
+							} else {
+								mergeVo.setItemName("*" + product.getTaxClass() + "*" + subjectMatter.getMaterialName());
+							}
+
+						}
+						mergeVo.setUnitPrice(subjectMatter.getUnitPrice());
+						mergeVo.setUnit(subjectMatter.getUnit());
+						mergeOutBounds.add(mergeVo);
+					}
+
+				}
+			});
+			if (CollUtil.isNotEmpty(mergeOutBounds)) {
+				invoiceItemVoList = BeanUtil.copyToList(mergeOutBounds, InvoiceItemVo.class);
+				invoiceItemVoList.stream().filter(invoiceItem -> invoiceItem.getUnitPrice().compareTo(new BigDecimal("0")) > 0).forEach(invoiceItemVo -> {
+//				for (InvoiceItemVo invoiceItemVo:invoiceItemVoList) {
+					BigDecimal itemPrice = invoiceItemVo.getUnitPrice().multiply(invoiceItemVo.getQuantity());
+					BigDecimal itemPriceTax = itemPrice.divide(new BigDecimal("100").add(invoiceItemVo.getTaxRate()), 2, RoundingMode.HALF_UP).multiply(invoiceItemVo.getTaxRate());
+					invoiceItemVo.setPriceTax(itemPriceTax);
+					invoiceItemVo.setPriceNoTax(itemPrice.subtract(itemPriceTax));
+					invoiceItemVo.setPriceAndTax(itemPrice);
+				});
+				vo.setTotalPrice(invoiceItemVoList.stream().map(item -> item.getPriceAndTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
+				vo.setTotalTax(invoiceItemVoList.stream().map(item -> item.getPriceTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
+				vo.setInvoiceItemList(invoiceItemVoList);
+				vo.setPriceWords(Convert.digitToChinese(vo.getTotalPrice()));
+			}
+		}
+
+		return vo;
+	}
+
 	@Override
-	public R toInvoice(GenInvoiceInfoDTO genInvoiceInfoDTO) {
-		if (ArrayUtil.isEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList().toArray())) {
-			return R.failed("璇烽�夋嫨寮�绁ㄥ嚭搴撳崟鍚庡啀鎿嶄綔");
-		}
-		Long contractId = null;
-		if (!StrUtil.equals(genInvoiceInfoDTO.getContractCategory(),"water_house")) {
-			ContractOutBound outBound = contractOutBoundMapper.selectById(genInvoiceInfoDTO.getOutBoundInvoiceList().get(0).getContractOutBoundId());
-			contractId = outBound.getContractId();
-		}else {
-			ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectById(genInvoiceInfoDTO.getOutBoundInvoiceList().get(0).getContractOutBoundId());
-			contractId = schedule.getContractId();
-		}
-		Contract contract = contractMapper.selectById(contractId);
+	public R toInvoice(ToInvoiceDTO toInvoiceDTO) {
+		Contract contract = contractMapper.selectById(toInvoiceDTO.getContractId());
 		if (ObjUtil.isNull(contract)) {
 			return R.failed("鍚堝悓淇℃伅寮傚父锛岃鑱旂郴鎶�鏈汉鍛�");
 		}
-		R<SysDept> r = remoteDeptService.getById(contract.getPartyBId());
-		if (!r.isOk()) {
-			return R.failed("鑾峰彇寮�绁ㄥ崟浣嶅紓甯�");
+		if (StrUtil.isNotBlank(toInvoiceDTO.getAdvanceInvoice())) {
+
+			ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectOne(Wrappers.<ContractPaymentSchedule>lambdaQuery()
+					.eq(ContractPaymentSchedule::getStageName, "鍚堝悓绛捐").eq(ContractPaymentSchedule::getContractId, toInvoiceDTO.getContractId())
+					.last("limit 1"));
+			if (ObjUtil.isNull(schedule)) {
+				return R.failed("鍚堝悓棰勬敹娆鹃樁娈靛紓甯革紝璇疯仈绯绘妧鏈汉鍛�");
+			}
+			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")) {
+				return R.failed("璇风瓑寰呮渶杩戠殑鍙戠エ瀹℃牳瀹屾垚鍚庡啀杩涜棰勬敹寮�绁�");
+			}
+			R<SysDept> r = remoteDeptService.getById(contract.getPartyBId());
+			if (!r.isOk()) {
+				return R.failed("鑾峰彇寮�绁ㄥ崟浣嶅紓甯�");
+			}
+			SysDept b = r.getData();
+			BigDecimal advanceAmount = new BigDecimal("0");
+			for (ContractOutBoundInvoiceVo contractOutBoundInvoiceVo : toInvoiceDTO.getOutBoundInvoiceList()) {
+				ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+				if (ObjUtil.isNotNull(subjectMatter)) {
+					advanceAmount = advanceAmount.add(contractOutBoundInvoiceVo.getInvoiceNum().multiply(subjectMatter.getUnitPrice()));
+				}
+			}
+
+			if (advanceAmount.compareTo(schedule.getPlannedAmount()) > 0) {
+				return R.failed("寮�绁ㄩ噾棰濊秴鍑哄悎鍚岀璁㈤樁娈靛簲鏀堕噾棰�:" + schedule.getPlannedAmount() + ",璇疯皟鏁村紑绁ㄦ暟閲�");
+			}
+			GenInvoiceInfoVo vo = BeanUtil.copyProperties(toInvoiceDTO, GenInvoiceInfoVo.class);
+			//鍙戠エ淇濆瓨
+			ContractInvoice invoice = saveContractInvoice(vo, contract, toInvoiceDTO.getOutBoundInvoiceList(), DateUtil.current() + "", "1", null);
+			//鍚姩娴佺▼
+			ProcessInstanceParamDto dto = new ProcessInstanceParamDto();
+			Map<String, Object> map = BeanUtil.beanToMap(invoice);
+			dto.setParamMap(map);
+			dto.setFlowName(FlowNameEnum.閿�鍞寕璐﹀鎵�.name());
+			R r1 = remoteFlowProcessService.startProcessInstance(dto);
+			if (r1.getCode() == 1) {
+				return R.failed("娴佺▼鍚姩澶辫触");
+			}
+			//鏇存柊鍚堝悓鍑哄簱鍗曠姸鎬�
+			toInvoiceDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
+				ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+				subjectMatter.setAdvanceNum(subjectMatter.getAdvanceNum().add(contractOutBoundInvoiceVo.getInvoiceNum()));
+				contractSubjectMatterMapper.updateById(subjectMatter);
+			});
+			return R.ok();
 		}
-		SysDept b = r.getData();
-		GenInvoiceInfoVo vo = genInvoiceInfoVo(genInvoiceInfoDTO, contract, b);
+		GenInvoiceInfoVo vo = BeanUtil.copyProperties(toInvoiceDTO, GenInvoiceInfoVo.class);
 		//鍙戠エ淇濆瓨
-		ContractInvoice invoice = saveContractInvoice(vo, contract, genInvoiceInfoDTO.getOutBoundInvoiceList(), DateUtil.current() + "");
+		ContractInvoice invoice = saveContractInvoice(vo, contract, toInvoiceDTO.getOutBoundInvoiceList(), DateUtil.current() + "", "0", null);
 		//鍚姩娴佺▼
 		ProcessInstanceParamDto dto = new ProcessInstanceParamDto();
 		Map<String, Object> map = BeanUtil.beanToMap(invoice);
-		if (StrUtil.equals(genInvoiceInfoDTO.getContractCategory(),"water_house")) {
-			map.put("contractCategory","water_house");
+		if (StrUtil.equals(toInvoiceDTO.getContractCategory(), "water_house")) {
+			map.put("contractCategory", "water_house");
 		}
 		dto.setParamMap(map);
 		dto.setFlowName(FlowNameEnum.閿�鍞寕璐﹀鎵�.name());
@@ -319,22 +965,48 @@
 		if (r1.getCode() == 1) {
 			return R.failed("娴佺▼鍚姩澶辫触");
 		}
-		if (!StrUtil.equals(contract.getContractCategory(),"water_house")) {
+		if (!StrUtil.equals(contract.getContractCategory(), "water_house")) {
 			//鏇存柊鍚堝悓鍑哄簱鍗曠姸鎬�
-			genInvoiceInfoDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
-				ContractOutBound bound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
-				bound.setInvoiceStatus("1");
-				bound.setInvoiceNum(bound.getInvoiceNum().add(contractOutBoundInvoiceVo.getInvoiceNum()));
-				contractOutBoundMapper.updateById(bound);
+			toInvoiceDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
+				ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+				contractOutBound.setInvoiceStatus("1");
+				contractOutBound.setInvoiceNum(contractOutBound.getInvoiceNum().add(contractOutBoundInvoiceVo.getInvoiceNum()));
+				contractOutBoundMapper.updateById(contractOutBound);
 			});
-		}else {
+		} else {
 			//鏇存柊鍚堝悓鎴跨 姘寸數 璐瑰紑绁ㄧ姸鎬�
-			genInvoiceInfoDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
-					ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
-					schedule.setInvoiceFlag("1");
-					contractPaymentScheduleMapper.updateById(schedule);
-				});
+			toInvoiceDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
+				ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+				schedule.setInvoiceFlag("1");
+				contractPaymentScheduleMapper.updateById(schedule);
+			});
 		}
+		return R.ok();
+	}
+
+	@Override
+	public R toMergeInvoice(ToMergeInvoiceDTO toMergeInvoiceDTO) {
+
+		GenInvoiceInfoVo vo = BeanUtil.copyProperties(toMergeInvoiceDTO, GenInvoiceInfoVo.class);
+		//鍙戠エ淇濆瓨
+		ContractInvoice invoice = saveContractInvoice(vo, null, toMergeInvoiceDTO.getOutBoundInvoiceList(),
+				DateUtil.current() + "", "0", toMergeInvoiceDTO.getContractIds());
+		//鍚姩娴佺▼
+		ProcessInstanceParamDto dto = new ProcessInstanceParamDto();
+		Map<String, Object> map = BeanUtil.beanToMap(invoice);
+		dto.setParamMap(map);
+		dto.setFlowName(FlowNameEnum.閿�鍞寕璐﹀鎵�.name());
+		R r1 = remoteFlowProcessService.startProcessInstance(dto);
+		if (r1.getCode() == 1) {
+			return R.failed("娴佺▼鍚姩澶辫触");
+		}
+		//鏇存柊鍚堝悓鍑哄簱鍗曠姸鎬�
+		toMergeInvoiceDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
+			ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+			contractOutBound.setInvoiceStatus("1");
+			contractOutBound.setInvoiceNum(contractOutBound.getInvoiceNum().add(contractOutBoundInvoiceVo.getInvoiceNum()));
+			contractOutBoundMapper.updateById(contractOutBound);
+		});
 		return R.ok();
 	}
 
@@ -348,17 +1020,16 @@
 		bwRequestRecordMapper.insert(bwRequestRecord);
 	}
 
-	private JSONObject genBlueInvoice(GenInvoiceInfoVo vo, String serialNo) {
+	private JSONObject genBlueInvoice(GenInvoiceInfoVo vo, String serialNo, SysDept dept) {
 		JSONObject jsonObject = new JSONObject();
 		//閿�鏂�
 		jsonObject.put("taxNo", vo.getPartyBOrgCode());//绋庡彿
 		jsonObject.put("isSplit", false);//瓒呰繃鍙戠エ鍗曞紶闄愰鏄惁闇�瑕佹媶鍒嗗紑鍏凤紝榛樿涓嶆媶鍒嗭紙鎷嗗垎鍙敮鎸佸彂绁ㄧ被鍨嬩唬鐮佷负 涓撶エ 004 鏅エ 007 鐢靛瓙绁� 026鐨�
-		jsonObject.put("taxUserName", "");//鐧诲綍鍚嶄负绋庡眬椤甸潰鐧�		褰曞悕
 		jsonObject.put("formatGenerate", false);//鏄惁闇�瑕佺敓鎴愮増寮忚繑鍥炵増寮忛摼鎺�(true / false)
 		jsonObject.put("formatPushType", false);//鐗堝紡鐢熸垚鏄惁鎺ㄩ��(true / false)
 		//data
 		JSONObject data = new JSONObject();
-		data.put("invoiceTypeCode", "01");
+		data.put("invoiceTypeCode", vo.getInvoiceType());
 		data.put("serialNo", serialNo);
 		//data.invoiceDetailsList
 		JSONArray invoiceDetailsList = new JSONArray();
@@ -367,44 +1038,56 @@
 			JSONObject invoiceDetail = new JSONObject();
 
 			invoiceDetail.put("goodsLineNo", lineNo);
+			invoiceDetail.put("goodsName", invoiceItemVo.getItemName());
+			invoiceDetail.put("projectName", invoiceItemVo.getItemName());
 			invoiceDetail.put("goodsCode", invoiceItemVo.getTaxCode());
 			invoiceDetail.put("goodsTaxRate", invoiceItemVo.getTaxRate().divide(new BigDecimal("100")));
 			invoiceDetail.put("goodsUnit", invoiceItemVo.getUnit());
 			invoiceDetail.put("goodsQuantity", invoiceItemVo.getQuantity());
-			invoiceDetail.put("goodsPrice", invoiceItemVo.getUnitPrice());
-			if (!StrUtil.equals(vo.getContractCategory(),"water_house")) {
-				invoiceDetail.put("goodsTotalPrice", invoiceItemVo.getUnitPrice().multiply(invoiceItemVo.getQuantity()));
-			}else {
-				invoiceDetail.put("goodsTotalPrice", invoiceItemVo.getPriceAndTax());
+//			invoiceDetail.put("goodsPrice", invoiceItemVo.getUnitPrice());
+			if (StrUtil.equals(vo.getInvoiceVehicleType(), "3")) {
+				invoiceDetail.put("goodsSpecification", vo.getVehicleNo());
+			} else {
+				invoiceDetail.put("goodsSpecification", invoiceItemVo.getSpecification());
+			}
+
+			if (!StrUtil.equals(vo.getContractCategory(), "water_house")) {
+				invoiceDetail.put("goodsTotalPrice", invoiceItemVo.getPriceNoTax());
+			} else {
+				invoiceDetail.put("goodsTotalPrice", invoiceItemVo.getPriceNoTax());
 			}
 			invoiceDetail.put("goodsTotalTax", invoiceItemVo.getPriceTax());
 
 			invoiceDetailsList.add(invoiceDetail);
 			lineNo++;
 		}
-		jsonObject.put("invoiceDetailsList", invoiceDetailsList);
+		data.put("invoiceDetailsList", invoiceDetailsList);
 		//璐柟
 		data.put("buyerTaxNo", vo.getPartyAOrgCode());
 		data.put("buyerName", vo.getPartyA());
-		data.put("invoiceTotalPrice", vo.getTotalPrice().subtract(vo.getInvoiceItemList().stream().map(item -> item.getPriceTax()).reduce(BigDecimal.ZERO, BigDecimal::add)));
-		data.put("invoiceTotalTax", vo.getInvoiceItemList().stream().map(item -> item.getPriceTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
+		data.put("drawer", dept.getInvoiceContact());// TODO 绋庡姟鎬诲眬绯荤粺鐧婚檰浜烘墜鏈哄彿
 		data.put("invoiceTotalPriceTax", vo.getTotalPrice());
 		data.put("buyerBankName", vo.getPartyAOpenBank());
 		data.put("buyerBankNumber", vo.getPartyABankAccount());
-
+		data.put("remarks", vo.getRemarks());
 		jsonObject.put("data", data);
 		return jsonObject;
 	}
 
-	private ContractInvoice saveContractInvoice(GenInvoiceInfoVo genInvoiceInfoVo, Contract contract, List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList, String serialNo) {
+	private ContractInvoice saveContractInvoice(GenInvoiceInfoVo genInvoiceInfoVo, Contract contract,
+												List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList, String serialNo, String advanceFlag,
+												List<String> contractIds) {
 		ContractInvoice invoice = new ContractInvoice();
-		invoice.setContractId(contract.getId());
+		if (ObjUtil.isNotNull(contract)) {
+			invoice.setContractId(contract.getId());
+		}
 		invoice.setInvoiceCategory("1");
 		invoice.setRedReversal("0");
 		invoice.setSerialNo(serialNo);
-		invoice.setTexNo(genInvoiceInfoVo.getPartyBOrgCode());
+		invoice.setTaxNo(genInvoiceInfoVo.getPartyBOrgCode());
 		invoice.setSellerTaxName(genInvoiceInfoVo.getPartyB());
 		invoice.setBuyerTaxName(genInvoiceInfoVo.getPartyA());
+		invoice.setBuyerTaxNo(genInvoiceInfoVo.getPartyAOrgCode());
 		invoice.setInvoiceTotalTax(genInvoiceInfoVo.getInvoiceItemList().stream().map(item -> item.getPriceTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
 		invoice.setInvoiceTotalPrice(genInvoiceInfoVo.getTotalPrice().subtract(invoice.getInvoiceTotalTax()));
 		invoice.setInvoiceTotalPriceTax(genInvoiceInfoVo.getTotalPrice());
@@ -412,9 +1095,14 @@
 		invoice.setInvoiceStatus("1");
 		invoice.setApprovalStatus("0");
 		invoice.setOutBoundId(outBoundInvoiceVoList.stream()
-				.map(item-> String.valueOf(item.getContractOutBoundId())) // 鎴栬�� .map(Object::toString)
+				.map(item -> String.valueOf(item.getContractOutBoundId())) // 鎴栬�� .map(Object::toString)
 				.collect(Collectors.joining(",")));
 		invoice.setInvoicePreviewParam(JSONObject.toJSONString(outBoundInvoiceVoList));
+		invoice.setAdvanceFlag(advanceFlag);
+		if (CollUtil.isNotEmpty(contractIds)) {
+			invoice.setIsMerge(true);
+			invoice.setContractIds(contractIds.toString());
+		}
 		baseMapper.insert(invoice);
 		return invoice;
 	}
@@ -423,29 +1111,47 @@
 	public R getContractInvoiceList(Long contractId) {
 		List<ContractInvoice> invoiceList = baseMapper.selectList(Wrappers.<ContractInvoice>lambdaQuery()
 				.eq(ContractInvoice::getContractId, contractId)
+				.or()
+				.like(ContractInvoice::getContractIds, contractId)
 				.orderByDesc(ContractInvoice::getCreateTime));
 		return R.ok(invoiceList);
 	}
 
 	@Override
 	public R toRedInvoice(Long invoiceId) {
-
 		ContractInvoice blueInvoice = baseMapper.selectById(invoiceId);
 		blueInvoice.setRedReversal("2");
 		baseMapper.updateById(blueInvoice);
-		Contract contract = contractMapper.selectById(blueInvoice.getContractId());
 		ContractInvoice invoice = new ContractInvoice();
-		invoice.setContractId(blueInvoice.getContractId());
-		invoice.setTexNo(blueInvoice.getTexNo());
+		if (!blueInvoice.getIsMerge()) {
+			invoice.setContractId(blueInvoice.getContractId());
+		}
+		if (blueInvoice.getIsMerge()) {
+			invoice.setContractIds(blueInvoice.getContractIds());
+			invoice.setIsMerge(true);
+		}
+		invoice.setTaxNo(blueInvoice.getTaxNo());
 		invoice.setSellerTaxName(blueInvoice.getSellerTaxName());
 		invoice.setBuyerTaxName(blueInvoice.getBuyerTaxName());
+		invoice.setBuyerTaxNo(blueInvoice.getBuyerTaxNo());
 		invoice.setInvoiceTotalTax(blueInvoice.getInvoiceTotalTax());
 		invoice.setInvoiceTotalPrice(blueInvoice.getInvoiceTotalPrice());
 		invoice.setInvoiceTotalPriceTax(blueInvoice.getInvoiceTotalPriceTax());
-		invoice.setInvoicePreview(blueInvoice.getInvoicePreview());
-		invoice.setInvoiceTotalTax(blueInvoice.getInvoiceTotalTax());
-		invoice.setInvoiceTotalPrice(blueInvoice.getInvoiceTotalPrice());
-		invoice.setInvoiceTotalPriceTax(blueInvoice.getInvoiceTotalPriceTax());
+
+		ToInvoiceDTO toInvoiceDTO = BeanUtil.copyProperties(JSONObject.parseObject(blueInvoice.getInvoicePreview()), ToInvoiceDTO.class);
+		toInvoiceDTO.setTotalPrice(toInvoiceDTO.getTotalPrice().multiply(new BigDecimal(-1)));
+		toInvoiceDTO.setTotalTax(toInvoiceDTO.getTotalTax().multiply(new BigDecimal(-1)));
+		if (CollUtil.isNotEmpty(toInvoiceDTO.getInvoiceItemList())) {
+			toInvoiceDTO.getInvoiceItemList().stream().forEach(item -> {
+				item.setPriceTax(item.getPriceTax().multiply(new BigDecimal("-1")));
+				item.setPriceNoTax(item.getPriceNoTax().multiply(new BigDecimal("-1")));
+				item.setPriceAndTax(item.getPriceAndTax().multiply(new BigDecimal("-1")));
+			});
+		}
+		invoice.setInvoicePreview(JSONObject.toJSONString(toInvoiceDTO));
+		invoice.setInvoiceTotalTax(blueInvoice.getInvoiceTotalTax().multiply(new BigDecimal("-1")));
+		invoice.setInvoiceTotalPrice(blueInvoice.getInvoiceTotalPrice().multiply(new BigDecimal("-1")));
+		invoice.setInvoiceTotalPriceTax(blueInvoice.getInvoiceTotalPriceTax().multiply(new BigDecimal("-1")));
 		invoice.setOutBoundId(blueInvoice.getOutBoundId());
 		invoice.setInvoiceTime(new Date());
 		invoice.setInvoiceCategory("2");
@@ -455,13 +1161,17 @@
 		invoice.setBlueInvoiceId(invoiceId);
 		invoice.setApprovalStatus("0");
 		invoice.setInvoicePreviewParam(blueInvoice.getInvoicePreviewParam());
+		invoice.setAdvanceFlag(blueInvoice.getAdvanceFlag());
 		baseMapper.insert(invoice);
 		//鍚姩娴佺▼
 		ProcessInstanceParamDto dto = new ProcessInstanceParamDto();
 		Map<String, Object> map = BeanUtil.beanToMap(invoice);
 		dto.setParamMap(map);
-		if (StrUtil.equals(contract.getContractCategory(),"water_house")) {
-			map.put("contractCategory","water_house");
+		if (!blueInvoice.getIsMerge()) {
+			Contract contract = contractMapper.selectById(blueInvoice.getContractId());
+			if (StrUtil.equals(contract.getContractCategory(), "water_house")) {
+				map.put("contractCategory", "water_house");
+			}
 		}
 		dto.setParamMap(map);
 		dto.setFlowName(FlowNameEnum.閿�鍞寕璐﹀鎵�.name());
@@ -473,42 +1183,43 @@
 		return R.ok();
 	}
 
-	private JSONObject genRedInvoice(Contract contract,ContractInvoice blueInvoice, String redConfirmSerialNo) {
+	private JSONObject genRedInvoice(ContractInvoice blueInvoice, ContractInvoice redInvoice, String redConfirmSerialNo) {
 		JSONObject jsonObject = new JSONObject();
-		jsonObject.put("taxNo", blueInvoice.getTexNo());
+		jsonObject.put("taxNo", redInvoice.getTaxNo());
 		jsonObject.put("redConfirmSerialNo", redConfirmSerialNo);
 		jsonObject.put("entryIdentity", "01");
-		jsonObject.put("sellerTaxNo", blueInvoice.getTexNo());
-		jsonObject.put("sellerTaxName", blueInvoice.getSellerTaxName());
-		jsonObject.put("buyerTaxName", blueInvoice.getBuyerTaxName());
-		jsonObject.put("originalInvoiceNo", blueInvoice.getInvoiceNo());
+		jsonObject.put("sellerTaxNo", redInvoice.getTaxNo());
+		jsonObject.put("sellerTaxName", redInvoice.getSellerTaxName());
+		jsonObject.put("buyerTaxName", redInvoice.getBuyerTaxName());
+		jsonObject.put("buyerTaxNo", redInvoice.getBuyerTaxNo());
+		jsonObject.put("originInvoiceDate", DateUtil.formatDateTime(blueInvoice.getInvoiceTime()));
+		jsonObject.put("originInvoiceTotalPrice", redInvoice.getInvoiceTotalPriceTax());
+		jsonObject.put("originInvoiceTotalTax", redInvoice.getInvoiceTotalTax());
+		jsonObject.put("invoiceTotalPrice", redInvoice.getInvoiceTotalPrice());
+		jsonObject.put("invoiceTotalTax", redInvoice.getInvoiceTotalTax());
 		jsonObject.put("originInvoiceIsPaper", "N");
-		jsonObject.put("originInvoiceDate", blueInvoice.getInvoiceTime());
-		jsonObject.put("originInvoiceTotalPrice", blueInvoice.getInvoiceTotalPrice());
-		jsonObject.put("originInvoiceTotalTax", blueInvoice.getInvoiceTotalPrice());
 		jsonObject.put("originInvoiceType", "01");
-		jsonObject.put("invoiceTotalPrice", blueInvoice.getInvoiceTotalPrice());
-		jsonObject.put("invoiceTotalTax", blueInvoice.getInvoiceTotalPrice());
-		jsonObject.put("redInvoiceLabel", "2");
-		GenInvoiceInfoVo vo = BeanUtil.copyProperties(JSONObject.parseObject(blueInvoice.getInvoicePreview()), GenInvoiceInfoVo.class);
+		jsonObject.put("redInvoiceLabel", "01");
+		jsonObject.put("invoiceSource", "2");
+		jsonObject.put("originalInvoiceNo", blueInvoice.getInvoiceNo());
+		GenInvoiceInfoVo vo = BeanUtil.copyProperties(JSONObject.parseObject(redInvoice.getInvoicePreview()), GenInvoiceInfoVo.class);
 		JSONArray invoiceDetailsList = new JSONArray();
 		Integer lineNo = 1;
 		for (InvoiceItemVo invoiceItemVo : vo.getInvoiceItemList()) {
 			JSONObject invoiceDetail = new JSONObject();
 			invoiceDetail.put("originalInvoiceDetailNo", lineNo);
+			invoiceDetail.put("projectName", invoiceItemVo.getItemName());
 			invoiceDetail.put("goodsLineNo", lineNo);
 			invoiceDetail.put("goodsCode", invoiceItemVo.getTaxCode());
-			invoiceDetail.put("goodsTaxRate", invoiceItemVo.getTaxRate().divide(new BigDecimal("100")));
+			invoiceDetail.put("goodsTaxRate", invoiceItemVo.getTaxRate());
 			invoiceDetail.put("goodsUnit", invoiceItemVo.getUnit());
 			invoiceDetail.put("goodsQuantity", invoiceItemVo.getQuantity());
-			invoiceDetail.put("goodsPrice", invoiceItemVo.getUnitPrice());
-			if (!StrUtil.equals(contract.getContractCategory(),"water_house")) {
-				invoiceDetail.put("goodsTotalPrice", invoiceItemVo.getUnitPrice().multiply(invoiceItemVo.getQuantity()));
-			}else {
-				invoiceDetail.put("goodsTotalPrice", invoiceItemVo.getPriceAndTax());
-			}
+//			invoiceDetail.put("goodsPrice", invoiceItemVo.getUnitPrice());
+			invoiceDetail.put("goodsTotalPrice", invoiceItemVo.getPriceNoTax());
 			invoiceDetail.put("goodsTotalTax", invoiceItemVo.getPriceTax());
-
+			if (StrUtil.isNotBlank(vo.getInvoiceVehicleType()) && (vo.getInvoiceVehicleType().equals("3") || vo.getInvoiceVehicleType().equals("4"))) {
+				invoiceDetail.put("goodsSpecification", invoiceItemVo.getSpecification());
+			}
 			invoiceDetailsList.add(invoiceDetail);
 			lineNo++;
 		}
@@ -521,32 +1232,157 @@
 	public R queryBlueInvoice() {
 		if (bwFlag) {
 			List<ContractInvoice> contractInvoices = baseMapper.selectList(Wrappers.<ContractInvoice>lambdaQuery()
-					.eq(ContractInvoice::getInvoiceCategory, "1").eq(ContractInvoice::getInvoiceStatus, "1"));
-			if (ArrayUtil.isNotEmpty(contractInvoices.toArray())) {
+					.eq(ContractInvoice::getApprovalStatus, "1")
+					.eq(ContractInvoice::getBwRequestResult, "1")
+					.isNull(ContractInvoice::getInvoicePath));
+			if (CollUtil.isNotEmpty(contractInvoices)) {
 				contractInvoices.stream().forEach(contractInvoice -> {
 					JSONObject request = new JSONObject();
-					request.put("tax_no", contractInvoice.getTexNo());
+					request.put("taxNo", contractInvoice.getTaxNo());
 					JSONObject data = new JSONObject();
-					data.put("serial_no", contractInvoice.getSerialNo());
-					data.put("return_type", "1");
+					data.put("serialNo", contractInvoice.getSerialNo());
+					data.put("returnType", "3");
+					data.put("invoiceIssueMode", "1");
+					request.put("data", data);
 					String requestId = IdUtil.fastUUID();
+
 					log.info("serial_no:{},鍙戠エ鏌ヨ鍏ュ弬锛歿},", contractInvoice.getSerialNo(), request.toJSONString());
-					String result = HttpUtil.post("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);
 					if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) && resultObj.getBoolean("success")) {
 						JSONObject model = resultObj.getJSONObject("model");
-						contractInvoice.setInvoicePath(model.getString("query_data"));
+						contractInvoice.setInvoicePath(model.getString("queryData"));
 						contractInvoice.setInvoiceStatus("2");
 						baseMapper.updateById(contractInvoice);
+						//浼犺緭闄勪欢
+//						pushBipInvoicePdf(contractInvoice);
 					}
-					//鎺ㄩ�丅IP
-					pushBipInvoice(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. 瑙g爜 Base64 涓哄瓧鑺傛暟缁�
+		byte[] fileBytes = Base64.getDecoder().decode(base64Str);
+
+		File file = new File(targetPath);
+
+		// 1. 鑾峰彇鐖剁洰褰曞璞�
+		File parentDir = file.getParentFile();
+
+		// 2. 濡傛灉鐖剁洰褰曚笉涓虹┖涓斾笉瀛樺湪锛屽垯鍒涘缓鎵�鏈夊繀闇�鐨勭埗鐩綍
+		if (parentDir != null && !parentDir.exists()) {
+			// mkdirs() 浼氶�掑綊鍒涘缓鎵�鏈変笉瀛樺湪鐨勭埗鐩綍
+			// 蹇呴』妫�鏌ヨ繑鍥炲�硷紝鍥犱负鍙兘鍥犳潈闄愪笉瓒虫垨璺緞闈炴硶鑰屽け璐�
+			if (!parentDir.mkdirs()) {
+				// 濡傛灉 mkdirs 杩斿洖 false锛屽啀娆℃鏌ユ槸鍚﹀瓨鍦紙澶勭悊骞跺彂鎯呭喌锛�
+				if (!parentDir.exists()) {
+					log.error("鏃犳硶鍒涘缓鐖剁洰褰�: " + parentDir.getAbsolutePath());
+				}
+			}
+		}
+
+		// 3. 鍒涘缓鏂囦欢鏈韩
+		// createNewFile() 浠呭湪鏂囦欢涓嶅瓨鍦ㄦ椂鍒涘缓锛屽鏋滃凡瀛樺湪鍒欒繑鍥� false 浣嗕笉鎶ラ敊
+		if (!file.exists()) {
+			boolean created = false;
+			try {
+				created = file.createNewFile();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+			if (!created) {
+				// 澶勭悊骞跺彂鍒涘缓澶辫触鎴栧叾浠栧紓甯�
+				log.error("鏃犳硶鍒涘缓鏂囦欢: " + file.getAbsolutePath());
+			}
+		}
+
+		// 3. 灏嗗瓧鑺傛暟缁勫啓鍏ユ枃浠�
+		try (FileOutputStream fos = new FileOutputStream(file)) {
+			fos.write(fileBytes);
+			fos.flush();
+			System.out.println("鏂囦欢淇濆瓨鎴愬姛: " + targetPath);
+		} catch (IOException e) {
+			e.printStackTrace();
+			throw new RuntimeException("鏂囦欢淇濆瓨澶辫触", e);
+		}
 	}
 
 	private void pushBipInvoice(ContractInvoice contractInvoice) {
@@ -554,22 +1390,45 @@
 		if (redisTemplate.hasKey("BIP_TOKEN")) {
 			accessToken = (String) redisTemplate.opsForValue().get("BIP_TOKEN");
 		} else {
-			paymentConfirmService.getAccessToken(accessToken);
+			accessToken = paymentConfirmService.getAccessToken(accessToken);
 		}
 		if (StrUtil.isEmpty(accessToken)) {
 			log.error("bip accessToken 鑾峰彇寮傚父");
 			return;
 		}
+		Contract contract = contractMapper.selectById(contractInvoice.getContractId());
+		if (ObjUtil.isNull(contract)) {
+			log.error("鏌ヨ鍚堝悓淇℃伅寮傚父");
+			return;
+		}
+		BusinessCustomer customer = businessCustomerMapper.selectById(contract.getPartyAId());
+		if (ObjUtil.isNull(customer) || StrUtil.isEmpty(customer.getBipCode())) {
+			log.error("鏌ヨ鍚堝悓淇℃伅寮傚父");
+			return;
+		}
+		R<SysDept> r = remoteDeptService.getById(contract.getPartyBId());
+		if (!r.isOk()) {
+			log.error("鏌ヨ鍗曚綅淇℃伅寮傚父");
+			return;
+		}
+		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);
+		if (StrUtil.equals(contractInvoice.getInvoiceCategory(), "1")) {
+
+			JSONObject params = genBlueReceiveParams(contractInvoice, contract, customer, comp, dept);
 			String finalAccessToken = accessToken;
 
-			log.info("XSJZ_YS_DJ_INSERT Request:", params.toJSONString());
-			String result = HttpUtil.post(url + "/yonbip/EFI/receivable/save?access_token=" + finalAccessToken, params.toJSONString());
-			log.info("XSJZ_YS_DJ_INSERT Response:{}", result);
+			log.info("搴旀敹鍙戠エ闆嗘垚鍏ュ弬:{}", params.toJSONString());
+			String result = HttpUtil.post(url + "/yonbip/EFI/receivable/saveandsubmit?access_token=" + finalAccessToken, params.toJSONString());
+			log.info("搴旀敹鍙戠エ闆嗘垚鍥炲弬:{}", result);
 			//淇濆瓨璇锋眰璁板綍
-			paymentConfirmService.saveBipRequestRecord(params, "< XSJZ_YS_DJ_001>-搴旀敹鍙戠エ淇濆瓨鎺ュ彛", result);
+			paymentConfirmService.saveBipRequestRecord(params, "搴旀敹鍙戠エ闆嗘垚鎺ュ彛", result);
 			JSONObject resultJson = JSONObject.parseObject(result);
 			if (resultJson.containsKey("code") && resultJson.getString("code").equals("200")) {
 				JSONObject data = resultJson.getJSONObject("data");
@@ -580,60 +1439,127 @@
 			}
 		}
 		//绾㈢エ
-		if (StrUtil.equals(contractInvoice.getInvoiceCategory(),"2")) {
+		if (StrUtil.equals(contractInvoice.getInvoiceCategory(), "2")) {
 			JSONObject params = genRedReceiveParams(contractInvoice);
 			String finalAccessToken = accessToken;
 
-			log.info("XSJZ_YS_DJ_DELETE Request:", params.toJSONString());
+			log.info("搴旀敹鍙戠エ鍒犻櫎鍏ュ弬:{}", params.toJSONString());
 			String result = HttpUtil.post(url + "/yonbip/EFI/receivable/delete?access_token=" + finalAccessToken, params.toJSONString());
-			log.info("XSJZ_YS_DJ_DELETE Response:{}", result);
+			log.info("搴旀敹鍙戠エ鍒犻櫎鍥炲弬:{}", result);
 			//淇濆瓨璇锋眰璁板綍
-			paymentConfirmService.saveBipRequestRecord(params, "< XSJZ_YS_DJ_002>-搴旀敹鍙戠エ鍒犻櫎鎺ュ彛", 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);
 			}
 		}
 	}
 
 	private JSONObject genRedReceiveParams(ContractInvoice contractInvoice) {
+		ContractInvoice blue = contractInvoice.selectById(contractInvoice.getBlueInvoiceId());
 		JSONObject jsonObject = new JSONObject();
 		JSONObject data = new JSONObject();
-		data.put("id",contractInvoice.getBipId());
-		jsonObject.put("data",data);
-		return  jsonObject;
+		data.put("id", blue.getBipId());
+		jsonObject.put("data", data);
+		return jsonObject;
 	}
 
-	private JSONObject genBlueReceiveParams(ContractInvoice contractInvoice) {
+	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")){
-			data.put("direction","1");
-		}else {
-			data.put("direction","-1");
+		if (contractInvoice.getInvoiceCategory().equals("1")) {
+			data.put("direction", "1");
+		} else {
+			data.put("direction", "-1");
 		}
-		data.put("billDate",DateUtil.format(contractInvoice.getInvoiceTime(),DatePattern.NORM_DATETIME_FORMAT));
-		data.put("objectType","1");
-		data.put("exchangeRate","1");
-		data.put("exchangeRate",DateUtil.now());
-		data.put("_status","Insert");
+		data.put("billDate", DateUtil.format(contractInvoice.getInvoiceTime(), DatePattern.NORM_DATETIME_FORMAT));
+		data.put("exchangeRate", "1");//姹囩巼
+		data.put("exchangeRateDate", DateUtil.now());//姹囩巼鏃堕棿
+		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", comp.getBipCode());//寮�绁ㄧ粍缁囩紪鐮�
+		data.put("orgCode", comp.getBipCode());//涓氬姟缁勭粐缂栫爜
+		data.put("bustypeCode", "ZBYXGLXT");//浜ゆ槗绫诲瀷缂栫爜 鏆備及榛樿ZGYSFP锛岄攢鍞粯璁BYXGLXT
+		data.put("contractNo", contract.getContractNo());
+		data.put("oriCurrencyCode", "CNY");//甯佺
+
+		data.put("_status", "Insert");
 		GenInvoiceInfoVo vo = BeanUtil.copyProperties(JSONObject.parseObject(contractInvoice.getInvoicePreview()), GenInvoiceInfoVo.class);
 		JSONArray bodyItem = new JSONArray();
-		for (InvoiceItemVo invoiceItemVo : vo.getInvoiceItemList()) {
+		for (InvoiceItemVo invoiceItemVo : vo.getBipVo().getItemList()) {
 			JSONObject item = new JSONObject();
-			item.put("invoiceNo",contractInvoice.getInvoiceNo());
-			item.put("materialCode",invoiceItemVo.getErpCode());
+			item.put("expenseItemCode", invoiceItemVo.getJjsx());//缁忔祹浜嬮」
+			item.put("invoiceNo", contractInvoice.getInvoiceNo());
 			item.put("taxRate", invoiceItemVo.getTaxRate());
 			item.put("oriTaxAmount", invoiceItemVo.getPriceTax());
-			item.put("oriTaxIncludedAmount", invoiceItemVo.getUnitPrice().multiply(invoiceItemVo.getQuantity()));
-			item.put("_status","Insert");
+			item.put("oriTaxIncludedAmount", invoiceItemVo.getPriceAndTax());
+			item.put("remarks", invoiceItemVo.getZy());//鎽樿
+			item.put("_status", "Insert");
+			JSONObject freeChId = new JSONObject();
+			freeChId.put("GX08", invoiceItemVo.getHsdy());//鏍哥畻鍗曞厓
+			freeChId.put("YSYF14", "2");//娆鹃」绫诲瀷 1 棰勬敹娆� 2 搴旀敹娆�
+			freeChId.put("YSYF31", invoiceItemVo.getSfjs());//鏄惁璁$◣
+			freeChId.put("JT04", invoiceItemVo.getHsjylx());//鏍哥畻浜ゆ槗绫诲瀷 0101 闆嗗洟澶栭儴 01020301 涓夌骇鍒嗗瓙鍏徃闂� 01020302 涓夌骇鍒嗗叕鍙镐笌瀛愬瓙鍏徃涔嬮棿
+			freeChId.put("JT06", invoiceItemVo.getKxmx());//娆鹃」鏄庣粏
+			freeChId.put("JT32", invoiceItemVo.getZyys());//浣滀笟瑕佺礌
+			freeChId.put("zzbkfl", invoiceItemVo.getBkfl());//鏉垮潡鍒嗙被
+			freeChId.put("JT12", invoiceItemVo.getCpwlfl());//浜у搧鐗╂枡鍒嗙被
 
+			item.put("freeChId", freeChId);
 			bodyItem.add(item);
 		}
-		data.put("bodyItem",bodyItem);
-		jsonObject.put("data",data);
-		return  jsonObject;
+		data.put("bodyItem", bodyItem);
+		JSONObject freeChId = new JSONObject();
+		freeChId.put("YSYF_SFZY", vo.getBipVo().getSfzy());//鏄惁涓昏惀
+		freeChId.put("fk_038", vo.getBipVo().getPzzdr());//鍑瘉鍒跺崟浜�
+		freeChId.put("YSYF_08", vo.getBipVo().getSfnbwl());//鏄惁鍐呴儴寰�鏉�
+		freeChId.put("YSYF24", vo.getBipVo().getSfjyjs());//鏄惁绠�鏄撹绋�
+		freeChId.put("fk_002", vo.getBipVo().getFjzs());//闄勪欢1
+		freeChId.put("GX08", vo.getBipVo().getHsdy());//鏍哥畻鍗曞厓
+		freeChId.put("TzMY042", contract.getExpirationDate());//棰勮鍥炴鏃ユ湡
+		data.put("freeChId", freeChId);
+		data.put("remarks", vo.getBipVo().getZy());//鎽樿
+		jsonObject.put("data", data);
+		return jsonObject;
+	}
+
+	private String transEconomic(String economicMatters) {
+		if (economicMatters.equals("1")) {
+			return "09001006";
+		}
+		if (economicMatters.equals("2")) {
+			return "09004003";
+		}
+		if (economicMatters.equals("3")) {
+			return "09003005";
+		}
+		if (economicMatters.equals("4")) {
+			return "09002042";
+		}
+		if (economicMatters.equals("5")) {
+			return "09002002";
+		}
+		if (economicMatters.equals("6")) {
+			return "09004001";
+		}
+		if (economicMatters.equals("7")) {
+			return "09003002001";
+		}
+		if (economicMatters.equals("8")) {
+			return "09003002002";
+		}
+		if (economicMatters.equals("9")) {
+			return "09003002003";
+		}
+		if (economicMatters.equals("10")) {
+			return "09003003";
+		}
+		return "";
 	}
 
 	@Override
@@ -641,27 +1567,38 @@
 		if (bwFlag) {
 			List<ContractInvoice> contractInvoices = baseMapper.selectList(Wrappers.<ContractInvoice>lambdaQuery()
 					.eq(ContractInvoice::getInvoiceCategory, "2").eq(ContractInvoice::getInvoiceStatus, "3"));
-			if (ArrayUtil.isNotEmpty(contractInvoices.toArray())) {
+			if (CollUtil.isNotEmpty(contractInvoices)) {
 				contractInvoices.stream().forEach(contractInvoice -> {
 					JSONObject request = new JSONObject();
-					request.put("taxNo", contractInvoice.getTexNo());
-					JSONObject data = new JSONObject();
-					data.put("redConfirmSerialNo", contractInvoice.getSerialNo());
-					data.put("buySelSelector", "1");
+					request.put("taxNo", contractInvoice.getTaxNo());
+					request.put("redConfirmSerialNo", contractInvoice.getSerialNo());
+					request.put("buySelSelector", "0");
+					request.put("invoiceStartDate", DateUtil.formatDate(DateUtil.beginOfYear(new Date())));
+					request.put("invoiceEndDate", DateUtil.formatDate(DateUtil.endOfYear(new Date())));
 					String requestId = IdUtil.fastUUID();
 					log.info("serial_no:{},绾㈠瓧纭鍗曟煡璇㈠叆鍙傦細{},", contractInvoice.getSerialNo(), request.toJSONString());
 					String result = HttpUtil.post("method=baiwang.output.redinvoice.formlist&&version=1.0&request_id=" + requestId, request.toJSONString());
 					log.info("serial_no:{},绾㈠瓧纭鍗曟煡璇㈠洖鍙傦細{},", contractInvoice.getSerialNo(), result);
 					JSONObject resultObj = JSONObject.parseObject(result);
 					saveBwRequestRecord("baiwang.output.redinvoice.formlist", requestId, request.toJSONString(), result);
-					if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) && resultObj.getBoolean("success")) {
-						JSONArray models = JSONArray.parseArray(resultObj.getString("model"));
-						if (ArrayUtil.isNotEmpty(models.toArray())) {
-							contractInvoice.setInvoiceStatus("2");
+					if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) &&
+							!resultObj.getBoolean("success")) {
+						log.error("绾㈠瓧纭鍗曞け璐ワ紒锛侊紒");
+						return;
+					}
+					JSONArray models = resultObj.getJSONArray("model");
+					if (CollUtil.isNotEmpty(models)) {
+						JSONObject model = (JSONObject) models.get(0);
+
+						if (StrUtil.isEmpty(model.getString("confirmBillingMark")) || StrUtil.equals(model.getString("confirmBillingMark"), "N")) {
+							//绾㈠啿澶辫触
+							contractInvoice.setRedReversal("2");
+						} else if (StrUtil.equals(model.getString("confirmBillingMark"), "Y")) {
+							//纭鍗冲紑
+							contractInvoice.setInvoiceNo(model.getString("redInvoiceNo"));
 							contractInvoice.setRedReversal("1");
-							baseMapper.updateById(contractInvoice);
 							//鎺ㄩ�丅IP
-							pushBipInvoice(contractInvoice);
+//							pushBipInvoice(contractInvoice);
 						}
 					}
 				});
@@ -673,158 +1610,454 @@
 	@Override
 	public void takeEffect(Long id) {
 		ContractInvoice invoice = baseMapper.selectById(id);
-		Contract contract = contractMapper.selectById(invoice.getContractId());
+		R<SysDept> r = remoteDeptService.getById(SecurityUtils.getUser().getCompId());
+		if (!r.isOk()) {
+			log.error("鍗曚綅淇℃伅鏌ヨ寮傚父");
+			return;
+		}
+		SysDept dept = r.getData();
+
 		GenInvoiceInfoVo vo = BeanUtil.copyProperties(JSONObject.parseObject(invoice.getInvoicePreview()), GenInvoiceInfoVo.class);
-		vo.setContractCategory(contract.getContractCategory());
+
+		invoice.setApprovalStatus("1");
+		baseMapper.updateById(invoice);
+		invoice.setBwRequestResult("0");
+
 		//钃濈エ
 		if (invoice.getInvoiceCategory().equals("1")) {
-			// TODO 寮�钃濈エ鎺ュ彛
-			JSONObject request = genBlueInvoice(vo, invoice.getSerialNo());
-			if (bwFlag) {
+			// TODO 寮�钃濈エ鎺ュ彛鏈哄姩杞﹂攢鍞�
+			if (StrUtil.equals(vo.getInvoiceVehicleType(), "4") && bwFlag) {
+				JSONObject request = genBlueInvoiceVehicle(vo, invoice.getSerialNo(), dept);
 				String requestId = IdUtil.fastUUID();
-				log.info("钃濈エ璇锋眰鎺ュ彛鍏ュ弬", request.toJSONString());
+				invoice.setBwRequestId(requestId);
+				invoice.setBwRequestParam(request.toJSONString());
+				log.info("鏈哄姩杞﹂攢鍞粺涓�鍙戠エ寮�鍏疯姹傛帴鍙e叆鍙�:{}", request.toJSONString());
+				String result = HttpUtil.post(bwUrl + "method=baiwang.output.invoice.vehicleissue&version=1.0&requestId=" + requestId, request.toJSONString());
+				log.info("鏈哄姩杞﹂攢鍞粺涓�鍙戠エ寮�鍏疯姹傛帴鍙e洖鍙�:{}", result);
+				saveBwRequestRecord("baiwang.output.invoice.vehicleissue", requestId, request.toJSONString(), result);
+				JSONObject resultObj = JSONObject.parseObject(result);
+				if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) &&
+						resultObj.getBoolean("success")) {
+					log.info("寮�绁ㄦ垚鍔燂紒锛侊紒");
+					invoice.setBwRequestResult("1");
+				}
+				JSONObject modelJson = resultObj.getJSONObject("model");
+				if (ObjUtil.isNotNull(modelJson)) {
+					Date invoiceDate = DateUtil.parse(modelJson.getString("invoiceDate"), DatePattern.PURE_DATETIME_PATTERN);
+					invoice.setInvoiceTime(invoiceDate);
+					invoice.setInvoiceNo(modelJson.getString("invoiceNo"));
+					//鎺ㄩ�丅IP
+//					pushBipInvoice(invoice);
+				}
+			}
+
+			// TODO 寮�钃濈エ鎺ュ彛鏈哄姩杞︿笓鐢�
+			if (StrUtil.equals(vo.getInvoiceVehicleType(), "3") && bwFlag) {
+				JSONObject request = genBlueInvoiceVehiclePre(vo, invoice.getSerialNo(), dept);
+				String requestId = IdUtil.fastUUID();
+				invoice.setBwRequestId(requestId);
+				invoice.setBwRequestParam(request.toJSONString());
+				log.info("鏈哄姩杞︿笓鐢ㄥ彂绁ㄥ紑鍏疯姹傛帴鍙e叆鍙�:{}", request.toJSONString());
 				String result = HttpUtil.post(bwUrl + "method=baiwang.output.invoice.issue&version=1.0&requestId=" + requestId, request.toJSONString());
-				log.info("钃濈エ璇锋眰鎺ュ彛鍥炲弬", result);
+				log.info("鏈哄姩杞︿笓鐢ㄥ彂绁ㄥ紑鍏疯姹傛帴鍙e洖鍙�:{}", result);
 				saveBwRequestRecord("baiwang.output.invoice.issue", requestId, request.toJSONString(), result);
 				JSONObject resultObj = JSONObject.parseObject(result);
 				if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) &&
-						!resultObj.getBoolean("success")) {
+						resultObj.getBoolean("success")) {
+					log.info("寮�绁ㄦ垚鍔燂紒锛侊紒");
+					invoice.setBwRequestResult("1");
 				}
-				JSONArray models = JSONArray.parseArray(resultObj.getString("success"));
-				if (ArrayUtil.isNotEmpty(models.toArray())) {
-					JSONObject model = (JSONObject) models.get(0);
-					Date invoiceDate = DateUtil.parse(model.getString("invoiceDate"), DatePattern.PURE_DATETIME_PATTERN);
+				JSONObject modelJson = resultObj.getJSONObject("model");
+				if (ObjUtil.isNotNull(modelJson)) {
+					Date invoiceDate = DateUtil.parse(modelJson.getString("invoiceDate"), DatePattern.PURE_DATETIME_PATTERN);
 					invoice.setInvoiceTime(invoiceDate);
-					invoice.setInvoiceNo(model.getString("invoiceNo"));
+					invoice.setInvoiceNo(modelJson.getString("invoiceNo"));
+					//鎺ㄩ�丅IP
+//					pushBipInvoice(invoice);
 				}
 			}
-			if (!StrUtil.equals(contract.getContractCategory(),"water_house")) {
-				//鍚堝悓鐘舵��
-				if (StrUtil.equals(contract.getBillingStatus(), "2")) {
-					if (ObjUtil.isNull(contract.getBillingAmout())) {
-						contract.setBillingAmout(vo.getTotalPrice());
-						if (contract.getBillingAmout().compareTo(contract.getAmount()) == 0) {
-							contract.setBillingStatus("3");
-						}
-						if (contract.getBillingAmout().compareTo(contract.getAmount()) < 0) {
-							contract.setBillingStatus("1");
-						}
-						contractMapper.updateById(contract);
-					} else {
-						contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
-						if (contract.getBillingAmout().compareTo(contract.getAmount()) == 0) {
-							contract.setBillingStatus("3");
-						}
-						if (contract.getBillingAmout().compareTo(contract.getAmount()) < 0) {
-							contract.setBillingStatus("1");
-						}
-						contractMapper.updateById(contract);
-					}
-				} else {
-					if (ObjUtil.isNull(contract.getBillingAmout())) {
-						contract.setBillingAmout(vo.getTotalPrice());
-						contractMapper.updateById(contract);
-					} else {
-						contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
-						contractMapper.updateById(contract);
+
+			// TODO 寮�钃濈エ鎺ュ彛 闈炴満鍔ㄨ溅
+			if (!StrUtil.equals(vo.getInvoiceVehicleType(), "3") && !StrUtil.equals(vo.getInvoiceVehicleType(), "4") && bwFlag) {
+				JSONObject request = genBlueInvoice(vo, invoice.getSerialNo(), dept);
+				String requestId = IdUtil.fastUUID();
+				invoice.setBwRequestId(requestId);
+				invoice.setBwRequestParam(request.toJSONString());
+				log.info("钃濈エ璇锋眰鎺ュ彛鍏ュ弬:{}", request.toJSONString());
+				String result = HttpUtil.post(bwUrl + "method=baiwang.output.invoice.issue&version=1.0&requestId=" + requestId, request.toJSONString());
+				log.info("钃濈エ璇锋眰鎺ュ彛鍥炲弬:{}", result);
+				saveBwRequestRecord("baiwang.output.invoice.issue", requestId, request.toJSONString(), result);
+				JSONObject resultObj = JSONObject.parseObject(result);
+				if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) &&
+						resultObj.getBoolean("success")) {
+					log.info("寮�绁ㄦ垚鍔燂紒锛侊紒");
+					invoice.setBwRequestResult("1");
+				}
+				JSONObject modelJson = resultObj.getJSONObject("model");
+				if (ObjUtil.isNotNull(modelJson)) {
+					JSONArray models = modelJson.getJSONArray("success");
+					if (CollUtil.isNotEmpty(models)) {
+						JSONObject model = (JSONObject) models.get(0);
+						Date invoiceDate = DateUtil.parse(model.getString("invoiceDate"), DatePattern.PURE_DATETIME_PATTERN);
+						invoice.setInvoiceTime(invoiceDate);
+						invoice.setInvoiceNo(model.getString("invoiceNo"));
+						//鎺ㄩ�丅IP
+//						pushBipInvoice(invoice);
 					}
 				}
-			}else {
-				//鍒ゆ柇 寰幆鏄惁瀹屾垚
-				List<ContractExecDate> execDateList = contractExecDateMapper.selectList(Wrappers.<ContractExecDate>lambdaQuery().eq(ContractExecDate::getContractId,contract.getId())
-						.eq(ContractExecDate::getGenFlag,"0"));
-				List<MeterReadRecord> recordList = meterReadRecordMapper.selectList(Wrappers.<MeterReadRecord>lambdaQuery()
-						.eq(MeterReadRecord::getContractId,contract.getId())
-						.isNull(MeterReadRecord::getMeterReadNum));
-				if (ArrayUtil.isEmpty(execDateList.toArray())&&ArrayUtil.isEmpty(recordList.toArray())) {
-					//鍒ゆ柇鏄惁鏈夊彲寮�绁ㄨ褰�
-					List<ContractPaymentSchedule> scheduleList = contractPaymentScheduleMapper.selectList(Wrappers.<ContractPaymentSchedule>lambdaQuery()
-							.eq(ContractPaymentSchedule::getContractId,contract.getId()).eq(ContractPaymentSchedule::getInvoiceFlag,"0"));
-					if (ArrayUtil.isEmpty(scheduleList.toArray())){
+			}
+			//闈炲悎骞跺紑绁�
+			if (!invoice.getIsMerge()) {
+				Contract contract = contractMapper.selectById(invoice.getContractId());
+				vo.setContractCategory(contract.getContractCategory());
+				if (StrUtil.isNotBlank(vo.getAdvanceInvoice())) {
+					contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
+					contractMapper.updateById(contract);
+					return;
+				}
+				if (!StrUtil.equals(contract.getContractCategory(), "water_house")) {
+					//鍚堝悓鐘舵��
+					contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
+					if (contract.getBillingAmout().compareTo(contract.getAmount()) == 0) {
 						contract.setBillingStatus("3");
-					}else {
-						contract.setBillingStatus("2");
+					}
+					if (contract.getPaidAmount().compareTo(contract.getAmount().subtract(contract.getDropAmount())) >= 0 &&
+							contract.getBillingAmout().compareTo(contract.getAmount()) == 0) {
+						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())
+								.apply("invoice_num < out_bound_num"));
+						if (CollUtil.isNotEmpty(outBoundList)) {
+							contract.setBillingStatus("2");
+						}
+
+					}
+					//闃叉閲嶅瀹″紑绁ㄥ鏍搁�氳繃鍚� 寮�绁ㄩ噾棰濊秴鍑哄悎鍚岄噾棰�
+					if (contract.getBillingAmout().compareTo(contract.getAmount()) > 0) {
+						contract.setBillingAmout(contract.getAmount());
+					}
+					contractMapper.updateById(contract);
+
+				} else {
+					//鍒ゆ柇 寰幆鏄惁瀹屾垚
+					List<ContractExecDate> execDateList = contractExecDateMapper.selectList(Wrappers.<ContractExecDate>lambdaQuery().eq(ContractExecDate::getContractId, contract.getId())
+							.eq(ContractExecDate::getGenFlag, "0"));
+					if (CollUtil.isEmpty(execDateList)) {
+						//鍒ゆ柇鏄惁鏈夊彲寮�绁ㄨ褰�
+						List<ContractPaymentSchedule> scheduleList = contractPaymentScheduleMapper.selectList(Wrappers.<ContractPaymentSchedule>lambdaQuery()
+								.eq(ContractPaymentSchedule::getContractId, contract.getId()).eq(ContractPaymentSchedule::getInvoiceFlag, "0"));
+						if (CollUtil.isEmpty(scheduleList)) {
+							contract.setBillingStatus("3");
+						} else {
+							contract.setBillingStatus("2");
+						}
+						contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
+						if (contract.getBillingAmout().compareTo(contract.getAmount()) == 0) {
+							contract.setBillingStatus("3");
+						}
+						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()
+								.eq(ContractPaymentSchedule::getContractId, contract.getId()));
+						if (CollUtil.isEmpty(scheduleList)) {
+							contract.setBillingStatus("1");
+						} else {
+							contract.setBillingStatus("2");
+						}
 					}
 
-				}else {
-					//鍒ゆ柇鏄惁鏈夊彲寮�绁ㄨ褰�
-					List<ContractPaymentSchedule> scheduleList = contractPaymentScheduleMapper.selectList(Wrappers.<ContractPaymentSchedule>lambdaQuery()
-							.eq(ContractPaymentSchedule::getContractId,contract.getId()));
-					if (ArrayUtil.isEmpty(scheduleList.toArray())){
+					contractMapper.updateById(contract);
+				}
+				baseMapper.updateById(invoice);
+				return;
+			} else {
+				//鍚堝苟寮�绁�
+				List<String> result = Arrays.stream(invoice.getContractIds().replace("[", "").replace("]", "").split(","))
+						.map(String::trim)
+						.filter(s -> !s.isEmpty())
+						.collect(Collectors.toList());
+				if (CollUtil.isNotEmpty(result)) {
+					for (String cid : result) {
+						Contract contract = contractMapper.selectById(cid);
+						BigDecimal contractBillAmount = new BigDecimal("0");
+						if (CollUtil.isNotEmpty(vo.getOutBoundInvoiceList())) {
+							for (ContractOutBoundInvoiceVo outBoundInvoiceVo : vo.getOutBoundInvoiceList()) {
+								ContractOutBound contractOutBound = contractOutBoundMapper.selectById(outBoundInvoiceVo.getContractOutBoundId());
+								if (ObjUtil.isNotNull(contractOutBound) && contractOutBound.getContractId().equals(contract.getId())) {
+									ContractSubjectMatter subjectMatter = subjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery()
+											.eq(ContractSubjectMatter::getMaterialCode, contractOutBound.getSubjectMatterCode())
+											.eq(StrUtil.isNotBlank(contractOutBound.getLineNo()), ContractSubjectMatter::getLineNo, contractOutBound.getLineNo())
+											.eq(ContractSubjectMatter::getContractId, contract.getId()).last("limit 1"));
+									if (ObjUtil.isNotNull(subjectMatter) && ObjUtil.isNotNull(subjectMatter.getUnitPrice())) {
+										contractBillAmount = contractBillAmount.add(outBoundInvoiceVo.getInvoiceNum().multiply(subjectMatter.getUnitPrice()));
+
+									}
+								}
+							}
+						}
+						contract.setBillingAmout(contract.getBillingAmout().add(contractBillAmount));
 						contract.setBillingStatus("1");
-					}else {
-						contract.setBillingStatus("2");
+						List<ContractOutBound> outBoundList = contractOutBoundMapper.selectList(Wrappers.<ContractOutBound>lambdaQuery()
+								.eq(ContractOutBound::getContractId, contract.getId())
+								.apply("invoice_num < out_bound_num"));
+						if (CollUtil.isNotEmpty(outBoundList)) {
+							contract.setBillingStatus("2");
+						}
+						if (contract.getBillingAmout().compareTo(contract.getAmount()) == 0) {
+							contract.setBillingStatus("3");
+						}
+						contractMapper.updateById(contract);
 					}
 				}
-				if (ObjUtil.isNull(contract.getBillingAmout())) {
-					contract.setBillingAmout(vo.getTotalPrice());
-				} else {
-					contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
-				}
-				contractMapper.updateById(contract);
 			}
+
 		}
 		//绾㈢エ
 		if (invoice.getInvoiceCategory().equals("2")) {
 			// TODO 寮�绾㈢エ鎺ュ彛
 			ContractInvoice blueInvoice = baseMapper.selectById(invoice.getBlueInvoiceId());
-			JSONObject request = genRedInvoice(contract,blueInvoice, invoice.getSerialNo());
+			JSONObject request = genRedInvoice(blueInvoice, invoice, invoice.getSerialNo());
 			String requestId = IdUtil.fastUUID();
+			invoice.setBwRequestId(requestId);
+			invoice.setBwRequestParam(request.toJSONString());
 			if (bwFlag) {
-				log.info("绾㈠瓧纭鍗曡姹傛帴鍙e叆鍙�", request.toJSONString());
+				log.info("绾㈠瓧纭鍗曡姹傛帴鍙e叆鍙�:{}", request.toJSONString());
 				String result = HttpUtil.post(bwUrl + "method=baiwang.output.redinvoice.add&version=1.0&requestId=" + requestId, request.toJSONString());
-				log.info("绾㈠瓧纭鍗曡姹傛帴鍙e洖鍙�", result);
+				log.info("绾㈠瓧纭鍗曡姹傛帴鍙e洖鍙�:{}", result);
 				saveBwRequestRecord("baiwang.output.redinvoice.add", requestId, request.toJSONString(), result);
 				JSONObject resultObj = JSONObject.parseObject(result);
 				if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) &&
-						!resultObj.getBoolean("success")) {
-					JSONArray models = JSONArray.parseArray(resultObj.getString("success"));
-					if (ArrayUtil.isNotEmpty(models.toArray())) {
-						JSONObject model = (JSONObject) models.get(0);
+						resultObj.getBoolean("success")) {
+					log.info("绾㈠瓧纭鍗曟垚鍔燂紒锛侊紒");
+					invoice.setBwRequestResult("1");
 
-						if (StrUtil.isEmpty(model.getString("confirmBillingMark"))||StrUtil.equals(model.getString("confirmBillingMark"),"N")) {
-							//绛夊緟纭
-							invoice.setRedReversal("3");
-						}else if (StrUtil.equals(model.getString("confirmBillingMark"),"Y")) {
-							//纭鍗冲紑
-							invoice.setInvoiceNo(model.getString("redInvoiceNo"));
-							invoice.setRedReversal("1");
-							//鎺ㄩ�丅IP
-							pushBipInvoice(invoice);
+				}
+				JSONArray models = resultObj.getJSONArray("model");
+				if (CollUtil.isNotEmpty(models)) {
+					JSONObject model = (JSONObject) models.get(0);
+
+					if (StrUtil.isEmpty(model.getString("confirmBillingMark")) || StrUtil.equals(model.getString("confirmBillingMark"), "N")) {
+						//绛夊緟纭
+						invoice.setRedReversal("3");
+					} else if (StrUtil.equals(model.getString("confirmBillingMark"), "Y")) {
+						//纭鍗冲紑
+						invoice.setInvoiceNo(model.getString("redInvoiceNo"));
+						invoice.setRedReversal("1");
+						//鎺ㄩ�丅IP
+//						pushBipInvoice(invoice);
+					}
+				}
+			}
+			if (!invoice.getIsMerge()) {
+				Contract contract = contractMapper.selectById(invoice.getContractId());
+				baseMapper.updateById(invoice);
+				contract.setBillingAmout(contract.getBillingAmout().add(invoice.getInvoiceTotalPriceTax()));
+				//闃叉閲嶅瀹″紑绁ㄥ鏍搁�氳繃鍚� 寮�绁ㄩ噾棰濅负璐�
+				if (contract.getBillingAmout().compareTo(new BigDecimal("0")) < 0) {
+					contract.setBillingAmout(new BigDecimal("0"));
+				}
+				contractMapper.updateById(contract);
+				blueInvoice.setRedReversal("1");
+				baseMapper.updateById(blueInvoice);
+				if (StrUtil.isNotBlank(vo.getAdvanceInvoice())) {
+					//杩樺師棰勫紑鏁伴噺
+					List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList = BeanUtil.copyToList(JSONArray.parseArray(blueInvoice.getInvoicePreviewParam()), ContractOutBoundInvoiceVo.class);
+					if (CollUtil.isNotEmpty(outBoundInvoiceVoList)) {
+						outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
+							ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+							if (ObjUtil.isNotNull(subjectMatter)) {
+								subjectMatter.setAdvanceNum(subjectMatter.getAdvanceNum().subtract(contractOutBoundInvoiceVo.getInvoiceNum()));
+								if (subjectMatter.getAdvanceNum().compareTo(new BigDecimal("0")) <= 0) {
+									subjectMatter.setAdvanceNum(new BigDecimal("0"));
+								}
+								contractSubjectMatterMapper.updateById(subjectMatter);
+							}
+						});
+					}
+					return;
+				}
+				//鏇存柊鍚堝悓寮�绁ㄧ姸鎬� 鍓嶆彁鍑哄簱瀹屾垚
+				contract.setBillingStatus("2");
+				contractMapper.updateById(contract);
+				if (!StrUtil.equals(contract.getContractCategory(), "water_house")) {
+					//鏇存柊鍚堝悓鍑哄簱鍗曠姸鎬�
+					List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList = BeanUtil.copyToList(JSONArray.parseArray(blueInvoice.getInvoicePreviewParam()), ContractOutBoundInvoiceVo.class);
+					if (CollUtil.isNotEmpty(outBoundInvoiceVoList)) {
+						outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
+							ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+							contractOutBound.setInvoiceNum(contractOutBound.getInvoiceNum().subtract(contractOutBoundInvoiceVo.getInvoiceNum()));
+							contractOutBoundMapper.updateById(contractOutBound);
+						});
+					}
+				} else {
+					//鏇存柊鍚堝悓鎴跨 姘寸數 璐瑰紑绁ㄧ姸鎬�
+					List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList = BeanUtil.copyToList(JSONArray.parseArray(blueInvoice.getInvoicePreviewParam()), ContractOutBoundInvoiceVo.class);
+					if (CollUtil.isNotEmpty(outBoundInvoiceVoList)) {
+						outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
+							ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+							schedule.setInvoiceFlag("0");
+							contractPaymentScheduleMapper.updateById(schedule);
+						});
+					}
+				}
+			} else {
+				blueInvoice.setRedReversal("1");
+				baseMapper.updateById(blueInvoice);
+				//鍚堝苟寮�绁�
+				List<String> result = Arrays.stream(invoice.getContractIds().replace("[", "").replace("]", "").split(","))
+						.map(String::trim)
+						.filter(s -> !s.isEmpty())
+						.collect(Collectors.toList());
+				if (CollUtil.isNotEmpty(result)) {
+					for (String cid : result) {
+						Contract contract = contractMapper.selectById(cid);
+						if (CollUtil.isNotEmpty(vo.getOutBoundInvoiceList())) {
+							for (ContractOutBoundInvoiceVo outBoundInvoiceVo : vo.getOutBoundInvoiceList()) {
+								BigDecimal contractBillAmount = new BigDecimal("0");
+								if (CollUtil.isNotEmpty(vo.getOutBoundInvoiceList())) {
+									ContractOutBound contractOutBound = contractOutBoundMapper.selectById(outBoundInvoiceVo.getContractOutBoundId());
+									if (ObjUtil.isNotNull(contractOutBound) && contractOutBound.getContractId().equals(contract.getId())) {
+										ContractSubjectMatter subjectMatter = subjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery()
+												.eq(ContractSubjectMatter::getMaterialCode, contractOutBound.getSubjectMatterCode())
+												.eq(StrUtil.isNotBlank(contractOutBound.getLineNo()), ContractSubjectMatter::getLineNo, contractOutBound.getLineNo())
+												.eq(ContractSubjectMatter::getContractId, contract.getId()).last("limit 1"));
+										if (ObjUtil.isNotNull(subjectMatter) && ObjUtil.isNotNull(subjectMatter.getUnitPrice())) {
+											contractBillAmount = contractBillAmount.add(outBoundInvoiceVo.getInvoiceNum().multiply(subjectMatter.getUnitPrice()));
+										}
+										contractOutBound.setInvoiceNum(contractOutBound.getInvoiceNum().subtract(outBoundInvoiceVo.getInvoiceNum()));
+										contractOutBoundMapper.updateById(contractOutBound);
+									}
+								}
+								//鏇存柊鍚堝悓寮�绁ㄧ姸鎬� 鍓嶆彁鍑哄簱瀹屾垚
+								contract.setBillingStatus("2");
+								contract.setBillingAmout(contract.getBillingAmout().add(invoice.getInvoiceTotalPriceTax()));
+								//闃叉閲嶅瀹″紑绁ㄥ鏍搁�氳繃鍚� 寮�绁ㄩ噾棰濅负璐�
+								if (contract.getBillingAmout().compareTo(new BigDecimal("0")) < 0) {
+									contract.setBillingAmout(new BigDecimal("0"));
+								}
+								contractMapper.updateById(contract);
+							}
 						}
 					}
 				}
 			}
-			contract.setBillingAmout(contract.getBillingAmout().subtract(invoice.getInvoiceTotalPriceTax()));
-			//鏇存柊鍚堝悓寮�绁ㄧ姸鎬� 鍓嶆彁鍑哄簱瀹屾垚
-			contract.setBillingStatus("2");
-			contractMapper.updateById(contract);
-			blueInvoice.setRedReversal("1");
-			baseMapper.updateById(blueInvoice);
-			if (!StrUtil.equals(contract.getContractCategory(),"water_house")) {
-				//鏇存柊鍚堝悓鍑哄簱鍗曠姸鎬�
-				List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList = BeanUtil.copyToList(JSONArray.parseArray(blueInvoice.getInvoicePreviewParam()), ContractOutBoundInvoiceVo.class);
-				if (ArrayUtil.isNotEmpty(outBoundInvoiceVoList.toArray())) {
-					outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
-						ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
-						contractOutBound.setInvoiceNum(contractOutBound.getInvoiceNum().subtract(contractOutBoundInvoiceVo.getInvoiceNum()));
-						contractOutBoundMapper.updateById(contractOutBound);
-					});
-				}
-			}else {
-				//鏇存柊鍚堝悓鎴跨 姘寸數 璐瑰紑绁ㄧ姸鎬�
-				List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList = BeanUtil.copyToList(JSONArray.parseArray(blueInvoice.getInvoicePreviewParam()), ContractOutBoundInvoiceVo.class);
-				if (ArrayUtil.isNotEmpty(outBoundInvoiceVoList.toArray())) {
-					outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
-						ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
-						schedule.setInvoiceFlag("0");
-						contractPaymentScheduleMapper.updateById(schedule);
-					});
-				}
-			}
 		}
-		invoice.setApprovalStatus("1");
-		baseMapper.updateById(invoice);
+	}
+
+	private JSONObject genBlueInvoiceVehiclePre(GenInvoiceInfoVo vo, String serialNo, SysDept dept) {
+		JSONObject vechicleData = JSONObject.parseObject(vo.getVehicleData());
+		JSONObject jsonObject = new JSONObject();
+		//閿�鏂�
+		jsonObject.put("taxNo", vo.getPartyBOrgCode());//绋庡彿
+		jsonObject.put("taxUserName", SecurityUtils.getUser().getPhone());//鏁扮數璐﹀彿
+
+		jsonObject.put("formatGenerate", false);//鏄惁闇�瑕佺敓鎴愮増寮忚繑鍥炵増寮忛摼鎺�(true / false)
+		jsonObject.put("formatPushType", false);//鐗堝紡鐢熸垚鏄惁鎺ㄩ��(true / false)
+		jsonObject.put("taxUserName", dept.getInvoiceContact());
+		//data
+		JSONObject data = new JSONObject();
+		data.put("invoiceTypeCode", "01");
+		data.put("invoiceType", "0");
+		data.put("serialNo", serialNo);
+		data.put("invoiceSpecialMark", "14");//鐗瑰畾涓氬姟鏍囪瘑	14-鏈哄姩杞�
+//		data.put("taxationMethod","2");
+//		data.put("taxationLabel","02");//鍙戠エ绫诲瀷浠g爜涓衡��01-鏁扮數鍙戠エ锛堝鍊肩◣涓撶敤鍙戠エ锛夈��02-鏁扮數鍙戠エ锛堟櫘閫氬彂绁級鈥濇椂涓斿緛绋庢柟寮忎负鈥�2-宸寰佺◣鈥濇椂蹇呭~
+		List<JSONObject> invoiceDetailsList = new ArrayList<>();
+		Integer lineNo = 1;
+		//data.invoiceDetailsList
+		for (InvoiceItemVo invoiceItemVo : vo.getInvoiceItemList()) {
+			JSONObject invoiceDetail = new JSONObject();
+
+			invoiceDetail.put("goodsLineNo", lineNo);
+			invoiceDetail.put("goodsName", invoiceItemVo.getItemName());
+			invoiceDetail.put("projectName", invoiceItemVo.getItemName());
+			invoiceDetail.put("goodsCode", invoiceItemVo.getTaxCode());
+			invoiceDetail.put("goodsTaxRate", invoiceItemVo.getTaxRate().divide(new BigDecimal("100")));
+			invoiceDetail.put("goodsUnit", "杈�");
+			invoiceDetail.put("goodsQuantity", invoiceItemVo.getQuantity());
+//			invoiceDetail.put("goodsPrice", invoiceItemVo.getUnitPrice());
+			invoiceDetail.put("goodsSpecification", vo.getVehicleNo());
+			invoiceDetail.put("goodsTotalPrice", invoiceItemVo.getPriceNoTax());
+			invoiceDetail.put("goodsTotalTax", invoiceItemVo.getPriceTax());
+
+			invoiceDetailsList.add(invoiceDetail);
+			lineNo++;
+		}
+		data.put("invoiceDetailsList", invoiceDetailsList);
+		//璐柟
+		data.put("buyerTaxNo", vo.getPartyAOrgCode());
+		data.put("buyerName", vo.getPartyA());
+		data.put("sellerTaxNo", vo.getPartyBOrgCode());// TODO 绋庡姟鎬诲眬绯荤粺鐧婚檰浜烘墜鏈哄彿
+		data.put("invoiceTotalPrice", vo.getTotalPrice().subtract(vo.getTotalTax()));
+		data.put("invoiceTotalPriceTax", vo.getTotalPrice());
+		data.put("invoiceTotalTax", vo.getTotalTax());
+		data.put("buyerBankName", vo.getPartyAOpenBank());
+		data.put("buyerBankNumber", vo.getPartyABankAccount());
+
+		jsonObject.put("data", data);
+		return jsonObject;
+	}
+
+	private JSONObject genBlueInvoiceVehicle(GenInvoiceInfoVo vo, String serialNo, SysDept dept) {
+		JSONObject vechicleData = JSONObject.parseObject(vo.getVehicleData());
+		JSONObject jsonObject = new JSONObject();
+		//閿�鏂�
+		jsonObject.put("taxNo", vo.getPartyBOrgCode());//绋庡彿
+		jsonObject.put("invoiceTerminalCode", "JDCwxj");//瓒呰繃鍙戠エ鍗曞紶闄愰鏄惁闇�瑕佹媶鍒嗗紑鍏凤紝榛樿涓嶆媶鍒嗭紙鎷嗗垎鍙敮鎸佸彂绁ㄧ被鍨嬩唬鐮佷负 涓撶エ 004 鏅エ 007 鐢靛瓙绁� 026鐨�
+		jsonObject.put("formatGenerate", false);//鏄惁闇�瑕佺敓鎴愮増寮忚繑鍥炵増寮忛摼鎺�(true / false)
+		jsonObject.put("formatPushType", false);//鐗堝紡鐢熸垚鏄惁鎺ㄩ��(true / false)
+		jsonObject.put("taxUserName", dept.getInvoiceContact());
+		//data
+		JSONObject data = new JSONObject();
+		data.put("invoiceTypeCode", "03");
+		data.put("invoiceType", "0");
+		data.put("serialNo", serialNo);
+		//data.invoiceDetailsList
+		Integer lineNo = 1;
+		JSONObject invoiceDetail = new JSONObject();
+
+		invoiceDetail.put("vehicleNo", vo.getVehicleNo());
+		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("goodsCode", vo.getInvoiceItemList().get(0).getTaxCode());
+		invoiceDetail.put("goodsTaxRate", vo.getInvoiceItemList().get(0).getTaxRate().divide(new BigDecimal("100")));
+		if (!StrUtil.equals(vo.getContractCategory(), "water_house")) {
+			invoiceDetail.put("goodsTotalPrice", vo.getInvoiceItemList().get(0).getPriceNoTax());
+		} else {
+			invoiceDetail.put("goodsTotalPrice", vo.getInvoiceItemList().get(0).getPriceNoTax());
+		}
+		invoiceDetail.put("goodsTotalTax", vo.getInvoiceItemList().get(0).getPriceTax());
+		data.put("invoiceVehicleInfo", invoiceDetail);
+		//璐柟
+		data.put("buyerTaxNo", vo.getPartyAOrgCode());
+		data.put("buyerName", vo.getPartyA());
+		data.put("sellerTaxNo", vo.getPartyBOrgCode());// TODO 绋庡姟鎬诲眬绯荤粺鐧婚檰浜烘墜鏈哄彿
+		data.put("invoiceTotalPrice", vo.getTotalPrice().subtract(vo.getTotalTax()));
+		data.put("invoiceTotalPriceTax", vo.getTotalPrice());
+		data.put("invoiceTotalTax", vo.getTotalTax());
+		data.put("buyerBankName", vo.getPartyAOpenBank());
+		data.put("buyerBankNumber", vo.getPartyABankAccount());
+
+		jsonObject.put("data", data);
+		return jsonObject;
 	}
 
 	@Override
@@ -835,20 +2068,20 @@
 		Contract contract = contractMapper.selectById(invoice.getContractId());
 		//钃濈エ
 		if (invoice.getInvoiceCategory().equals("1")) {
-			if (!StrUtil.equals(contract.getContractCategory(),"water_house")) {
+			if (!StrUtil.equals(contract.getContractCategory(), "water_house")) {
 				//鏇存柊鍚堝悓鍑哄簱鍗曠姸鎬�
 				List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList = BeanUtil.copyToList(JSONArray.parseArray(invoice.getInvoicePreviewParam()), ContractOutBoundInvoiceVo.class);
-				if (ArrayUtil.isNotEmpty(outBoundInvoiceVoList.toArray())) {
+				if (CollUtil.isNotEmpty(outBoundInvoiceVoList)) {
 					outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
 						ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
 						contractOutBound.setInvoiceNum(contractOutBound.getInvoiceNum().subtract(contractOutBoundInvoiceVo.getInvoiceNum()));
 						contractOutBoundMapper.updateById(contractOutBound);
 					});
 				}
-			}else {
+			} else {
 				//鏇存柊鍚堝悓鎴跨 姘寸數 璐瑰紑绁ㄧ姸鎬�
 				List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList = BeanUtil.copyToList(JSONArray.parseArray(invoice.getInvoicePreviewParam()), ContractOutBoundInvoiceVo.class);
-				if (ArrayUtil.isNotEmpty(outBoundInvoiceVoList.toArray())) {
+				if (CollUtil.isNotEmpty(outBoundInvoiceVoList)) {
 					outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
 						ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
 						schedule.setInvoiceFlag("0");
@@ -869,11 +2102,296 @@
 
 	@Override
 	public Page pageInvoice(Page page, ContractInvoiceQueryDTO queryDTO) {
-		return baseMapper.pageInvoice(page,queryDTO, DataScope.of("comp_id"));
+		return baseMapper.pageInvoice(page, queryDTO, DataScope.of("comp_id"));
 	}
 
 	@Override
 	public Page pageScope(Page page, ContractQueryDTO queryDTO) {
-		return baseMapper.pageScope(page,queryDTO, DataScope.of("comp_id"));
+		return baseMapper.pageScope(page, queryDTO, DataScope.of("comp_id"));
+	}
+
+	@Override
+	public R refresh(Long invoiceId) {
+		ContractInvoice invoice = baseMapper.selectById(invoiceId);
+		//钃濈エ
+		if (invoice.getInvoiceCategory().equals("1")) {
+			// TODO 寮�钃濈エ鎺ュ彛
+			if (bwFlag) {
+				String requestId = IdUtil.fastUUID();
+				invoice.setBwRequestId(requestId);
+				invoice.setBwRequestResult("1");
+				invoice.setBwRequestParam(invoice.getBwRequestParam());
+				log.info("钃濈エ璇锋眰鎺ュ彛鍏ュ弬:{}", invoice.getBwRequestParam());
+				String result = HttpUtil.post(bwUrl + "method=baiwang.output.invoice.issue&version=1.0&requestId=" + requestId, invoice.getBwRequestParam());
+				log.info("钃濈エ璇锋眰鎺ュ彛鍥炲弬:{}", result);
+				saveBwRequestRecord("baiwang.output.invoice.issue", requestId, invoice.getBwRequestParam(), result);
+				JSONObject resultObj = JSONObject.parseObject(result);
+				if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) &&
+						!resultObj.getBoolean("success")) {
+					log.error("寮�绁ㄥけ璐ワ紒锛侊紒");
+					return R.failed(resultObj.getString("message"));
+				}
+				invoice.setBwRequestResult("1");
+				JSONObject modelJson = resultObj.getJSONObject("model");
+				JSONArray models = modelJson.getJSONArray("success");
+				if (CollUtil.isNotEmpty(models)) {
+					JSONObject model = (JSONObject) models.get(0);
+					Date invoiceDate = DateUtil.parse(model.getString("invoiceDate"), DatePattern.PURE_DATETIME_PATTERN);
+					invoice.setInvoiceTime(invoiceDate);
+					invoice.setInvoiceNo(model.getString("invoiceNo"));
+					//鎺ㄩ�丅IP
+//					pushBipInvoice(invoice);
+				}
+			}
+		}
+		//绾㈢エ
+		if (invoice.getInvoiceCategory().equals("2")) {
+			// TODO 寮�绾㈢エ鎺ュ彛
+			String requestId = IdUtil.fastUUID();
+			invoice.setBwRequestId(requestId);
+			invoice.setBwRequestParam(invoice.getBwRequestParam());
+			if (bwFlag) {
+				log.info("绾㈠瓧纭鍗曡姹傛帴鍙e叆鍙�:{}", invoice.getBwRequestParam());
+				String result = HttpUtil.post(bwUrl + "method=baiwang.output.redinvoice.add&version=1.0&requestId=" + requestId, invoice.getBwRequestParam());
+				log.info("绾㈠瓧纭鍗曡姹傛帴鍙e洖鍙�:{}", result);
+				saveBwRequestRecord("baiwang.output.redinvoice.add", requestId, invoice.getBwRequestParam(), result);
+				JSONObject resultObj = JSONObject.parseObject(result);
+				if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) &&
+						!resultObj.getBoolean("success")) {
+					log.error("绾㈠瓧纭鍗曞け璐ワ紒锛侊紒");
+
+					return R.failed(resultObj.getString("message"));
+				}
+				invoice.setBwRequestResult("1");
+				JSONArray models = resultObj.getJSONArray("model");
+				if (CollUtil.isNotEmpty(models)) {
+					JSONObject model = (JSONObject) models.get(0);
+					if (StrUtil.isEmpty(model.getString("confirmBillingMark")) || StrUtil.equals(model.getString("confirmBillingMark"), "N")) {
+						//绛夊緟纭
+						invoice.setRedReversal("3");
+					} else if (StrUtil.equals(model.getString("confirmBillingMark"), "Y")) {
+						//纭鍗冲紑
+						invoice.setInvoiceNo(model.getString("redInvoiceNo"));
+						invoice.setRedReversal("1");
+						//鎺ㄩ�丅IP
+//						pushBipInvoice(invoice);
+					}
+				}
+			}
+		}
+		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(result);
+		}
+		//绾㈢エ
+		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(result);
+		}
+		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();
+	}
+
+	@Override
+	public ContractInvoice getById(Long id) {
+		return baseMapper.selectById(id);
+	}
+
+	@Override
+	public R bipPushPdf(Long invoiceId) {
+		ContractInvoice invoice = baseMapper.selectById(invoiceId);
+		pushBipInvoicePdf(invoice);
+		return R.ok();
+	}
+
+	@Override
+	public R selectBipByKey(String dictKey) {
+		List<BipDict> bipDictList = bipDictMapper.selectList(Wrappers.<BipDict>lambdaQuery().eq(BipDict::getDictKey, dictKey));
+		if (CollUtil.isNotEmpty(bipDictList)) {
+			// 鏉冮檺鍐呴儴闂�
+			List<TreeNode<Long>> collect = bipDictList.stream()
+					.map(dict -> {
+						TreeNode<Long> treeNode = new TreeNode<>();
+						treeNode.setId(dict.getId());
+						treeNode.setParentId(dict.getParentId());
+						treeNode.setName(dict.getDictName());
+						treeNode.setWeight(dict.getDictCode());
+						return treeNode;
+					})
+					.collect(Collectors.toList());
+
+			return R.ok(TreeUtil.build(collect, 0L));
+		}
+		return R.failed("瀛楀吀鑾峰彇澶辫触");
+	}
+
+	@Override
+	public R saveAndPush(ContractInvoiceUpateDTO upateDTO) {
+		ContractInvoice invoice = baseMapper.selectById(upateDTO.getId());
+		invoice.setInvoicePreview(upateDTO.getInvoicePreview());
+		baseMapper.updateById(invoice);
+		R r = bipPush(invoice.getId());
+		if (!r.isOk()) {
+			return r;
+		}
+		return bipPushPdf(invoice.getId());
+	}
+
+	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);
 	}
 }

--
Gitblit v1.9.1