From 2db76f2066701cbe292f206ad49a7f8523b8aa9f Mon Sep 17 00:00:00 2001
From: shiyunteng <shiyunteng@example.com>
Date: 星期五, 14 八月 2026 16:30:25 +0800
Subject: [PATCH] feat:银行流水关联多个合同,新增预收款开票,所有List校验调整为ColUtil

---
 platformx-business-finance-biz/src/main/java/com/by4cloud/platformx/business/service/impl/ContractInvoiceServiceImpl.java |  819 ++++++++++++++++++++++++++++++++++++++++++++++------------
 1 files changed, 645 insertions(+), 174 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 fa9c7b6..9325098 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,6 +1,7 @@
 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;
@@ -9,10 +10,8 @@
 import cn.hutool.core.util.ObjUtil;
 import cn.hutool.core.util.StrUtil;
 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,33 +19,31 @@
 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.entity.*;
 import com.by4cloud.platformx.business.mapper.*;
 import com.by4cloud.platformx.business.service.ContractInvoiceService;
 import com.by4cloud.platformx.business.service.PaymentConfirmService;
-import com.by4cloud.platformx.business.vo.ContractInvoiceOutBoundVo;
-import com.by4cloud.platformx.business.vo.ContractOutBoundMergeVo;
-import com.by4cloud.platformx.business.vo.GenInvoiceInfoVo;
-import com.by4cloud.platformx.business.vo.InvoiceItemVo;
+import com.by4cloud.platformx.business.vo.*;
 import com.by4cloud.platformx.common.core.util.R;
-import com.by4cloud.platformx.common.data.mybatis.BaseModel;
+import com.by4cloud.platformx.common.data.datascope.DataScope;
 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.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.math.BigDecimal;
 import java.math.RoundingMode;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
 import java.util.stream.Collectors;
 
 @Slf4j
@@ -55,15 +52,20 @@
 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;
+	private final ContractExecDateMapper contractExecDateMapper;
+	private final ContractPaymentScheduleMapper contractPaymentScheduleMapper;
+	private final MeterReadRecordMapper meterReadRecordMapper;
 	private final ContractSubjectMatterMapper subjectMatterMapper;
 	private final ProductMapper productMapper;
 	private final BwRequestRecordMapper bwRequestRecordMapper;
 	private final RemoteDeptService remoteDeptService;
 	private final RemoteFlowProcessService remoteFlowProcessService;
 	private final PaymentConfirmService paymentConfirmService;
-	private final RedisTemplate redisTemplate;
+	private final StringRedisTemplate redisTemplate;
 
 
 	@Value("${BWInvoice.url}")
@@ -88,16 +90,98 @@
 				.selectAll(ContractOutBound.class)
 				.eq(ContractOutBound::getContractId, contractId);
 		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().eq(ContractSubjectMatter::getContractId,contractId)
+						.eq(ContractSubjectMatter::getMaterialCode,contractInvoiceOutBoundVo.getSubjectMatterCode())
+						.eq(StrUtil.isNotBlank(contractInvoiceOutBoundVo.getLineNo()),ContractSubjectMatter::getLineNo,contractInvoiceOutBoundVo.getLineNo())
+						.last("limit 1"));
+				if (ObjUtil.isNotNull(subjectMatter)&&subjectMatter.getAdvanceNum().compareTo(new BigDecimal("0"))>0){
+					contractInvoiceOutBoundVo.setInvoiceNum(contractInvoiceOutBoundVo.getOutBoundNum().subtract(subjectMatter.getAdvanceNum()));
+				}
+				contractInvoiceOutBoundVo.setToInvoiceNum(contractInvoiceOutBoundVo.getInvoiceNum());
+			});
+		}
+		return R.ok(invoiceOutBoundVoList);
+	}
+
+	@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 (ArrayUtil.isNotEmpty(invoiceOutBoundVoList)) {
+			invoiceOutBoundVoList.stream().forEach(contractInvoiceOutBoundVo -> {
+				contractInvoiceOutBoundVo.setInvoiceNum(contractInvoiceOutBoundVo.getOutBoundNum().subtract(contractInvoiceOutBoundVo.getAdvanceNum()));
+				contractInvoiceOutBoundVo.setToInvoiceNum(contractInvoiceOutBoundVo.getInvoiceNum());
+			});
+		}
+		return R.ok(invoiceOutBoundVoList);
+	}
+
+	@Override
+	public R getContractHouseWater(Long contractId) {
+		MPJLambdaWrapper<ContractPaymentSchedule> wrapper = new MPJLambdaWrapper<ContractPaymentSchedule>()
+				.selectAll(ContractPaymentSchedule.class)
+				.eq(ContractPaymentSchedule::getContractId, contractId)
+				.orderByAsc(ContractPaymentSchedule::getCreateTime);
+		List<ContractHouseWaterVo> invoiceOutBoundVoList = contractPaymentScheduleMapper.selectJoinList(ContractHouseWaterVo.class, wrapper);
 		return R.ok(invoiceOutBoundVoList);
 	}
 
 	@Override
 	public R genInvoiceInfo(GenInvoiceInfoDTO genInvoiceInfoDTO) {
-		if (ArrayUtil.isEmpty(genInvoiceInfoDTO.getContractOutBoundIds())) {
+		if (ArrayUtil.isEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList())) {
 			return R.failed("璇烽�夋嫨寮�绁ㄥ嚭搴撳崟鍚庡啀鎿嶄綔");
 		}
-		ContractOutBound outBound = contractOutBoundMapper.selectById(genInvoiceInfoDTO.getContractOutBoundIds().get(0));
-		Contract contract = contractMapper.selectById(outBound.getContractId());
+		Long contractId = null;
+		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();
+			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()));
+				}
+			}
+			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);
+
+			return R.ok(vo);
+		}
+
+		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);
 		if (ObjUtil.isNull(contract)) {
 			return R.failed("鍚堝悓淇℃伅寮傚父锛岃鑱旂郴鎶�鏈汉鍛�");
 		}
@@ -125,46 +209,191 @@
 		List<InvoiceItemVo> invoiceItemVoList = new ArrayList<>();
 		List<String> erpCode = new ArrayList<>();
 		List<ContractOutBoundMergeVo> mergeOutBounds = new ArrayList<>();
-		List<ContractOutBound> outBounds = contractOutBoundMapper.selectList(Wrappers.<ContractOutBound>lambdaQuery()
-				.in(ContractOutBound::getId, genInvoiceInfoDTO.getContractOutBoundIds()));
-		if (ArrayUtil.isNotEmpty(outBounds.toArray())) {
-			outBounds.stream().forEach(contractOutBound -> {
-				if (!ArrayUtil.contains(erpCode.toArray(), contractOutBound.getSubjectMatterCode())) {
-					erpCode.add(contractOutBound.getSubjectMatterCode());
-					ContractOutBoundMergeVo mergeVo = new ContractOutBoundMergeVo();
-					mergeVo.setMaterialCode(contractOutBound.getSubjectMatterCode());
-					mergeVo.setMaterialInternalName(contractOutBound.getSubjectMatterName());
-					mergeVo.setQuantity(contractOutBound.getOutBoundNum());
-					Product 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());
+//		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 (CollUtil.isNotEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList())) {
+				genInvoiceInfoDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
+					ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+
+					if (!CollUtil.contains(erpCode, contractOutBound.getSubjectMatterCode())) {
+						erpCode.add(contractOutBound.getSubjectMatterCode());
+						ContractOutBoundMergeVo mergeVo = new ContractOutBoundMergeVo();
+						mergeVo.setMaterialCode(contractOutBound.getSubjectMatterCode());
+						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"));
 						if (ObjUtil.isNotNull(product)) {
-							mergeVo.setItemName("*" + product.getTaxClass() + "*" + productClass.getProductName());
+							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());
+						}
+						mergeOutBounds.add(mergeVo);
+					} else {
+						List<ContractOutBoundMergeVo> filteredList = mergeOutBounds.stream()
+								.filter(item -> contractOutBound.getSubjectMatterCode().equals(item.getMaterialCode())) // 闃叉绌烘寚閽堬紝寤鸿甯搁噺鍦ㄥ墠
+								.collect(Collectors.toList());
+						if (ArrayUtil.isNotEmpty(filteredList)) {
+							filteredList.get(0).setQuantity(filteredList.get(0).getQuantity().add(contractOutBound.getOutBoundNum()));
 						}
 					}
-					ContractSubjectMatter subjectMatter = subjectMatterMapper.selectOne(Wrappers.<ContractSubjectMatter>lambdaQuery()
-							.eq(ContractSubjectMatter::getMaterialCode, contractOutBound.getSubjectMatterCode())
-							.eq(ContractSubjectMatter::getContractId, contract.getId()).last("limit 1"));
-					if (ObjUtil.isNotNull(subjectMatter)) {
+				});
+				if (ArrayUtil.isNotEmpty(mergeOutBounds)) {
+					invoiceItemVoList = BeanUtil.copyToList(mergeOutBounds, InvoiceItemVo.class);
+					invoiceItemVoList.stream().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));
+					vo.setInvoiceItemList(invoiceItemVoList);
+					vo.setPriceWords(Convert.digitToChinese(vo.getTotalPrice()));
+				}
+			}
+		} else {
+			if (ArrayUtil.isNotEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList())) {
+				genInvoiceInfoDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
+					ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+
+					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());
+						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)) {
+							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, schedule.getSubjectMatterCode())
+								.eq(ContractSubjectMatter::getContractId, contract.getId()).last("limit 1"));
+						if (ObjUtil.isNotNull(subjectMatter)) {
+							mergeVo.setUnitPrice(subjectMatter.getUnitPrice());
+						}
+						mergeOutBounds.add(mergeVo);
+					} else {
+						List<ContractOutBoundMergeVo> filterMergeVo = mergeOutBounds.stream().filter(item -> item.getMaterialCode()
+								.equals(schedule.getSubjectMatterCode())).collect(Collectors.toList());
+						if (ArrayUtil.isNotEmpty(filterMergeVo)) {
+							filterMergeVo.get(0).setPriceAndTax(schedule.getPlannedAmount().add(filterMergeVo.get(0).getPriceAndTax()));
+						}
+					}
+				});
+				if (ArrayUtil.isNotEmpty(mergeOutBounds)) {
+					invoiceItemVoList = BeanUtil.copyToList(mergeOutBounds, InvoiceItemVo.class);
+					invoiceItemVoList.stream().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));
+					});
+					vo.setTotalPrice(invoiceItemVoList.stream().map(item -> item.getPriceAndTax()).reduce(BigDecimal.ZERO, BigDecimal::add));
+					vo.setInvoiceItemList(invoiceItemVoList);
+					vo.setPriceWords(Convert.digitToChinese(vo.getTotalPrice()));
+				}
+			}
+		}
+		return vo;
+	}
+
+	private GenInvoiceInfoVo genAdvanceInvoiceInfoVo(GenInvoiceInfoDTO genInvoiceInfoDTO, Contract contract, SysDept b) {
+		GenInvoiceInfoVo vo = new GenInvoiceInfoVo();
+		BusinessCustomer a = businessCustomerMapper.selectById(contract.getPartyAId());
+		vo.setAdvanceInvoice("111");
+		vo.setPartyA(a.getCompanyName());
+		vo.setPartyAOrgCode(a.getCreditCode());
+		vo.setPartyAOpenBank(a.getBankName());
+		vo.setPartyABankAccount(a.getBankAccount());
+		vo.setPartyB(b.getOrgName());
+		vo.setPartyBOrgCode(b.getOrgCode());
+		vo.setPartyBOpenBank(b.getOrgBank());
+		vo.setPartyBBankAccount(b.getOrgBankAccount());
+		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())) {
+						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());
+							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());
+								}
+
+							}
+						}
 						mergeVo.setUnitPrice(subjectMatter.getUnitPrice());
 						mergeVo.setUnit(subjectMatter.getUnit());
+						mergeOutBounds.add(mergeVo);
 					}
-					mergeOutBounds.add(mergeVo);
-				} else {
-					List<ContractOutBoundMergeVo> filteredList = mergeOutBounds.stream()
-							.filter(item -> contractOutBound.getSubjectMatterCode().equals(item.getMaterialCode())) // 闃叉绌烘寚閽堬紝寤鸿甯搁噺鍦ㄥ墠
-							.collect(Collectors.toList());
-					if (ArrayUtil.isNotEmpty(filteredList.toArray())) {
-						filteredList.get(0).setQuantity(filteredList.get(0).getQuantity().add(contractOutBound.getOutBoundNum()));
-					}
+
 				}
 			});
-			if (ArrayUtil.isNotEmpty(mergeOutBounds.toArray())) {
+			if (ArrayUtil.isNotEmpty(mergeOutBounds)) {
 				invoiceItemVoList = BeanUtil.copyToList(mergeOutBounds, InvoiceItemVo.class);
 				invoiceItemVoList.stream().forEach(invoiceItemVo -> {
 //				for (InvoiceItemVo invoiceItemVo:invoiceItemVoList) {
@@ -178,16 +407,77 @@
 				vo.setPriceWords(Convert.digitToChinese(vo.getTotalPrice()));
 			}
 		}
+
 		return vo;
 	}
 
 	@Override
 	public R toInvoice(GenInvoiceInfoDTO genInvoiceInfoDTO) {
-		if (ArrayUtil.isEmpty(genInvoiceInfoDTO.getContractOutBoundIds().toArray())) {
+		if (ArrayUtil.isEmpty(genInvoiceInfoDTO.getOutBoundInvoiceList())) {
 			return R.failed("璇烽�夋嫨寮�绁ㄥ嚭搴撳崟鍚庡啀鎿嶄綔");
 		}
-		ContractOutBound outBound = contractOutBoundMapper.selectById(genInvoiceInfoDTO.getContractOutBoundIds().get(0));
-		Contract contract = contractMapper.selectById(outBound.getContractId());
+		Long contractId = null;
+		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("鍚堝悓淇℃伅寮傚父锛岃鑱旂郴鎶�鏈汉鍛�");
+			}
+			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 : genInvoiceInfoDTO.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 = genAdvanceInvoiceInfoVo(genInvoiceInfoDTO, contract, b);
+			//鍙戠エ淇濆瓨
+			ContractInvoice invoice = saveContractInvoice(vo, contract, genInvoiceInfoDTO.getOutBoundInvoiceList(), DateUtil.current() + "","1");
+			//鍚姩娴佺▼
+			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("娴佺▼鍚姩澶辫触");
+			}
+			//鏇存柊鍚堝悓鍑哄簱鍗曠姸鎬�
+			genInvoiceInfoDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
+				ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+				subjectMatter.setAdvanceNum(subjectMatter.getAdvanceNum().add(contractOutBoundInvoiceVo.getInvoiceNum()));
+				contractSubjectMatterMapper.updateById(subjectMatter);
+			});
+			return R.ok();
+		}
+		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);
 		if (ObjUtil.isNull(contract)) {
 			return R.failed("鍚堝悓淇℃伅寮傚父锛岃鑱旂郴鎶�鏈汉鍛�");
 		}
@@ -198,22 +488,37 @@
 		SysDept b = r.getData();
 		GenInvoiceInfoVo vo = genInvoiceInfoVo(genInvoiceInfoDTO, contract, b);
 		//鍙戠エ淇濆瓨
-		ContractInvoice invoice = saveContractInvoice(vo, contract, genInvoiceInfoDTO.getContractOutBoundIds(), DateUtil.current() + "");
+		ContractInvoice invoice = saveContractInvoice(vo, contract, genInvoiceInfoDTO.getOutBoundInvoiceList(), DateUtil.current() + "","0");
 		//鍚姩娴佺▼
 		ProcessInstanceParamDto dto = new ProcessInstanceParamDto();
 		Map<String, Object> map = BeanUtil.beanToMap(invoice);
+		if (StrUtil.equals(genInvoiceInfoDTO.getContractCategory(), "water_house")) {
+			map.put("contractCategory", "water_house");
+		}
 		dto.setParamMap(map);
 		dto.setFlowName(FlowNameEnum.閿�鍞寕璐﹀鎵�.name());
 		R r1 = remoteFlowProcessService.startProcessInstance(dto);
 		if (r1.getCode() == 1) {
 			return R.failed("娴佺▼鍚姩澶辫触");
 		}
-		//鏇存柊鍚堝悓鍑哄簱鍗曠姸鎬�
-		genInvoiceInfoDTO.getContractOutBoundIds().stream().forEach(outBoundId -> {
-			ContractOutBound bound = contractOutBoundMapper.selectById(outBoundId);
-			bound.setInvoiceStatus("1");
-			contractOutBoundMapper.updateById(bound);
-		});
+		if (!StrUtil.equals(contract.getContractCategory(), "water_house")) {
+			//鏇存柊鍚堝悓鍑哄簱鍗曠姸鎬�
+			genInvoiceInfoDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
+				ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+				contractOutBound.setInvoiceStatus("1");
+				if (contractOutBoundInvoiceVo.getInvoiceNum().compareTo(contractOutBound.getOutBoundNum().subtract(contractOutBound.getInvoiceNum())) <= 0) {
+					contractOutBound.setInvoiceNum(contractOutBound.getInvoiceNum().subtract(contractOutBoundInvoiceVo.getInvoiceNum()));
+				}
+				contractOutBoundMapper.updateById(contractOutBound);
+			});
+		} else {
+			//鏇存柊鍚堝悓鎴跨 姘寸數 璐瑰紑绁ㄧ姸鎬�
+			genInvoiceInfoDTO.getOutBoundInvoiceList().stream().forEach(contractOutBoundInvoiceVo -> {
+				ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+				schedule.setInvoiceFlag("1");
+				contractPaymentScheduleMapper.updateById(schedule);
+			});
+		}
 		return R.ok();
 	}
 
@@ -232,7 +537,6 @@
 		//閿�鏂�
 		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
@@ -251,7 +555,11 @@
 			invoiceDetail.put("goodsUnit", invoiceItemVo.getUnit());
 			invoiceDetail.put("goodsQuantity", invoiceItemVo.getQuantity());
 			invoiceDetail.put("goodsPrice", invoiceItemVo.getUnitPrice());
-			invoiceDetail.put("goodsTotalPrice", invoiceItemVo.getUnitPrice().multiply(invoiceItemVo.getQuantity()));
+			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);
@@ -261,8 +569,7 @@
 		//璐柟
 		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", SecurityUtils.getUser().getPhone());// TODO 绋庡姟鎬诲眬绯荤粺鐧婚檰浜烘墜鏈哄彿
 		data.put("invoiceTotalPriceTax", vo.getTotalPrice());
 		data.put("buyerBankName", vo.getPartyAOpenBank());
 		data.put("buyerBankNumber", vo.getPartyABankAccount());
@@ -271,24 +578,28 @@
 		return jsonObject;
 	}
 
-	private ContractInvoice saveContractInvoice(GenInvoiceInfoVo genInvoiceInfoVo, Contract contract, List<Long> outBoundIds, String serialNo) {
+	private ContractInvoice saveContractInvoice(GenInvoiceInfoVo genInvoiceInfoVo, Contract contract,
+				List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList, String serialNo,String advanceFlag) {
 		ContractInvoice invoice = new ContractInvoice();
 		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());
 		invoice.setInvoicePreview(JSONObject.toJSONString(genInvoiceInfoVo));
 		invoice.setInvoiceStatus("1");
 		invoice.setApprovalStatus("0");
-		invoice.setOutBoundId(outBoundIds.stream()
-				.map(String::valueOf) // 鎴栬�� .map(Object::toString)
+		invoice.setOutBoundId(outBoundInvoiceVoList.stream()
+				.map(item -> String.valueOf(item.getContractOutBoundId())) // 鎴栬�� .map(Object::toString)
 				.collect(Collectors.joining(",")));
+		invoice.setInvoicePreviewParam(JSONObject.toJSONString(outBoundInvoiceVoList));
+		invoice.setAdvanceFlag(advanceFlag);
 		baseMapper.insert(invoice);
 		return invoice;
 	}
@@ -307,11 +618,13 @@
 		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());
+		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());
@@ -327,10 +640,16 @@
 		invoice.setSerialNo(DateUtil.current() + "");
 		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");
+		}
 		dto.setParamMap(map);
 		dto.setFlowName(FlowNameEnum.閿�鍞寕璐﹀鎵�.name());
 		R r1 = remoteFlowProcessService.startProcessInstance(dto);
@@ -341,38 +660,40 @@
 		return R.ok();
 	}
 
-	private JSONObject genRedInvoice(ContractInvoice blueInvoice, String redConfirmSerialNo) {
+	private JSONObject genRedInvoice(Contract contract, ContractInvoice blueInvoice, String redConfirmSerialNo) {
 		JSONObject jsonObject = new JSONObject();
-		jsonObject.put("taxNo", blueInvoice.getTexNo());
+		jsonObject.put("taxNo", blueInvoice.getTaxNo());
 		jsonObject.put("redConfirmSerialNo", redConfirmSerialNo);
 		jsonObject.put("entryIdentity", "01");
-		jsonObject.put("sellerTaxNo", blueInvoice.getTexNo());
+		jsonObject.put("sellerTaxNo", blueInvoice.getTaxNo());
 		jsonObject.put("sellerTaxName", blueInvoice.getSellerTaxName());
 		jsonObject.put("buyerTaxName", blueInvoice.getBuyerTaxName());
-		jsonObject.put("originalInvoiceNo", blueInvoice.getInvoiceNo());
-		jsonObject.put("originInvoiceIsPaper", "N");
+		jsonObject.put("buyerTaxNo", blueInvoice.getBuyerTaxNo());
 		jsonObject.put("originInvoiceDate", blueInvoice.getInvoiceTime());
 		jsonObject.put("originInvoiceTotalPrice", blueInvoice.getInvoiceTotalPrice());
-		jsonObject.put("originInvoiceTotalTax", blueInvoice.getInvoiceTotalPrice());
+		jsonObject.put("originInvoiceTotalTax", blueInvoice.getInvoiceTotalTax());
+		jsonObject.put("invoiceTotalPrice", blueInvoice.getInvoiceTotalPrice().multiply(new BigDecimal("-1")));
+		jsonObject.put("invoiceTotalTax", blueInvoice.getInvoiceTotalTax().multiply(new BigDecimal("-1")));
+		jsonObject.put("originInvoiceIsPaper", "N");
 		jsonObject.put("originInvoiceType", "01");
-		jsonObject.put("invoiceTotalPrice", blueInvoice.getInvoiceTotalPrice());
-		jsonObject.put("invoiceTotalTax", blueInvoice.getInvoiceTotalPrice());
-		jsonObject.put("redInvoiceLabel", "2");
+		jsonObject.put("redInvoiceLabel", "01");
+		jsonObject.put("invoiceSource", "2");
+		jsonObject.put("originalInvoiceNo", blueInvoice.getInvoiceNo());
 		GenInvoiceInfoVo vo = BeanUtil.copyProperties(JSONObject.parseObject(blueInvoice.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("goodsUnit", invoiceItemVo.getUnit());
 			invoiceDetail.put("goodsQuantity", invoiceItemVo.getQuantity());
 			invoiceDetail.put("goodsPrice", invoiceItemVo.getUnitPrice());
-			invoiceDetail.put("goodsTotalPrice", invoiceItemVo.getUnitPrice().multiply(invoiceItemVo.getQuantity()));
-			invoiceDetail.put("goodsTotalTax", invoiceItemVo.getPriceTax());
-
+			invoiceDetail.put("goodsTotalPrice", invoiceItemVo.getPriceNoTax().multiply(new BigDecimal("-1")));
+			invoiceDetail.put("goodsTotalTax", invoiceItemVo.getPriceTax().multiply(new BigDecimal("-1")));
 			invoiceDetailsList.add(invoiceDetail);
 			lineNo++;
 		}
@@ -386,14 +707,16 @@
 		if (bwFlag) {
 			List<ContractInvoice> contractInvoices = baseMapper.selectList(Wrappers.<ContractInvoice>lambdaQuery()
 					.eq(ContractInvoice::getInvoiceCategory, "1").eq(ContractInvoice::getInvoiceStatus, "1"));
-			if (ArrayUtil.isNotEmpty(contractInvoices.toArray())) {
+			if (ArrayUtil.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("taxNo", contractInvoice.getSerialNo());
+					data.put("returnType", "3");
+					data.put("invoiceIssueMode", "1");
 					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());
 					log.info("serial_no:{},鍙戠エ鏌ヨ鍥炲弬锛歿},", contractInvoice.getSerialNo(), result);
@@ -401,7 +724,7 @@
 					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);
 					}
@@ -418,18 +741,34 @@
 		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 dept = r.getData();
 		//钃濈エ
-		if (StrUtil.equals(contractInvoice.getInvoiceCategory(),"1")) {
-			JSONObject params = genBlueReceiveParams(contractInvoice);
+		if (StrUtil.equals(contractInvoice.getInvoiceCategory(), "1")) {
+			JSONObject params = genBlueReceiveParams(contractInvoice, contract, customer, dept);
 			String finalAccessToken = accessToken;
 
-			log.info("XSJZ_YS_DJ_INSERT Request:", params.toJSONString());
+			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);
 			//淇濆瓨璇锋眰璁板綍
@@ -444,7 +783,7 @@
 			}
 		}
 		//绾㈢エ
-		if (StrUtil.equals(contractInvoice.getInvoiceCategory(),"2")) {
+		if (StrUtil.equals(contractInvoice.getInvoiceCategory(), "2")) {
 			JSONObject params = genRedReceiveParams(contractInvoice);
 			String finalAccessToken = accessToken;
 
@@ -462,42 +801,48 @@
 	}
 
 	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 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");
+		data.put("customerCode", customer.getBipCode());//瀹㈡埛缂栫爜
+		data.put("financeOrgCode", dept.getBipCode());//寮�绁ㄧ粍缁囩紪鐮�
+		data.put("orgCode", dept.getBipCode());//涓氬姟缁勭粐缂栫爜
+		data.put("bustypeCode", "");//浜ゆ槗绫诲瀷缂栫爜 鏆備及榛樿ZGYSFP锛岄攢鍞粯璁JHYXGLXT
+		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()) {
 			JSONObject item = new JSONObject();
-			item.put("invoiceNo",contractInvoice.getInvoiceNo());
-			item.put("materialCode",invoiceItemVo.getErpCode());
+			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("_status", "Insert");
 
 			bodyItem.add(item);
 		}
-		data.put("bodyItem",bodyItem);
-		jsonObject.put("data",data);
-		return  jsonObject;
+		data.put("bodyItem", bodyItem);
+		jsonObject.put("data", data);
+		return jsonObject;
 	}
 
 	@Override
@@ -505,25 +850,36 @@
 		if (bwFlag) {
 			List<ContractInvoice> contractInvoices = baseMapper.selectList(Wrappers.<ContractInvoice>lambdaQuery()
 					.eq(ContractInvoice::getInvoiceCategory, "2").eq(ContractInvoice::getInvoiceStatus, "3"));
-			if (ArrayUtil.isNotEmpty(contractInvoices.toArray())) {
+			if (ArrayUtil.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 (ArrayUtil.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);
 						}
@@ -539,13 +895,16 @@
 		ContractInvoice invoice = baseMapper.selectById(id);
 		Contract contract = contractMapper.selectById(invoice.getContractId());
 		GenInvoiceInfoVo vo = BeanUtil.copyProperties(JSONObject.parseObject(invoice.getInvoicePreview()), GenInvoiceInfoVo.class);
-
+		vo.setContractCategory(contract.getContractCategory());
+		invoice.setApprovalStatus("1");
+		baseMapper.updateById(invoice);
 		//钃濈エ
 		if (invoice.getInvoiceCategory().equals("1")) {
 			// TODO 寮�钃濈エ鎺ュ彛
 			JSONObject request = genBlueInvoice(vo, invoice.getSerialNo());
 			if (bwFlag) {
 				String requestId = IdUtil.fastUUID();
+				invoice.setBwRequestId(requestId);
 				log.info("钃濈エ璇锋眰鎺ュ彛鍏ュ弬", request.toJSONString());
 				String result = HttpUtil.post(bwUrl + "method=baiwang.output.invoice.issue&version=1.0&requestId=" + requestId, request.toJSONString());
 				log.info("钃濈エ璇锋眰鎺ュ彛鍥炲弬", result);
@@ -553,100 +912,212 @@
 				JSONObject resultObj = JSONObject.parseObject(result);
 				if (resultObj.containsKey("requestId") && StrUtil.equals(resultObj.getString("requestId"), requestId) &&
 						!resultObj.getBoolean("success")) {
+					log.error("寮�绁ㄥけ璐ワ紒锛侊紒");
+					return;
 				}
-				JSONArray models = JSONArray.parseArray(resultObj.getString("success"));
-				if (ArrayUtil.isNotEmpty(models.toArray())) {
+				JSONObject modelJson = resultObj.getJSONObject("model");
+				JSONArray models = modelJson.getJSONArray("success");
+				if (ArrayUtil.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"));
 				}
 			}
-
-			//鍚堝悓鐘舵��
-			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");
-					}
-					contractMapper.updateById(contract);
-				} else {
+			if (StrUtil.isNotBlank(vo.getAdvanceInvoice())){
+				contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
+				contractMapper.updateById(contract);
+				return;
+			}
+			if (!StrUtil.equals(contract.getContractCategory(), "water_house")) {
+				//鍚堝悓鐘舵��
+				if (StrUtil.equals(contract.getBillingStatus(), "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.setBillingStatus("1");
+					}
+					//闃叉閲嶅瀹″紑绁ㄥ鏍搁�氳繃鍚� 寮�绁ㄩ噾棰濊秴鍑哄悎鍚岄噾棰�
+					if (contract.getBillingAmout().compareTo(contract.getAmount()) > 0) {
+						contract.setBillingAmout(contract.getAmount());
 					}
 					contractMapper.updateById(contract);
 				}
 			} else {
-				if (ObjUtil.isNull(contract.getBillingAmout())) {
-					contract.setBillingAmout(vo.getTotalPrice());
-					contractMapper.updateById(contract);
+				//鍒ゆ柇 寰幆鏄惁瀹屾垚
+				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) && ArrayUtil.isEmpty(recordList)) {
+					//鍒ゆ柇鏄惁鏈夊彲寮�绁ㄨ褰�
+					List<ContractPaymentSchedule> scheduleList = contractPaymentScheduleMapper.selectList(Wrappers.<ContractPaymentSchedule>lambdaQuery()
+							.eq(ContractPaymentSchedule::getContractId, contract.getId()).eq(ContractPaymentSchedule::getInvoiceFlag, "0"));
+					if (ArrayUtil.isEmpty(scheduleList)) {
+						contract.setBillingStatus("3");
+					} else {
+						contract.setBillingStatus("2");
+					}
+
 				} else {
-					contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
-					contractMapper.updateById(contract);
+					//鍒ゆ柇鏄惁鏈夊彲寮�绁ㄨ褰�
+					List<ContractPaymentSchedule> scheduleList = contractPaymentScheduleMapper.selectList(Wrappers.<ContractPaymentSchedule>lambdaQuery()
+							.eq(ContractPaymentSchedule::getContractId, contract.getId()));
+					if (ArrayUtil.isEmpty(scheduleList)) {
+						contract.setBillingStatus("1");
+					} else {
+						contract.setBillingStatus("2");
+					}
 				}
+				contract.setBillingAmout(vo.getTotalPrice().add(contract.getBillingAmout()));
+				//闃叉閲嶅瀹″紑绁ㄥ鏍搁�氳繃鍚� 寮�绁ㄩ噾棰濊秴鍑哄悎鍚岄噾棰�
+				if (contract.getBillingAmout().compareTo(contract.getAmount()) > 0) {
+					contract.setBillingAmout(contract.getAmount());
+				}
+				contractMapper.updateById(contract);
 			}
 		}
 		//绾㈢エ
 		if (invoice.getInvoiceCategory().equals("2")) {
 			// TODO 寮�绾㈢エ鎺ュ彛
 			ContractInvoice blueInvoice = baseMapper.selectById(invoice.getBlueInvoiceId());
-			JSONObject request = genRedInvoice(blueInvoice, invoice.getSerialNo());
+			JSONObject request = genRedInvoice(contract, blueInvoice, invoice.getSerialNo());
 			String requestId = IdUtil.fastUUID();
+			invoice.setBwRequestId(requestId);
 			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);
+					log.error("绾㈠瓧纭鍗曞け璐ワ紒锛侊紒");
+					return;
+				}
+				JSONArray models = resultObj.getJSONArray("model");
+				if (ArrayUtil.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 (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);
 					}
 				}
 			}
-			//鏇存柊鍚堝悓寮�绁ㄧ姸鎬�
-			contract.setBillingStatus("2");
-			contract.setBillingAmout(contract.getAmount().subtract(invoice.getInvoiceTotalPriceTax()));
+			contract.setBillingAmout(contract.getBillingAmout().subtract(invoice.getInvoiceTotalPriceTax()));
+			//闃叉閲嶅瀹″紑绁ㄥ鏍搁�氳繃鍚� 寮�绁ㄩ噾棰濅负璐�
+			if (contract.getBillingAmout().compareTo(new BigDecimal("0")) < 0) {
+				contract.setBillingAmout(new BigDecimal("0"));
+			}
 			contractMapper.updateById(contract);
-
-			//鏇存柊鍚堝悓鍑哄簱鍗曠姸鎬�
-			String[] outBoundIds = blueInvoice.getOutBoundId().split(",");
-			Arrays.stream(outBoundIds).forEach(outBoundId -> {
-				ContractOutBound bound = contractOutBoundMapper.selectById(outBoundId);
-				bound.setInvoiceStatus("0");
-				contractOutBoundMapper.updateById(bound);
-			});
+			blueInvoice.setRedReversal("1");
+			baseMapper.updateById(blueInvoice);
+			if (StrUtil.isNotBlank(vo.getAdvanceInvoice())){
+				//杩樺師棰勫紑鏁伴噺
+				List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList = BeanUtil.copyToList(JSONArray.parseArray(blueInvoice.getInvoicePreviewParam()), ContractOutBoundInvoiceVo.class);
+				if (ArrayUtil.isNotEmpty(outBoundInvoiceVoList)) {
+					outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
+						ContractSubjectMatter subjectMatter = contractSubjectMatterMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+						if (ObjUtil.isNotNull(subjectMatter)){
+							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 (ArrayUtil.isNotEmpty(outBoundInvoiceVoList)) {
+					outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
+						ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+						if (contractOutBoundInvoiceVo.getInvoiceNum().compareTo(contractOutBound.getOutBoundNum().subtract(contractOutBound.getInvoiceNum())) <= 0) {
+							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)) {
+					outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
+						ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+						schedule.setInvoiceFlag("0");
+						contractPaymentScheduleMapper.updateById(schedule);
+					});
+				}
+			}
 		}
-		invoice.setApprovalStatus("1");
-		baseMapper.updateById(invoice);
+
 	}
 
 	@Override
 	public void refuseApproval(Long id) {
 		ContractInvoice invoice = baseMapper.selectById(id);
-		//鏇存柊鍚堝悓鍑哄簱鍗曠姸鎬�
-		String[] outBoundIds = invoice.getOutBoundId().split(",");
-		Arrays.stream(outBoundIds).forEach(outBoundId -> {
-			ContractOutBound bound = contractOutBoundMapper.selectById(outBoundId);
-			bound.setInvoiceStatus("0");
-			contractOutBoundMapper.updateById(bound);
-		});
 		invoice.setApprovalStatus("2");
 		baseMapper.updateById(invoice);
+		Contract contract = contractMapper.selectById(invoice.getContractId());
+		//钃濈エ
+		if (invoice.getInvoiceCategory().equals("1")) {
+			if (!StrUtil.equals(contract.getContractCategory(), "water_house")) {
+				//鏇存柊鍚堝悓鍑哄簱鍗曠姸鎬�
+				List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList = BeanUtil.copyToList(JSONArray.parseArray(invoice.getInvoicePreviewParam()), ContractOutBoundInvoiceVo.class);
+				if (ArrayUtil.isNotEmpty(outBoundInvoiceVoList)) {
+					outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
+						ContractOutBound contractOutBound = contractOutBoundMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+						if (contractOutBoundInvoiceVo.getInvoiceNum().compareTo(contractOutBound.getOutBoundNum().subtract(contractOutBound.getInvoiceNum())) <= 0) {
+							contractOutBound.setInvoiceNum(contractOutBound.getInvoiceNum().subtract(contractOutBoundInvoiceVo.getInvoiceNum()));
+							contractOutBoundMapper.updateById(contractOutBound);
+						}
+					});
+				}
+			} else {
+				//鏇存柊鍚堝悓鎴跨 姘寸數 璐瑰紑绁ㄧ姸鎬�
+				List<ContractOutBoundInvoiceVo> outBoundInvoiceVoList = BeanUtil.copyToList(JSONArray.parseArray(invoice.getInvoicePreviewParam()), ContractOutBoundInvoiceVo.class);
+				if (ArrayUtil.isNotEmpty(outBoundInvoiceVoList)) {
+					outBoundInvoiceVoList.stream().forEach(contractOutBoundInvoiceVo -> {
+						ContractPaymentSchedule schedule = contractPaymentScheduleMapper.selectById(contractOutBoundInvoiceVo.getContractOutBoundId());
+						schedule.setInvoiceFlag("0");
+						contractPaymentScheduleMapper.updateById(schedule);
+					});
+				}
+				contract.setBillingStatus("2");
+				contractMapper.updateById(contract);
+			}
+		}
+		//绾㈢エ
+		if (invoice.getInvoiceCategory().equals("2")) {
+			ContractInvoice blueInvoice = baseMapper.selectById(invoice.getBlueInvoiceId());
+			blueInvoice.setRedReversal("0");
+			baseMapper.updateById(blueInvoice);
+		}
+	}
+
+	@Override
+	public Page pageInvoice(Page page, ContractInvoiceQueryDTO queryDTO) {
+		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"));
 	}
 }

--
Gitblit v1.9.1