package com.zfire.mall.manager.logic.invoice;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.EnumUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.engin.deposit.DepositManageRecordBean;
import com.zfire.mall.manager.bean.invoice.*;
import com.zfire.mall.manager.bean.k3.RequestApiBean;
import com.zfire.mall.manager.bean.listV2.dto.InvoiceProjectDTO;
import com.zfire.mall.manager.bean.sale.SaleOrderBean;
import com.zfire.mall.manager.bean.sale.SaleOrderVO;
import com.zfire.mall.manager.commonmapper.InvoiceMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.constant.KingDeeCons;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.enums.InvoiceCustomerEnum;
import com.zfire.mall.manager.enums.IsEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.customer.CustomerProductTypeLogic;
import com.zfire.mall.manager.logic.engin.deposit.DepositManageLogic;
import com.zfire.mall.manager.logic.k3.K3Logic;
import com.zfire.mall.manager.logic.k3.bill.GeJiangInStockLogic;
import com.zfire.mall.manager.logic.pick.PickLogic;
import com.zfire.mall.manager.logic.reserved.ReservedLogic;
import com.zfire.mall.manager.logic.retail.RetailOrderLogic;
import com.zfire.mall.manager.logic.stock.StockCommonLogic;
import com.zfire.mall.manager.logic.wallet.WalletLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import com.zfire.mall.manager.utils.RedisUtil;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.stream.Collectors;

/**
 * 申请发货单
 *
 * @author change
 */
@Service
public class InvoiceLogic {

    @Autowired
    InvoiceMapper invoiceMapper;

    @Autowired
    StockCustomerService stockCustomerService;

    @Autowired
    StockCommonLogic stockCommonLogic;

    @Autowired
    KingDeeOrganizationService kingDeeOrganizationService;

    @Autowired
    K3Logic k3Logic;

    @Autowired
    StockService stockService;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    RetailOrderItemService retailOrderItemService;

    @Autowired
    RetailOrderService retailOrderService;

    @Autowired
    KingDeeCustomerService kingDeeCustomerService;

    @Autowired
    KingDeeMaterialService kingDeeMaterialService;

    @Autowired
    InvoiceApplicationService invoiceApplicationService;

    @Autowired
    InvoiceApplicationOrderService invoiceApplicationOrderService;

    @Autowired
    RetailOrderLogic retailOrderLogic;

    @Autowired
    DisplaceOrderItemService displaceOrderItemService;

    @Autowired
    DisplaceOrderService displaceOrderService;

    @Autowired
    EnginOrderService enginOrderService;

    @Autowired
    EnginOrderItemService enginOrderItemService;

    @Autowired
    DepositManageItemService depositManageItemService;

    @Autowired
    CustomerProductTypeLogic customerProductTypeLogic;

    @Autowired
    DepositManageLogic depositManageLogic;

    @Autowired
    WalletLogic walletLogic;

    @Autowired
    CustomerWalletService customerWalletService;

    @Autowired
    ReservedLogic reservedLogic;

    @Autowired
    SalesOrderService salesOrderService;

    @Autowired
    RetreatDocumentOrderService retreatDocumentOrderService;

    @Autowired
    ShipDocumentService shipDocumentService;

    @Autowired
    PickManagerShipService pickManagerShipService;

    @Autowired
    AdminWebsitService adminWebsitService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    PickLogic pickLogic;

    @Autowired
    RequisitionOrderService requisitionOrderService;

    @Autowired
    RequisitionOrderItemService requisitionOrderItemService;

    @Autowired
    SalesOrderItemService salesOrderItemService;

    @Autowired
    GeJiangInStockLogic geJiangInStockLogic;

    @Autowired
    SalesOrderPictureService salesOrderPictureService;

    @Autowired
    KingDeeDepartmentService kingDeeDepartmentService;

    @Autowired
    AdminUserCategoryRelaService adminUserCategoryRelaService;


    @Autowired
    StockCorrespondCategoryService stockCorrespondCategoryService;

    @Autowired
    AdminUserStockService adminUserStockService;

    @Autowired
    RedisLockRegistry redisLockRegistry;

    @Autowired
    StockForceCategoryService stockForceCategoryService;

    @Autowired
    StockForceService stockForceService;

    @Autowired
    AdminUserForceStockService adminUserForceStockService;


    public IPage<InvoiceBean> list(Integer automaticStatus, String createBy, String approvalName, String categoryId, String k3ServiceId, String mainOrderId, String id, String categoryName, Integer type, String customerName, String correspondId, String correspondName, String materialName, String specification, String startTime, String endTime,
                                   String customerNumber, String examineStatus, String orderType, Integer pageNum, Integer pageSize, String serviceId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        //String status = adminUser.getIsCustomer() ? "" : "SAVE";
        IPage<InvoiceBean> invoiceBeanIPage = invoiceMapper.listInvoice(new Page<>(pageNum, pageSize),automaticStatus, createBy, approvalName, categoryId, k3ServiceId, mainOrderId, id, categoryName, type, customerName, correspondId, correspondName, materialName, specification,
                startTime, endTime, customerNumber, examineStatus, orderType, customerId, adminUser.getServiceIds(), null, serviceId, adminUser.getK3CategoryIds());
        return invoiceBeanIPage;
    }

    public InvoiceBody detail(String id) {
        InvoiceBody detail = invoiceMapper.detail(id);

        //获得可发货数量

        detail.getOrders().forEach(item -> {
            if (StringUtils.isNotBlank(detail.getCorrespondId())) {

                Integer integer = invoiceMapper.selectInvoiceOk(item.getOrderId());
                item.setAlreadyInvoiceNum(integer - item.getRefundableQty());

                item.setCanApply(item.getQty() - item.getAlreadyInvoiceNum());
            }
        });
        List<SalesOrderPicture> listPicture = salesOrderPictureService.lambdaQuery().eq(SalesOrderPicture::getSalesId, detail.getId()).list();
        detail.setSalesOrderPictures(listPicture);
        return detail;
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(InvoiceRequestJson invoiceRequest) throws Exception {
        //1查看发货单即时库存是否充足
        checkAdd(invoiceRequest.getOrders(), invoiceRequest.getCorrespondId(), invoiceRequest.getExamineStatus(),invoiceRequest.getCustomerId());


        //查询仓库是否符合
        List<String> collect = invoiceRequest.getOrders().stream().map(InvoiceApplicationOrderRequest::getMaterialId).collect(Collectors.toList());
        checkStock(invoiceRequest.getCorrespondId(),collect);

        //2，添加发货申请单
        AdminUserCom adminUser = commonLogic.getAdminUser();
        AdminWebsit adminWebsit = adminWebsitService.lambdaQuery().eq(AdminWebsit::getAdminWebsitId, adminWebsitService.getById(adminUser.getAdminWebsitId()).getAdminWebsitId()).one();
        if (adminWebsit == null || StringUtils.isEmpty(adminWebsit.getWebsitNumber()))
            throw new RemoteServiceException("该经销商不在区域范围");

        if (StringUtils.isNotBlank(adminUser.getCustomerId())) {
            invoiceRequest.setCustomerId(adminUser.getCustomerId());
            invoiceRequest.setCustomerName(adminUser.getCustomerName());
            invoiceRequest.setCustomerNumber(adminUser.getCustomerNumber());
        }

        invoiceRequest.setOrderTime(new Date());
        List<InvoiceApplicationOrder> invoiceApplicationOrders = new ArrayList<>();
        String orderNumber = generateInvoiceOrder(adminWebsit.getWebsitNumber());
        invoiceRequest.setId(adminWebsit.getWebsitNumber() + orderNumber);
        boolean save = invoiceApplicationService.save(invoiceRequest);

        //存储图片
        if (!CollectionUtils.isEmpty(invoiceRequest.getSalesOrderPictures())){
            for (SalesOrderPicture salesOrderPicture : invoiceRequest.getSalesOrderPictures()) {
                salesOrderPicture.setSalesId(invoiceRequest.getId());
            }
            salesOrderPictureService.saveBatch(invoiceRequest.getSalesOrderPictures());
        }

        if (CollectionUtils.isEmpty(invoiceRequest.getOrders()))
            throw new RemoteServiceException("未添加订单");

        Map<String, String> map = new HashMap<>();
        Map<String, String> mapBool = new HashMap<>();

        //添加产品明细
        for (InvoiceApplicationOrder order : invoiceRequest.getOrders()) {


            if (order.getInvoiceNum() == null || order.getInvoiceNum().equals(0))
                continue;
            if (order.getInvoiceNum() < 0)
                throw new RemoteServiceException("数量不能为负数");

            //添加零售订单的申请发货单详细
            if (order.getOrderType().equals("RETAIL") || order.getOrderType().equals("RETAIL_POLICY")) {

                //检查订单可申请数量是否大于申请数量
                invoiceOrder(order.getOrderId(), order.getInvoiceNum());

                RetailOrder retailOrder = retailOrderService.getById(order.getMainOrderId());
                RetailOrderItem retailOrderItem = retailOrderItemService.getById(order.getOrderId());

                if (retailOrderItem.getQty() < (retailOrderItem.getRefundableQty()+retailOrderItem.getHasSendQty()))
                    throw new RemoteServiceException("可退数量大于了订单数量!");


                if (!retailOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()) && retailOrder.getIsPlanOrder())
                    throw new RemoteServiceException("订单不属于审核状态，无法发货");

                KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(retailOrder.getCustomerId());

                //判断发产品类是否是同一品类
                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(retailOrderItem.getMaterialId());

                map.put(kingDeeMaterial.getCategoryNumber(),kingDeeMaterial.getCategoryName());


                if (adminUser.getIsCustomer() && adminUserForceStockService.lambdaQuery()
                        .eq(AdminUserForceStock::getCategoryId, kingDeeMaterial.getCategoryId())
                        .eq(AdminUserForceStock::getCorrespondId,invoiceRequest.getCorrespondId())
                        .eq(AdminUserForceStock::getAdminUserId,adminUser.getAdminUserId())
                        .count() < 1) {
                    //强制仓返回，有强制仓，判断强制是否有库存，有库存都返回0,没返回正常库存
                    List<AdminUserForceStock> list = adminUserForceStockService.lambdaQuery()
                            .eq(AdminUserForceStock::getCategoryId, kingDeeMaterial.getCategoryId())
                            .ne(AdminUserForceStock::getCorrespondId, invoiceRequest.getCorrespondId())
                            .eq(AdminUserForceStock::getAdminUserId,adminUser.getAdminUserId())
                            .list();
                    if (!CollectionUtils.isEmpty(list) ) {
                        for (AdminUserForceStock adminUserForceStock : list) {
                            if (stockCommonLogic.stockCorrespondStatus(null, adminUserForceStock.getCorrespondId(), order.getMaterialId(), null) > 0) {
                                throw new RemoteServiceException("物料规格"+order.getSpecification()+"没有库存请去"+adminUserForceStock.getCorrespondName());
                            }
                        }


                    }
                }

                //判断是否直调发货未完成
                if (retailOrderItem.getIsDirectTransfer().equals(1) && retailOrderItem.getDirectTransferStatus().equals(0))
                    throw new RemoteServiceException(retailOrderItem.getMaterialName() + "直调未完成不能申请发货");

                invoiceRequest.setCustomerNumber(retailOrder.getCustomerNumber());
                invoiceRequest.setCustomerId(retailOrder.getCustomerId());
                invoiceRequest.setCustomerName(retailOrder.getCustomerName());
                invoiceRequest.setSecondCustomerNumber(kingDeeCustomer.getSecondCustomerNumber());
                invoiceRequest.setParentId(kingDeeCustomer.getParentId());

                order.setMainOrderId(retailOrderItem.getRetailOrderId());
                order.setRefundableQty(order.getInvoiceNum());
                order.setVarietyQty(order.getInvoiceNum());
                order.setInvoiceId(invoiceRequest.getId());
                order.setSaleTypeId(retailOrderItem.getSaleTypeId());
                order.setSaleTypeCode(retailOrderItem.getSaleTypeCode());
                order.setSaleTypeName(retailOrderItem.getSaleTypeName());
                order.setTheTime(retailOrder.getTheTime());
                order.setMaterialName(retailOrderItem.getMaterialName());
                order.setMaterialId(retailOrderItem.getMaterialId());
                order.setMaterialCode(retailOrderItem.getMaterialCode());
                order.setMaterialOldNumber(retailOrderItem.getMaterialOldNumber());
                order.setSpecification(retailOrderItem.getSpecification());
                order.setUnit(retailOrderItem.getUnit());
                order.setPrice(retailOrderItem.getPrice());

                order.setPayAmount(retailOrderItem.getSinglePayPrice()
                        .multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTotalAmount(retailOrderItem.getPrice().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setPayRebateAmount(retailOrderItem.getSingleRebateAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTotalDiscAmount(retailOrderItem.getDiscAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTax(retailOrderItem.getTax());
                order.setSingleRebateAmount(retailOrderItem.getSingleRebateAmount());
                order.setQty(retailOrderItem.getQty());
                order.setSinglePayPrice(retailOrderItem.getSinglePayPrice());
                order.setServiceId(retailOrderItem.getServiceId());
                order.setServiceName(retailOrderItem.getServiceName());
                order.setDiscAmount(retailOrderItem.getDiscAmount());
                order.setKingDeeSeq(retailOrderItem.getKingDeeSeq());
                order.setKingDeeEntryId(retailOrderItem.getKingDeeEntryId());
                order.setK3CategoryId(retailOrderItem.getK3CategoryId());
                order.setK3CategoryName(retailOrderItem.getK3CategoryName());
                order.setK3CategoryNumber(retailOrderItem.getK3CategoryNumber());
                order.setK3ServiceId(retailOrder.getK3ServiceId());
                order.setK3ServiceName(retailOrder.getK3ServiceName());
                order.setCustomerWalletId(retailOrderItem.getCustomerWalletId());
                order.setCustomerWalletName(retailOrderItem.getCustomerWalletName());
                order.setCustomerWalletNumber(retailOrderItem.getCustomerWalletNumber());
                order.setCustomerWalletId2(retailOrderItem.getCustomerWalletId2());
                order.setCustomerWalletName2(retailOrderItem.getCustomerWalletName2());
                order.setFileNo(retailOrder.getFileNo());
                order.setRetiredQty(0);
                order.setCategoryId(kingDeeMaterial.getCategoryId());
                order.setCategoryName(kingDeeMaterial.getCategoryName());
                order.setCategoryNumber(kingDeeMaterial.getCategoryNumber());
                order.setGoodsOrderId(retailOrder.getId());
                order.setMaterialGroupName(kingDeeMaterial.getMaterialGroupName());
                order.setInvoiceExamineStatus(invoiceRequest.getExamineStatus());

                if (retailOrder.getType().equals(2)) {
                    order.setPolicyId(retailOrder.getPolicyId());
                    order.setPolicyTitle(retailOrder.getPolicyTitle());
                    order.setPolicyCode(retailOrder.getPolicyCode());
                }

            }

            //判断是否是新单还是旧单，两种情况都有就提示
            if ( StringUtils.isEmpty(order.getKingDeeEntryId())) {
                mapBool.put("1","1");
                invoiceRequest.setSyncType(2);
            }
            if  (!StringUtils.isEmpty(order.getKingDeeEntryId()))
                mapBool.put("2","2");


            invoiceApplicationOrders.add(order);
            invoiceRequest.updateById();
            //增加经销商暂扣库存
            stockCommonLogic.inventoryStockCustomerSuspended(order.getMaterialId(), invoiceRequest.getCustomerId(), order.getRefundableQty());

            //更改预留单预留数量
            reservedLogic.reduceReserved(order, invoiceRequest.getCorrespondId());
        }

        if (mapBool.size() > 1)
            throw new RemoteServiceException("新单旧单发货逻辑更改，需分别发货");

        //判断是否是同一个存货类别
        if (map.size() > 1)
            throw new RemoteServiceException("非同一存货类别不能一起申请发货，请分开申请发货后。");

        List<String> collect1 = invoiceApplicationOrders.stream().map(InvoiceApplicationOrder::getMaterialId).distinct().collect(Collectors.toList());
        if (collect1.size() != invoiceApplicationOrders.size()) {
            throw new RemoteServiceException("同一物料不能一起申请发货，请分开申请发货后。");
        }

        invoiceApplicationService.updateById(invoiceRequest);
        invoiceApplicationOrderService.saveBatch(invoiceApplicationOrders);

        //invoiceMapper.updateStatus(invoiceRequest.getId());
        //invoiceMapper.updateInvoice(invoiceRequest.getId());
        invoiceMapper.updateWithold(invoiceRequest.getId(),Constant.RETAIL_UPDATE);
    }

    private void checkStock(String correspondId, List<String> collect) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        //仓库无配置分类
        List<StockCorrespondCategory> stockCorrespondCategories = stockCorrespondCategoryService.lambdaQuery().in(StockCorrespondCategory::getCorrespondId, correspondId).list();
        if (CollectionUtils.isEmpty(stockCorrespondCategories))
            return;

        //用户拥有此仓库
        Integer stockCount = adminUserStockService.lambdaQuery().eq(AdminUserStock::getCorrespondId, correspondId)
                .eq(AdminUserStock::getAdminUserId,adminUser.getAdminUserId()).count();
        if (stockCount > 0)
            return;

        //
        for (String m : collect) {
            KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(m);
            long count = stockCorrespondCategories.stream().filter(item -> item.getCategoryId().equals(kingDeeMaterial.getCategoryId())).count();
            if (count < 1)
                throw new RemoteServiceException(kingDeeMaterial.getSpecification()+":"+kingDeeMaterial.getName()+":库存不足");
        }

    }


    public void invoiceRequisitionOrder(String orderId, Integer invoiceNum) {
        //检查订单可申请数量是否大于申请数量
        RequisitionOrderItem requisitionOrderItemServiceById = requisitionOrderItemService.getById(orderId);
        Integer integer = invoiceMapper.selectInvoice(orderId);
        if (integer == null)
            integer = 0;
        if (invoiceNum + integer > requisitionOrderItemServiceById.getRefundableQty())
            throw new RemoteServiceException("当前申请数量大于可申请数量，可申请数量"+(requisitionOrderItemServiceById.getRefundableQty()-integer));
    }

    public void invoicePermuOrder(String orderId, Integer invoiceNum) {
        //检查订单可申请数量是否大于申请数量
        DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(orderId);

        Integer integer = invoiceMapper.selectInvoice(orderId);
        if (integer == null)
            integer = 0;
        if (invoiceNum + integer > displaceOrderItem.getRefundableQty())
            throw new RemoteServiceException("当前申请数量大于可申请数量,可申请数量"+(displaceOrderItem.getRefundableQty()-integer));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(InvoiceRequestJson invoiceRequest, HttpServletRequest request) throws Exception {
        //1查看发货单即时库存是否充足
        checkAdd(invoiceRequest.getOrders(), invoiceRequest.getCorrespondId(), invoiceRequest.getExamineStatus(),invoiceRequest.getCustomerId());

        //2，添加发货申请单
        AdminUserCom adminUser = commonLogic.getAdminUser(request);


        boolean save = invoiceApplicationService.updateById(invoiceRequest);
        invoiceApplicationOrderService.lambdaUpdate().eq(InvoiceApplicationOrder::getInvoiceId, invoiceRequest.getId()).remove();
        List<InvoiceApplicationOrder> invoiceApplicationOrders = new ArrayList<>();

        InvoiceApplication invoiceApplication = invoiceApplicationService.getById(invoiceRequest.getId());

        if (invoiceApplication.getIsRe().equals("YES"))
            throw new RemoteServiceException("预留发货单不可编辑改变预留数量");

        String categoryId = null;

        //存储图片
        salesOrderPictureService.lambdaUpdate().eq(SalesOrderPicture::getSalesId,invoiceRequest.getId()).remove();
        if (!CollectionUtils.isEmpty(invoiceRequest.getSalesOrderPictures())){
            for (SalesOrderPicture salesOrderPicture : invoiceRequest.getSalesOrderPictures()) {
                salesOrderPicture.setSalesId(invoiceRequest.getId());
            }
            salesOrderPictureService.saveBatch(invoiceRequest.getSalesOrderPictures());
        }

        Map<String, String> mapBool = new HashMap<>();

        for (InvoiceApplicationOrder order : invoiceRequest.getOrders()) {



            if (order.getInvoiceNum() == null || order.getInvoiceNum().equals(0))
                continue;
            if (order.getInvoiceNum() < 0)
                throw new RemoteServiceException("数量不能为负数");

            order.setId(null);

            //添加零售订单的申请发货单详细
            if (order.getOrderType().equals("RETAIL") || order.getOrderType().equals("RETAIL_POLICY")) {

                //检查订单可申请数量是否大于申请数量
                invoiceOrder(order.getOrderId(), order.getInvoiceNum());

                RetailOrder retailOrder = retailOrderService.getById(order.getMainOrderId());
                RetailOrderItem retailOrderItem = retailOrderItemService.getById(order.getOrderId());
                //判断发产品类是否是同一品类
                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(retailOrderItem.getMaterialId());
                if (categoryId == null)
                    categoryId = kingDeeMaterial.getCategoryId();
                if (!categoryId.equals(kingDeeMaterial.getCategoryId()))
                    throw new RemoteServiceException("产品类别不同，无法申请发货");


                if (adminUser.getIsCustomer() && adminUserForceStockService.lambdaQuery()
                        .eq(AdminUserForceStock::getCategoryId, kingDeeMaterial.getCategoryId())
                        .eq(AdminUserForceStock::getCorrespondId,invoiceRequest.getCorrespondId())
                        .eq(AdminUserForceStock::getAdminUserId,adminUser.getAdminUserId())
                        .count() < 1) {
                    //强制仓返回，有强制仓，判断强制是否有库存，有库存都返回0,没返回正常库存
                    List<AdminUserForceStock> list = adminUserForceStockService.lambdaQuery()
                            .eq(AdminUserForceStock::getCategoryId, kingDeeMaterial.getCategoryId())
                            .ne(AdminUserForceStock::getCorrespondId, invoiceRequest.getCorrespondId())
                            .eq(AdminUserForceStock::getAdminUserId,adminUser.getAdminUserId())
                            .list();
                    if (!CollectionUtils.isEmpty(list) ) {
                        for (AdminUserForceStock adminUserForceStock : list) {
                            if (stockCommonLogic.stockCorrespondStatus(null, adminUserForceStock.getCorrespondId(), order.getMaterialId(), null) > 0) {
                                throw new RemoteServiceException("物料规格"+order.getSpecification()+"没有库存请去"+adminUserForceStock.getCorrespondName());
                            }
                        }


                    }
                }



                //判断是否直调发货未完成
                if (retailOrderItem.getIsDirectTransfer().equals(1) && retailOrderItem.getDirectTransferStatus().equals(0))
                    throw new RemoteServiceException(retailOrderItem.getMaterialName() + "直调未完成不能申请发货");

                invoiceRequest.setCustomerNumber(retailOrder.getCustomerNumber());
                invoiceRequest.setCustomerId(retailOrder.getCustomerId());
                invoiceRequest.setCustomerName(retailOrder.getCustomerName());

                order.setMainOrderId(retailOrderItem.getRetailOrderId());
                order.setRefundableQty(order.getInvoiceNum());
                order.setVarietyQty(order.getInvoiceNum());
                order.setInvoiceId(invoiceRequest.getId());
                order.setSaleTypeId(retailOrderItem.getSaleTypeId());
                order.setSaleTypeCode(retailOrderItem.getSaleTypeCode());
                order.setSaleTypeName(retailOrderItem.getSaleTypeName());
                order.setTheTime(retailOrder.getTheTime());
                order.setMaterialName(retailOrderItem.getMaterialName());
                order.setMaterialId(retailOrderItem.getMaterialId());
                order.setMaterialCode(retailOrderItem.getMaterialCode());
                order.setMaterialOldNumber(retailOrderItem.getMaterialOldNumber());
                order.setSpecification(retailOrderItem.getSpecification());
                order.setUnit(retailOrderItem.getUnit());
                order.setPrice(retailOrderItem.getPrice());

                order.setPayAmount(retailOrderItem.getSinglePayPrice()
                        .multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTotalAmount(retailOrderItem.getPrice().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setPayRebateAmount(retailOrderItem.getSingleRebateAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTotalDiscAmount(retailOrderItem.getDiscAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTax(retailOrderItem.getTax());
                order.setSingleRebateAmount(retailOrderItem.getSingleRebateAmount());
                order.setQty(retailOrderItem.getQty());
                order.setSinglePayPrice(retailOrderItem.getSinglePayPrice());
                order.setServiceId(retailOrderItem.getServiceId());
                order.setServiceName(retailOrderItem.getServiceName());
                order.setDiscAmount(retailOrderItem.getDiscAmount());
                order.setKingDeeSeq(retailOrderItem.getKingDeeSeq());
                order.setKingDeeEntryId(retailOrderItem.getKingDeeEntryId());
                order.setK3CategoryId(retailOrderItem.getK3CategoryId());
                order.setK3CategoryName(retailOrderItem.getK3CategoryName());
                order.setK3CategoryNumber(retailOrderItem.getK3CategoryNumber());
                order.setK3ServiceId(retailOrder.getK3ServiceId());
                order.setK3ServiceName(retailOrder.getK3ServiceName());
                order.setCustomerWalletId(retailOrderItem.getCustomerWalletId());
                order.setCustomerWalletName(retailOrderItem.getCustomerWalletName());
                order.setCustomerWalletNumber(retailOrderItem.getCustomerWalletNumber());
                order.setCustomerWalletId2(retailOrderItem.getCustomerWalletId2());
                order.setCustomerWalletName2(retailOrderItem.getCustomerWalletName2());
                order.setFileNo(retailOrderItem.getFileNo());
                if (retailOrder.getType().equals(2)) {
                    order.setPolicyId(retailOrder.getPolicyId());
                    order.setPolicyTitle(retailOrder.getPolicyTitle());
                    order.setPolicyCode(retailOrder.getPolicyCode());
                }

            }
            if ( StringUtils.isEmpty(order.getKingDeeEntryId())) {
                mapBool.put("1","1");
                invoiceRequest.setSyncType(2);
            }else if  (!StringUtils.isEmpty(order.getKingDeeEntryId())){
                mapBool.put("2","2");
            }
            if (mapBool.size() > 1){
                throw new RemoteServiceException("新单旧单发货逻辑更改，需分别发货");
            }
            invoiceApplicationOrders.add(order);
            //增加经销商暂扣库存
            stockCommonLogic.inventoryStockCustomerSuspended(order.getMaterialId(), invoiceRequest.getCustomerId(), order.getRefundableQty());
        }
        invoiceApplicationOrderService.saveBatch(invoiceApplicationOrders);
        invoiceMapper.updateStatus(invoiceRequest.getId());
        invoiceMapper.updateInvoice(invoiceRequest.getId());
        invoiceMapper.updateWithold(invoiceRequest.getId(),Constant.RETAIL_UPDATE);
    }

    /**
     * 检查订单申请数量是否大于
     *
     * @Param
     */
    public void invoiceOrder(String retailId, Integer invoiceNum) {
        //检查订单可申请数量是否大于申请数量
        RetailOrderItem retailOrderItem = retailOrderItemService.getById(retailId);
        Integer integer = invoiceMapper.selectInvoice(retailId);
        if (integer == null)
            integer = 0;
        if (invoiceNum + integer > retailOrderItem.getRefundableQty())
            throw new RemoteServiceException("当前申请数量大于可申请数量,可申请数量"+(retailOrderItem.getRefundableQty()-integer));
    }


    private void checkAdd(List<InvoiceApplicationOrderRequest> orders, String correspondId, String status,String customerId) throws Exception {

            for (InvoiceApplicationOrder order : orders) {

                //查询该仓库库存
                Integer integer = stockCommonLogic.stockCorrespondStatus(order.getOrderId(), correspondId, order.getMaterialId(),customerId);

                if (order.getId() != null) {
                    InvoiceApplicationOrder invoiceApplicationOrder = invoiceApplicationOrderService.getById(order.getId());
                    integer = integer + invoiceApplicationOrder.getInvoiceNum();
                }


                if ((status.equals(ExamineStatusEnum.WAIT.toString()) || status.equals(ExamineStatusEnum.SAVE.toString())) && order.getInvoiceNum() > integer)
                    throw new RemoteServiceException(order.getMaterialName()+"/"+order.getSpecification() + "库存不足");

                if (status.equals(ExamineStatusEnum.OK.toString()) && order.getApprovalNumber() > integer)
                    throw new RemoteServiceException(order.getMaterialName()+"/"+order.getSpecification()  + "库存不足");
            }

    }


    /**
     * 审核查找实时库存
     */
    public void syncInStock(String materialId) throws Exception {
        // 调用即时库存
        RequestApiBean request = k3Logic.getInstance(null, null, KingDeeCons.STOCK_AMOUNT, null, null);
        String filterStr = "FMaterialId = "+materialId;
        request.setFieldKeys("FID,FStockId,FMaterialId,FBaseQty,FStockOrgId");
        request.setStartTime(null);
        request.setEndTime(null);
        request.setFilterString("");
        request.setOrderString("");

        String[] fields = new String[]{"id", "stockId", "materialId", "stockQty", "orgId"};
        List<Stock> objects = k3Logic.allSync(request, fields, Stock.class);
        if (Objects.nonNull(objects)) {
            stockService.saveOrUpdateBatch(objects);

        }else {
            throw new RemoteServiceException("数据为空，异常");
        }

    }


    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        InvoiceApplication byId = invoiceApplicationService.getById(id);
        if (!byId.getExamineStatus().equals("SAVE") && !byId.getExamineStatus().equals(ExamineStatusEnum.FAIL.toString())) {
            throw new RemoteServiceException("该申请单不为保存状态，不可删除");
        }
        List<String> orderId = new ArrayList<>();
        for (InvoiceApplicationOrder invoiceApplicationOrder : invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, id).list()) {
            //减少经销商暂扣库存
            stockCommonLogic.reduceStockCustomerSuspended(invoiceApplicationOrder.getMaterialId(), byId.getCustomerId(), invoiceApplicationOrder.getRefundableQty());

            orderId.add(invoiceApplicationOrder.getOrderId());

        }


        invoiceApplicationService.removeById(id);
        invoiceApplicationOrderService.lambdaUpdate().eq(InvoiceApplicationOrder::getInvoiceId, id).remove();

        for (String s : orderId) {
            invoiceMapper.updateWitholdOrder(s,Constant.RETAIL_UPDATE);
        }

    }

    public void submit(String id, String examineStatus ) throws Exception {
        InvoiceApplication byId = invoiceApplicationService.getById(id);
        if (!byId.getExamineStatus().equals(ExamineStatusEnum.SAVE.toString()) && !byId.getExamineStatus().equals(ExamineStatusEnum.WAIT.toString())) {
            throw new RemoteServiceException("该申请单不为保存或提审状态");
        }
        List<InvoiceApplicationOrder> list = invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, byId.getId()).list();
        List<InvoiceApplicationOrderRequest> invoiceApplicationOrderRequests = BeanUtil.copyToList(list, InvoiceApplicationOrderRequest.class);
        //1查看发货单即时库存是否充足
        if (examineStatus.equals("WAIT")) {
            checkUpdate(invoiceApplicationOrderRequests, byId.getCorrespondId(), examineStatus);
        }

        InvoiceApplication invoiceApplication = new InvoiceApplication();
        invoiceApplication.setId(id);
        invoiceApplication.setExamineStatus(examineStatus);
        invoiceApplicationService.updateById(invoiceApplication);
        invoiceMapper.updateStatus(invoiceApplication.getId());
        invoiceMapper.updateWithold(invoiceApplication.getId(),Constant.RETAIL_UPDATE);
    }

    private void checkUpdate(List<InvoiceApplicationOrderRequest> invoiceApplicationOrderRequests, String correspondId, String examineStatus) throws Exception {
        for (InvoiceApplicationOrder order : invoiceApplicationOrderRequests) {
            //查询订单明细
           /* syncInStock(order.getMaterialId());*/
            //查询该仓库库存
            Integer integer = stockCommonLogic.stockCorrespondStatus(order.getOrderId(), correspondId, order.getMaterialId(),null);


            if ((order.equals(ExamineStatusEnum.WAIT.toString()) || order.equals(ExamineStatusEnum.SAVE.toString())) && order.getInvoiceNum() > (integer + order.getRefundableQty()))
                throw new RemoteServiceException(order.getMaterialName() +order.getSpecification()+ "库存不足");

            if (order.equals(ExamineStatusEnum.OK.toString()) && order.getApprovalNumber() > integer)
                throw new RemoteServiceException(order.getMaterialName()+order.getSpecification() + "库存不足");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void approvalInvoice(InvoiceRequestJson invoiceRequestJson ) throws Exception {
        //保存申请发货单
        InvoiceApplication invoiceApplication = invoiceApplicationService.getById(invoiceRequestJson.getId());
        if (!invoiceApplication.getExamineStatus().equals(ExamineStatusEnum.WAIT.toString())) {
            throw new RemoteServiceException("非审核单，无法审核");
        }


        AdminUserCom adminUser = commonLogic.getAdminUser();

        invoiceRequestJson.setApprovalName(adminUser.getNickName());
        invoiceRequestJson.setApprovalTime(new Date());
        invoiceApplicationService.updateById(invoiceRequestJson);
        for (InvoiceApplicationOrderRequest order : invoiceRequestJson.getOrders()) {
            InvoiceApplicationOrder invoiceApplicationOrder = invoiceApplicationOrderService.getById(order.getId());
            order.setApprovalNumber(invoiceApplicationOrder.getInvoiceNum());
            order.setRefundableQty(order.getApprovalNumber());
            order.setVarietyQty(order.getApprovalNumber());

            order.setPayAmount(invoiceApplicationOrder.getSinglePayPrice()
                    .multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setTotalAmount(invoiceApplicationOrder.getPrice().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setPayRebateAmount(invoiceApplicationOrder.getSingleRebateAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setTotalDiscAmount(invoiceApplicationOrder.getDiscAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setAfterTaxPrice(invoiceApplicationOrder.getSinglePayPrice().subtract(invoiceApplicationOrder.getSinglePayPrice().multiply(invoiceApplicationOrder.getTax())));
            order.setNoTotalAmount(order.getPayAmount().subtract(order.getPayAmount().multiply(invoiceApplicationOrder.getTax())));
            order.setInvoiceExamineStatus(invoiceRequestJson.getExamineStatus());

            Integer integer = stockCommonLogic.stockKingDeeNumber(invoiceApplication.getCorrespondId(), order.getMaterialId());


            if (order.getApprovalNumber() > integer)
                throw new RemoteServiceException(order.getMaterialName()+"/"+order.getSpecification()  + "库存不足");

            invoiceApplicationOrderService.updateById(order);
        }
        if (invoiceRequestJson.getExamineStatus().equals("SAVE"))
            return;

        //查看发货单即时库存是否充足
       // checkAdd(invoiceRequestJson.getOrders(), invoiceApplication.getCorrespondId(), ExamineStatusEnum.OK.toString(),invoiceApplication.getCustomerId());


        //生成发货单
        ShipDocument shipDocument = BeanUtil.toBean(invoiceApplication, ShipDocument.class);
        shipDocument.setExamineStatus(ExamineStatusEnum.OK.toString());
        shipDocument.insert();
        //生成销售出库单
        String yyyyMM = DateUtil.format(new Date(), "yyyyMM");
        String orderWater = yyyyMM.substring(yyyyMM.length() - 4);
        if (redisUtil.get("sales" + orderWater) == null) {
            redisUtil.set("sales" + orderWater, "0000", 60 * 60 * 24 * 31);
        }
        Object water = redisUtil.get("sales" + orderWater);
        String s = pickLogic.generateNum(4, Convert.toStr(water));

        if (salesOrderService.lambdaQuery().eq(SalesOrder::getId, orderWater + s).count() > 0) {
            throw new RemoteServiceException("请勿频繁新增，稍等一会");
        }
        redisUtil.set("sales" + orderWater, s, 60 * 60 * 24 * 31);


        SalesOrder salesOrder = BeanUtil.toBean(invoiceApplication, SalesOrder.class);
        salesOrder.setId(orderWater + s);

        invoiceRequestJson.setSalesId(orderWater + s);
        invoiceRequestJson.setSalesOrderId(orderWater + s);
        invoiceRequestJson.updateById();

        salesOrder.setOrderNo(invoiceApplication.getId());
        salesOrder.setOrderTime(new Date());
        salesOrder.setExamineStatus("WAIT");
        salesOrder.insert();


        for (InvoiceApplicationOrderRequest order : invoiceRequestJson.getOrders()) {

            //增加经销商暂扣库存
            if (order.getRefundableQty() - order.getInvoiceNum() >= 0) {
                stockCommonLogic.inventoryStockCustomerSuspended(order.getMaterialId(), invoiceApplication.getCustomerId(), order.getRefundableQty());
            } else {
                stockCommonLogic.reduceStockCustomerSuspended(order.getMaterialId(), invoiceApplication.getCustomerId(), order.getInvoiceNum() - order.getRefundableQty());
            }

            //因为可能同时审核同一个订单的数据，所以要锁住一个一个订单拿

            Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_APPLICATION+order.getOrderId());
            try {
                if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                    throw new RemoteServiceException("系统繁忙，请稍后再试");
                }
                //变更可退货数量
                if (order.getOrderType().equals("RETAIL") || order.getOrderType().equals("RETAIL_POLICY"))
                    retailOrderLogic.changeRefundableQty(order.getOrderId(), order.getApprovalNumber());

                if (order.getOrderType().equals("PERMU_RETAIL") || order.getOrderType().equals("PERMU_RETAIL_POLICY"))
                    changeDiplaceRefundableQty(order.getOrderId(), order.getApprovalNumber());

                if (order.getOrderType().equals("REQUISITION_RETAIL") || order.getOrderType().equals("REQUISITION_RETAIL_POLICY"))
                    changeRqquisitionRefundableQty(order.getRequisitionItemId(), order.getApprovalNumber());
            } finally {
                obtain.unlock();
            }


            //记录台账记录
            String customerWalletId = null;
            if (order.getOrderType().equals("RETAIL") || order.getOrderType().equals("RETAIL_POLICY")) {
                RetailOrderItem retailOrderItem = retailOrderItemService.getById(order.getOrderId());
                if (retailOrderItem.getRefundableQty().equals("0") && retailOrderItem.getIsDirectTransfer() == false) {
                    order.setPayAmount(
                            retailOrderItem.getPayAmount().subtract(new BigDecimal((retailOrderItem.getHasSendQty() - retailOrderItem.getDirectTransferQty())).multiply(retailOrderItem.getSinglePayPrice())));

                }
                customerWalletId = retailOrderItem.getCustomerWalletId();
            }

            if (order.getOrderType().equals("PERMU_RETAIL") || order.getOrderType().equals("PERMU_RETAIL_POLICY")) {
                DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(order.getOrderId());
                if (displaceOrderItem.getRefundableQty().equals("0")) {
                    order.setPayAmount(
                            displaceOrderItem.getPayAmount().subtract(new BigDecimal((displaceOrderItem.getHasSendQty())).multiply(displaceOrderItem.getSinglePayPrice())));
                }
                customerWalletId = displaceOrderItem.getCustomerWalletId();
            }

            if (order.getOrderType().equals("REQUISITION_RETAIL") || order.getOrderType().equals("REQUISITION_RETAIL_POLICY")) {
                salesOrder.setInvoiceType(3);
                RequisitionOrderItem requisitionOrderItem = requisitionOrderItemService.getById(order.getRequisitionItemId());
                if (requisitionOrderItem.getRefundableQty().equals("0")) {
                    order.setPayAmount(
                            requisitionOrderItem.getPayAmount().subtract(new BigDecimal((requisitionOrderItem.getHasSendQty())).multiply(requisitionOrderItem.getSinglePayPrice())));

                }
                customerWalletId = requisitionOrderItem.getCustomerWalletId();
            }
            CustomerWallet customerWallet = customerWalletService.getById(customerWalletId);
            walletLogic.saveCustomerWalletRecord(customerWallet, order.getPayAmount(), "申请发货单流水", "申请发货单", new Date(), invoiceRequestJson.getId(), 3, "OUT");

            order.updateById();

        }
        salesOrder.updateById();

        List<InvoiceApplicationOrder> list = invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, invoiceApplication.getId()).list();
        List<SalesOrderItem> salesOrders = new ArrayList<>();
        for (InvoiceApplicationOrder invoiceApplicationOrder : list) {
            SalesOrderItem salesOrderItem = BeanUtil.toBean(invoiceApplicationOrder, SalesOrderItem.class);
            salesOrderItem.setSalesOrderNo(salesOrder.getId());
            salesOrderItem.setInvoiceId(salesOrder.getId());
            salesOrderItem.setInvoiceItemId(invoiceApplicationOrder.getId());
            salesOrderItem.setGoodsOrderId(invoiceApplicationOrder.getGoodsOrderId());
            salesOrderItem.setId(null);
            salesOrders.add(salesOrderItem);
        }
        salesOrderItemService.saveBatch(salesOrders);

        //格匠同步采购入库单
        if (invoiceApplication.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_FOSHAN.getCode()) ||
                invoiceApplication.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU.getCode())){
            InvoiceApplication invoiceApplication1 = new InvoiceApplication();
            invoiceApplication1.setId(invoiceApplication.getId());
            invoiceApplication1.setGejiangSync(0);
            invoiceApplication1.updateById();
            InvoiceApplicationSyncGejiang invoiceApplicationSyncGejiang = new InvoiceApplicationSyncGejiang();
            invoiceApplicationSyncGejiang.setInvoiceId(invoiceApplication.getId());
            invoiceApplicationSyncGejiang.setStatus(0);
            invoiceApplicationSyncGejiang.insert();
        }

        //invoiceMapper.updateInvoice(invoiceApplication.getId());
        //invoiceMapper.updateStatus(invoiceApplication.getId());
        //invoiceMapper.updateSalseOrderId(invoiceApplication.getId());
        invoiceMapper.updateTaiZhang(invoiceApplication.getId());
        invoiceMapper.updateWithold(invoiceApplication.getId(),Constant.RETAIL_UPDATE);
    }


    @Transactional(rollbackFor = Exception.class)
    public synchronized void approvalInvoice(InvoiceApplication invoiceApplicationRequest, HttpServletRequest request, String examineStatus, String approvalRemark) throws Exception {
        //保存申请发货单
        InvoiceApplication invoiceApplication = invoiceApplicationService.getById(invoiceApplicationRequest.getId());
        if (!invoiceApplication.getExamineStatus().equals(ExamineStatusEnum.WAIT.toString())) {
            throw new RemoteServiceException("非审核单，无法审核");
        }


        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        invoiceApplicationRequest.setApprovalName(adminUser.getNickName());
        invoiceApplicationRequest.setApprovalTime(new Date());
        invoiceApplicationRequest.setApprovalRemark(approvalRemark);
        invoiceApplicationRequest.setExamineStatus(examineStatus);
        invoiceApplicationService.updateById(invoiceApplicationRequest);
        List<InvoiceApplicationOrder> list = invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, invoiceApplication.getId()).list();
        for (InvoiceApplicationOrder order : list) {
            order.setApprovalNumber(order.getRefundableQty());
            if (order.getApprovalNumber() == null)
                throw new RemoteServiceException("审批数量不能为空");
            InvoiceApplicationOrder invoiceApplicationOrder = invoiceApplicationOrderService.getById(order.getId());
            order.setRefundableQty(order.getApprovalNumber());
            order.setVarietyQty(order.getApprovalNumber());

            order.setPayAmount(invoiceApplicationOrder.getSinglePayPrice()
                    .multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setTotalAmount(invoiceApplicationOrder.getPrice().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setPayRebateAmount(invoiceApplicationOrder.getSingleRebateAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setTotalDiscAmount(invoiceApplicationOrder.getDiscAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setAfterTaxPrice(invoiceApplicationOrder.getSinglePayPrice().subtract(invoiceApplicationOrder.getSinglePayPrice().multiply(invoiceApplicationOrder.getTax())));
            order.setNoTotalAmount(order.getPayAmount().subtract(order.getPayAmount().multiply(invoiceApplicationOrder.getTax())));
            invoiceApplicationOrderService.updateById(order);
        }
        if (examineStatus.equals("SAVE"))
            return;

        //查看发货单即时库存是否充足
        List<InvoiceApplicationOrderRequest> invoiceApplicationOrderRequests = BeanUtil.copyToList(list, InvoiceApplicationOrderRequest.class);
        checkAdd(invoiceApplicationOrderRequests, invoiceApplication.getCorrespondId(), ExamineStatusEnum.OK.toString(),invoiceApplicationRequest.getCustomerId());

        //生成发货单
        ShipDocument shipDocument = BeanUtil.toBean(invoiceApplication, ShipDocument.class);
        shipDocument.setExamineStatus(ExamineStatusEnum.OK.toString());
        shipDocument.insert();
        //生成销售出库单
        String yyyyMM = DateUtil.format(new Date(), "yyyyMM");
        String orderWater = yyyyMM.substring(yyyyMM.length() - 4);
        if (redisUtil.get("sales" + orderWater) == null) {
            redisUtil.set("sales" + orderWater, "0000", 60 * 60 * 24 * 31);
        }
        Object water = redisUtil.get("sales" + orderWater);
        String s = pickLogic.generateNum(4, Convert.toStr(water));

        if (salesOrderService.lambdaQuery().eq(SalesOrder::getId, orderWater + s).count() > 0) {
            throw new RemoteServiceException("请勿频繁新增，稍等一会");
        }
        redisUtil.set("sales" + orderWater, s, 60 * 60 * 24 * 31);


        SalesOrder salesOrder = BeanUtil.toBean(invoiceApplication, SalesOrder.class);
        salesOrder.setId(orderWater + s);
        salesOrder.setOrderNo(invoiceApplication.getId());
        salesOrder.setOrderTime(new Date());
        salesOrder.setExamineStatus("WAIT");
        salesOrder.insert();
        invoiceApplicationRequest.setSalesId(orderWater + s);
        invoiceApplicationRequest.setSalesOrderId(orderWater + s);
        invoiceApplicationRequest.updateById();
        List<SalesOrderItem> salesOrders = new ArrayList<>();
        for (InvoiceApplicationOrder invoiceApplicationOrder : list) {
            SalesOrderItem salesOrderItem = BeanUtil.toBean(invoiceApplicationOrder, SalesOrderItem.class);
            salesOrderItem.setSalesOrderNo(salesOrder.getId());
            salesOrderItem.setInvoiceId(salesOrder.getId());
            salesOrderItem.setInvoiceItemId(invoiceApplicationOrder.getId());
            salesOrderItem.setId(null);
            salesOrders.add(salesOrderItem);
        }
        salesOrderItemService.saveBatch(salesOrders);

        for (InvoiceApplicationOrder order : list) {

            //增加经销商暂扣库存
            if (order.getRefundableQty() - order.getInvoiceNum() >= 0) {
                stockCommonLogic.inventoryStockCustomerSuspended(order.getMaterialId(), invoiceApplication.getCustomerId(), order.getRefundableQty());
            } else {
                stockCommonLogic.reduceStockCustomerSuspended(order.getMaterialId(), invoiceApplication.getCustomerId(), order.getInvoiceNum() - order.getRefundableQty());
            }

            //变更可退货数量
            if (order.getOrderType().equals("RETAIL") || order.getOrderType().equals("RETAIL_POLICY"))
                retailOrderLogic.changeRefundableQty(order.getOrderId(), order.getApprovalNumber());

            if (order.getOrderType().equals("PERMU_RETAIL") || order.getOrderType().equals("PERMU_RETAIL_POLICY"))
                changeDiplaceRefundableQty(order.getOrderId(), order.getApprovalNumber());

            if (order.getOrderType().equals("REQUISITION_RETAIL") || order.getOrderType().equals("REQUISITION_RETAIL_POLICY"))
                changeRqquisitionRefundableQty(order.getRequisitionItemId(), order.getApprovalNumber());
            //记录台账记录
            String customerWalletId = null;
            if (order.getOrderType().equals("RETAIL") || order.getOrderType().equals("RETAIL_POLICY")) {
                RetailOrderItem retailOrderItem = retailOrderItemService.getById(order.getOrderId());
                if (retailOrderItem.getRefundableQty().equals("0") && retailOrderItem.getIsDirectTransfer() == false) {
                    order.setPayAmount(
                            retailOrderItem.getPayAmount().subtract(new BigDecimal((retailOrderItem.getHasSendQty() - retailOrderItem.getDirectTransferQty())).multiply(retailOrderItem.getSinglePayPrice())));
                }
                customerWalletId = retailOrderItem.getCustomerWalletId();
            }

            if (order.getOrderType().equals("PERMU_RETAIL") || order.getOrderType().equals("PERMU_RETAIL_POLICY")) {
                DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(order.getOrderId());
                if (displaceOrderItem.getRefundableQty().equals("0")) {
                    order.setPayAmount(
                            displaceOrderItem.getPayAmount().subtract(new BigDecimal((displaceOrderItem.getHasSendQty())).multiply(displaceOrderItem.getSinglePayPrice())));
                }
                customerWalletId = displaceOrderItem.getCustomerWalletId();
            }

            if (order.getOrderType().equals("REQUISITION_RETAIL") || order.getOrderType().equals("REQUISITION_RETAIL_POLICY")) {
                salesOrder.setInvoiceType(3);
                RequisitionOrderItem requisitionOrderItem = requisitionOrderItemService.getById(order.getRequisitionItemId());
                if (requisitionOrderItem.getRefundableQty().equals("0")) {
                    order.setPayAmount(
                            requisitionOrderItem.getPayAmount().subtract(new BigDecimal((requisitionOrderItem.getHasSendQty())).multiply(requisitionOrderItem.getSinglePayPrice())));
                }
                customerWalletId = requisitionOrderItem.getCustomerWalletId();
            }
            CustomerWallet customerWallet = customerWalletService.getById(customerWalletId);
            walletLogic.saveCustomerWalletRecord(customerWallet, order.getPayAmount(), "申请发货单流水", "申请发货单", new Date(), invoiceApplicationRequest.getId(), 3, "OUT");

            order.updateById();

        }

        //格匠同步采购入库单
        if (invoiceApplication.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_FOSHAN.getCode()) ||
                invoiceApplication.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU.getCode())){
            InvoiceApplication invoiceApplication1 = new InvoiceApplication();
            invoiceApplication1.setId(invoiceApplication.getId());
            invoiceApplication1.setGejiangSync(0);
            invoiceApplication1.updateById();
            InvoiceApplicationSyncGejiang invoiceApplicationSyncGejiang = new InvoiceApplicationSyncGejiang();
            invoiceApplicationSyncGejiang.setInvoiceId(invoiceApplication.getId());
            invoiceApplicationSyncGejiang.setStatus(0);
            invoiceApplicationSyncGejiang.insert();
        }

        salesOrder.updateById();
        invoiceMapper.updateInvoice(invoiceApplication.getId());
        invoiceMapper.updateStatus(invoiceApplication.getId());
        invoiceMapper.updateSalseOrderId(invoiceApplication.getId());
    }

    public void changeRqquisitionRefundableQty(String orderId, Integer approvalNumber) {
        RequisitionOrderItem requisitionOrderItem = requisitionOrderItemService.getById(orderId);
        RetailOrderItem retailOrderItem = retailOrderItemService.getById(requisitionOrderItem.getOrderId());
        if (requisitionOrderItem == null) {
            return;
        }
        if (requisitionOrderItem.getRefundableQty().intValue() < approvalNumber.intValue()) {
            throw new RemoteServiceException("可退货数量不足!");
        }
        requisitionOrderItem.setRefundableQty(requisitionOrderItem.getRefundableQty() - approvalNumber);
        requisitionOrderItem.updateById();

        retailOrderItem.setRefundableQty(retailOrderItem.getRefundableQty() - approvalNumber);
        retailOrderItem.updateById();
    }

    public void changeRqquisitionEnginRefundableQty(String orderId, Integer approvalNumber) {
        RequisitionOrderItem requisitionOrderItem = requisitionOrderItemService.getById(orderId);
        EnginOrderItem enginOrderItem = enginOrderItemService.getById(requisitionOrderItem.getOrderId());
        if (requisitionOrderItem == null) {
            return;
        }
        if (requisitionOrderItem.getRefundableQty().intValue() < approvalNumber.intValue()) {
            throw new RemoteServiceException("可退货数量不足!");
        }
        requisitionOrderItem.setRefundableQty(requisitionOrderItem.getRefundableQty() - approvalNumber);
        requisitionOrderItem.updateById();

        enginOrderItem.setRefundableQty(enginOrderItem.getRefundableQty() - approvalNumber);
        enginOrderItem.updateById();
    }

    public Integer stockNumber(List<String> stockIds, String materialId) {
        List<Stock> list = stockService.lambdaQuery().select(Stock::getStockQty, Stock::getStockId).eq(Stock::getMaterialId, materialId).in(Stock::getStockId, stockIds).list();
        BigDecimal count = new BigDecimal("0");
        for (Stock stock : list) {
            count = count.add(stock.getStockQty());
        }
        return Convert.toInt(count);
    }

    public IPage<InvoiceProjectBean> listProject(Integer automaticStatus,String createBy,String refRegionWork,String approvalName,String categoryId,String k3ServiceId,String refUseUnit, String mainOrderId, String id, String customerName, Integer type, String correspondId, String correspondName, String materialName, String specification, String startTime,
                                                 String endTime, String customerNumber, String examineStatus, String orderType, Integer pageNum, Integer pageSize, String refEnginRecordNo, String serviceId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        //String status = adminUser.getIsCustomer() ? "" : "SAVE";
        IPage<InvoiceProjectBean> invoiceProjectBeanIPage = invoiceMapper.listProject(new Page<>(pageNum, pageSize),automaticStatus,createBy,refRegionWork,approvalName,categoryId,k3ServiceId, refUseUnit, mainOrderId, id, customerName, type, correspondId,
                correspondName, materialName, specification, startTime, endTime, customerNumber, examineStatus, orderType, customerId, adminUser.getServiceIds(),
                refEnginRecordNo, null, serviceId, adminUser.getK3CategoryIds());
        return invoiceProjectBeanIPage;
    }

    public InvoiceProjectBody detailProject(String id) {
        InvoiceProjectBody detail = invoiceMapper.detailProject(id);

            List<SalesOrderPicture> listPicture = salesOrderPictureService.lambdaQuery().eq(SalesOrderPicture::getSalesId, detail.getId()).list();
        detail.setSalesOrderPictures(listPicture);

        return detail;
    }

    /**
     * 检查订单申请数量是否大于
     *
     * @Param
     */
    public void invoiceEnginOrder(String retailId, Integer invoiceNum) {
        //检查订单可申请数量是否大于申请数量
        EnginOrderItem enginOrderItem = enginOrderItemService.getById(retailId);
        Integer integer = invoiceMapper.selectInvoice(retailId);
        if (integer == null)
            integer = 0;
        if (invoiceNum + integer > enginOrderItem.getRefundableQty())
            throw new RemoteServiceException("当前申请数量大于可申请数量,可申请数量"+(enginOrderItem.getRefundableQty() - integer));
    }

    @Transactional(rollbackFor = Exception.class)
    public void addProject(InvoiceRequestJson invoiceRequest ) throws Exception {
        //查看发货单即时库存是否充足
        checkAdd(invoiceRequest.getOrders(), invoiceRequest.getCorrespondId(), invoiceRequest.getExamineStatus(),invoiceRequest.getCustomerId());

        String adminWebsitId = "";
        String customer = "";

        //查询仓库是否符合
        List<String> collect = invoiceRequest.getOrders().stream().map(InvoiceApplicationOrderRequest::getMaterialId).collect(Collectors.toList());
        checkStock(invoiceRequest.getCorrespondId(),collect);


        for (InvoiceApplicationOrder order : invoiceRequest.getOrders()) {
            //添加零售订单的申请发货单详细
            if (order.getOrderType().equals("TRADE") || order.getOrderType().equals("HOME")) {

                EnginOrder enginOrder = enginOrderService.getById(order.getMainOrderId());

                EnginOrderItem enginOrderItem = enginOrderItemService.getById(order.getOrderId());
                adminWebsitId = enginOrder.getAdminWebsitId();
                customer = enginOrder.getCustomerId();
                break;
            }
        }

        AdminUserCom adminUser = commonLogic.getAdminUser();
        //添加发货申请单
        AdminWebsit adminWebsit = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getAdminWebsitId, adminWebsitService.getById(adminWebsitId).getAdminWebsitId()).one();
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(customer);

        if (adminWebsit == null || StringUtils.isEmpty(adminWebsit.getWebsitNumber()))
            throw new RemoteServiceException("该经销商不在区域范围");

        if (kingDeeCustomer != null) {
            invoiceRequest.setCustomerId(kingDeeCustomer.getId());
            invoiceRequest.setCustomerName(kingDeeCustomer.getName());
            invoiceRequest.setCustomerNumber(kingDeeCustomer.getNumber());
        }

        //生成订单流水号
        String invoiceOrder = generateInvoiceOrder(adminWebsit.getWebsitNumber());


        invoiceRequest.setId(adminWebsit.getWebsitNumber()+invoiceOrder);
        invoiceRequest.setOrderTime(new Date());
        boolean save = invoiceApplicationService.save(invoiceRequest);


        //存储图片
        if (!CollectionUtils.isEmpty(invoiceRequest.getSalesOrderPictures())){
            for (SalesOrderPicture salesOrderPicture : invoiceRequest.getSalesOrderPictures()) {
                salesOrderPicture.setSalesId(invoiceRequest.getId());
            }
            salesOrderPictureService.saveBatch(invoiceRequest.getSalesOrderPictures());
        }


        Map<String, String> map = new HashMap<>();
        Map<String, String> mapBool = new HashMap<>();

        //存入订单明细
        List<InvoiceApplicationOrder> invoiceApplicationOrders = new ArrayList<>();
        for (InvoiceApplicationOrder order : invoiceRequest.getOrders()) {

            if (order.getInvoiceNum() == null || order.getInvoiceNum().equals(0))
                continue;

            order.setRefundableQty(order.getInvoiceNum());

            //添加零售订单的申请发货单详细
            if (order.getOrderType().equals("TRADE") || order.getOrderType().equals("HOME")) {

                EnginOrder enginOrder = enginOrderService.getById(order.getMainOrderId());
                EnginOrderItem enginOrderItem = enginOrderItemService.getById(order.getOrderId());

                if (enginOrderItem.getQty() < (enginOrderItem.getRefundableQty()+enginOrderItem.getHasSendQty()))
                    throw new RemoteServiceException("可退数量大于了订单数量!");



                if (!enginOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()) && enginOrder.getIsPlanOrder())
                    throw new RemoteServiceException("订单不属于审核状态，无法发货");

                invoiceEnginOrder(enginOrderItem.getId(), order.getInvoiceNum());

                //判断发货品类是否是同一品类
                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(enginOrderItem.getMaterialId());

                map.put(kingDeeMaterial.getCategoryNumber(),kingDeeMaterial.getCategoryName());


                if (adminUser.getIsCustomer() && adminUserForceStockService.lambdaQuery()
                        .eq(AdminUserForceStock::getCategoryId, kingDeeMaterial.getCategoryId())
                        .eq(AdminUserForceStock::getCorrespondId,invoiceRequest.getCorrespondId())
                        .eq(AdminUserForceStock::getAdminUserId,adminUser.getAdminUserId())
                        .count() < 1) {
                    //强制仓返回，有强制仓，判断强制是否有库存，有库存都返回0,没返回正常库存
                    List<AdminUserForceStock> list = adminUserForceStockService.lambdaQuery()
                            .eq(AdminUserForceStock::getCategoryId, kingDeeMaterial.getCategoryId())
                            .ne(AdminUserForceStock::getCorrespondId, invoiceRequest.getCorrespondId())
                            .eq(AdminUserForceStock::getAdminUserId,adminUser.getAdminUserId())
                            .list();
                    if (!CollectionUtils.isEmpty(list) ) {
                        for (AdminUserForceStock adminUserForceStock : list) {
                            if (stockCommonLogic.stockCorrespondStatus(null, adminUserForceStock.getCorrespondId(), order.getMaterialId(), null) > 0) {
                                throw new RemoteServiceException("物料规格"+order.getSpecification()+"没有库存请去"+adminUserForceStock.getCorrespondName());
                            }
                        }


                    }
                }


                //判断是否直调发货未完成
                if (enginOrderItem.getIsDirectTransfer().equals(1) && enginOrderItem.getDirectTransferStatus().equals(0))
                    throw new RemoteServiceException(enginOrderItem.getMaterialName() + "直调未完成不能申请发货");


                invoiceRequest.setEnginOrderType(enginOrder.getEnginOrderType());
                invoiceRequest.setRefEnginRecordNo(enginOrder.getRefEnginRecordNo());
                invoiceRequest.setRefRegionWork(enginOrder.getRefRegionWork());
                invoiceRequest.setRefProjectCategory(enginOrder.getRefProjectCategory());
                invoiceRequest.setRefBuyUnitName(enginOrder.getRefBuyUnitName());
                invoiceRequest.setRefDeclareNo(enginOrder.getRefDeclareNo());
                invoiceRequest.setRefFactoryNo(enginOrder.getRefFactoryNo());
                invoiceRequest.setRefInstallAddress(enginOrder.getRefInstallAddress());
                invoiceRequest.setRefLinkman(enginOrder.getRefLinkman());
                invoiceRequest.setRefMachineType(enginOrder.getRefMachineType());
                invoiceRequest.setRefOtherAnnexIdea(enginOrder.getRefOtherAnnexIdea());
                invoiceRequest.setRefPhone(enginOrder.getRefPhone());
                invoiceRequest.setRefPowerCategory(enginOrder.getRefPowerCategory());
                invoiceRequest.setRefProjectName(enginOrder.getRefProjectName());
                invoiceRequest.setRefProjectNo(enginOrder.getRefProjectNo());
                invoiceRequest.setRefProjectNote(enginOrder.getRefProjectNote());
                invoiceRequest.setRefProjectType(enginOrder.getRefProjectType());
                invoiceRequest.setRefPromiseProvide(enginOrder.getRefPromiseProvide());
                invoiceRequest.setRefPromiseStatus(enginOrder.getRefPromiseStatus());
                invoiceRequest.setRefTel(enginOrder.getRefTel());
                invoiceRequest.setRefTradeCategory(enginOrder.getRefTradeCategory());
                invoiceRequest.setRefUseUnit(enginOrder.getRefUseUnit());
                invoiceRequest.setEnginOrderNo(enginOrder.getEnginOrderNo());
                invoiceRequest.setFileNo(enginOrder.getFileNo());
                invoiceRequest.setEnginFileNo(enginOrder.getFileNo());
                invoiceRequest.setEnginOrderDate(enginOrder.getOrderDate());
                invoiceRequest.setConfirmBy(enginOrder.getConfirmBy());
                invoiceRequest.setConfirmName(enginOrder.getConfirmName());
                invoiceRequest.setConfirmTime(enginOrder.getConfirmTime());
                invoiceRequest.setExamineNote(enginOrder.getExamineNote());
                invoiceRequest.setCustomerNumber(enginOrder.getCustomerNumber());
                invoiceRequest.setCustomerId(enginOrder.getCustomerId());
                invoiceRequest.setCustomerName(enginOrder.getCustomerName());

                order.setMainOrderId(enginOrder.getEnginOrderId());
                order.setInvoiceId(invoiceRequest.getId());
                order.setSaleTypeId(enginOrderItem.getSaleTypeId());
                order.setSaleTypeCode(enginOrderItem.getSaleTypeCode());
                order.setSaleTypeName(enginOrderItem.getSaleTypeName());
                order.setTheTime(enginOrder.getOrderDate());
                order.setMaterialName(enginOrderItem.getMaterialName());
                order.setMaterialId(enginOrderItem.getMaterialId());
                order.setMaterialCode(enginOrderItem.getMaterialNumber());
                order.setMaterialOldNumber(enginOrderItem.getMaterialOldNumber());
                order.setSpecification(enginOrderItem.getSpecification());
                order.setUnit(enginOrderItem.getUnit());

                order.setPayAmount(enginOrderItem.getSinglePayPrice()
                        .multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTotalAmount(enginOrderItem.getPrice().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setPayRebateAmount(enginOrderItem.getSingleRebateAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTotalDiscAmount(enginOrderItem.getDiscAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));
                order.setTax(enginOrderItem.getTax());

                order.setQty(enginOrderItem.getQty());
                order.setSingleRebateAmount(enginOrderItem.getSingleRebateAmount());
                order.setPrice(enginOrderItem.getPrice());
                order.setSinglePayPrice(enginOrderItem.getSinglePayPrice());
                order.setSingleDepositAmount(enginOrderItem.getSingleDepositAmount());
                order.setServiceId(enginOrderItem.getServiceId());
                order.setRefundableQty(order.getInvoiceNum());
                order.setVarietyQty(order.getInvoiceNum());
                order.setServiceName(enginOrderItem.getServiceName());
                order.setDiscAmount(enginOrderItem.getDiscAmount());
                order.setKingDeeSeq(enginOrderItem.getKingDeeSeq());
                order.setKingDeeEntryId(enginOrderItem.getKingDeeEntryId());
                order.setTotalAmount(enginOrderItem.getTotalAmount().divide(new BigDecimal(Convert.toStr(order.getQty()))).multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));
                order.setK3ServiceId(enginOrder.getServiceId());
                order.setK3ServiceName(enginOrder.getServiceName());
                order.setK3CategoryId(enginOrderItem.getK3CategoryId());
                order.setK3CategoryNumber(enginOrderItem.getK3CategoryNumber());
                order.setK3CategoryName(enginOrderItem.getK3CategoryName());
                order.setCustomerWalletId(enginOrderItem.getCustomerWalletId());
                order.setCustomerWalletName(enginOrderItem.getCustomerWalletName());
                order.setCustomerWalletNumber(enginOrderItem.getCustomerWalletNumber());
                order.setCustomerWalletId2(enginOrderItem.getCustomerWalletId2());
                order.setCustomerWalletName2(enginOrderItem.getCustomerWalletName2());
                order.setFileNo(enginOrder.getFileNo());
                order.setRealMaterialId(enginOrderItem.getRealMaterialId());
                order.setRealMaterialName(enginOrderItem.getRealMaterialName());
                order.setRealMaterialNumber(enginOrderItem.getMaterialNumber());
                order.setRealMaterialOldNumber(enginOrderItem.getMaterialOldNumber());
                order.setRealSpecification(enginOrderItem.getRealSpecification());
                order.setRetiredQty(0);

            }

            if ( StringUtils.isEmpty(order.getKingDeeEntryId())) {
                mapBool.put("1","1");
                invoiceRequest.setSyncType(2);
            }else if  (!StringUtils.isEmpty(order.getKingDeeEntryId())){
                mapBool.put("2","2");
            }
            if (mapBool.size() > 1){
                throw new RemoteServiceException("新单旧单发货逻辑更改，需分别发货");
            }
            invoiceApplicationOrders.add(order);
            //增加经销商暂扣库存
            stockCommonLogic.inventoryStockCustomerSuspended(order.getMaterialId(), invoiceRequest.getCustomerId(), order.getRefundableQty());

            //更改预留单预留数量
            reservedLogic.reduceReserved(order, invoiceRequest.getCorrespondId());
        }

        if (map.size() > 1)
            throw new RemoteServiceException("非同一存货类别不能一起申请发货，请分开申请发货后。");

        List<String> collect1 = invoiceApplicationOrders.stream().map(InvoiceApplicationOrder::getMaterialId).distinct().collect(Collectors.toList());
        if (collect1.size() != invoiceApplicationOrders.size()) {
            throw new RemoteServiceException("同一物料不能一起申请发货，请分开申请发货后。");
        }

        invoiceApplicationService.updateById(invoiceRequest);
        invoiceApplicationOrderService.saveBatch(invoiceApplicationOrders);
        List<DepositManageRecordBean> depositManageRecordList = new ArrayList<>();

        for (InvoiceApplicationOrder order : invoiceRequest.getOrders()) {

            if (order.getInvoiceNum() == null || order.getInvoiceNum().equals(0))
                continue;

            if (order.getOrderType().equals("PERMU_HOME")) {
                DisplaceOrder displaceOrder = displaceOrderService.getById(order.getMainOrderId());
                DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(order.getOrderId());
                DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                depositManageRecordBean.handleEnginOrderItem(displaceOrder, displaceOrderItem, order.getInvoiceNum(), displaceOrderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(order.getInvoiceNum()))));
                depositManageRecordList.add(depositManageRecordBean);
            }
            if (order.getOrderType().equals("REQUISITION_HOME")) {
                RequisitionOrder requisitionOrder = requisitionOrderService.getById(order.getMainOrderId());
                RequisitionOrderItem requisitionOrderItemServiceById = requisitionOrderItemService.getById(order.getOrderId());
                EnginOrder enginOrder = enginOrderService.getById(requisitionOrderItemServiceById.getMainOrderId());
                EnginOrderItem orderItem = enginOrderItemService.getById(requisitionOrderItemServiceById.getOrderId());
                DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                depositManageRecordBean.setConsumNo(order.getInvoiceId());
                depositManageRecordBean.handleEnginOrderItem(enginOrder, orderItem, order.getInvoiceNum(), orderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(order.getInvoiceNum()))));
                depositManageRecordList.add(depositManageRecordBean);
            }

            //工程扣除押金
            if (order.getOrderType().equals("HOME")) {

                EnginOrder enginOrder = enginOrderService.getById(order.getMainOrderId());
                EnginOrderItem orderItem = enginOrderItemService.getById(order.getOrderId());
                DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                depositManageRecordBean.setConsumNo(order.getInvoiceId());
                depositManageRecordBean.handleEnginOrderItem(enginOrder, orderItem, order.getInvoiceNum(), orderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(order.getInvoiceNum()))));
                if (invoiceRequest.getType() != null && invoiceRequest.getType().equals(3)){

                    depositManageRecordBean.setOrderItem(orderItem);
                }

                depositManageRecordList.add(depositManageRecordBean);
            }
        }
        if (!CollectionUtils.isEmpty(depositManageRecordList))
            depositManageLogic.addDepositAmount(invoiceRequest.getRefEnginRecordNo(), depositManageRecordList);
        invoiceMapper.updateStatus(invoiceRequest.getId());
        invoiceMapper.updateInvoice(invoiceRequest.getId());
        invoiceMapper.updateWithold(invoiceRequest.getId(),Constant.ENGIN_UPDATE);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateProject(InvoiceRequestJson invoiceRequest, HttpServletRequest request) throws Exception {
        //1查看发货单即时库存是否充足
        checkAdd(invoiceRequest.getOrders(), invoiceRequest.getCorrespondId(), invoiceRequest.getExamineStatus(),invoiceRequest.getCustomerId());

        InvoiceApplication byId = invoiceApplicationService.getById(invoiceRequest.getId());

        if (byId.getIsRe().equals("YES"))
            throw new RemoteServiceException("预留发货单不可编辑改变预留数量");

        //3，添加发货申请单
        //3，添加发货申请单
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        KingDeeCustomer kingDeeCustomer = kingDeeCustomerService.getById(adminUser.getCustomerId());

        if (kingDeeCustomer != null) {
            invoiceRequest.setCustomerId(adminUser.getCustomerId());
            invoiceRequest.setCustomerName(adminUser.getCustomerName());
            invoiceRequest.setCustomerNumber(kingDeeCustomer.getNumber());
        }

        List<InvoiceApplicationOrder> applicationOrders = invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, invoiceRequest.getId()).list();
        List<DepositManageRecordBean> depositManageRecordList = new ArrayList<>();

            for (InvoiceApplicationOrder order : applicationOrders) {

                order.setRefundableQty(order.getInvoiceNum());

                if (order.getOrderType().equals("PERMU_HOME")) {
                    DisplaceOrder displaceOrder = displaceOrderService.getById(order.getMainOrderId());
                    DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(order.getOrderId());
                    DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                    depositManageRecordBean.setConsumNo(order.getInvoiceId());
                    depositManageRecordBean.handleEnginOrderItem(displaceOrder, displaceOrderItem, order.getInvoiceNum(), displaceOrderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(order.getInvoiceNum()))));
                    depositManageRecordList.add(depositManageRecordBean);
                }

                if (order.getOrderType().equals("REQUISITION_HOME")) {
                    RequisitionOrder requisitionOrder = requisitionOrderService.getById(order.getMainOrderId());
                    RequisitionOrderItem requisitionOrderItemServiceById = requisitionOrderItemService.getById(order.getOrderId());
                    EnginOrder enginOrder = enginOrderService.getById(requisitionOrderItemServiceById.getMainOrderId());
                    EnginOrderItem orderItem = enginOrderItemService.getById(requisitionOrderItemServiceById.getOrderId());
                    DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                    depositManageRecordBean.setConsumNo(order.getInvoiceId());
                    depositManageRecordBean.handleEnginOrderItem(enginOrder, orderItem, order.getInvoiceNum(), orderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(order.getInvoiceNum()))));
                    depositManageRecordList.add(depositManageRecordBean);
                }
                //工程扣除押金
                if (order.getOrderType().equals("HOME")) {
                    EnginOrder enginOrder = enginOrderService.getById(order.getMainOrderId());
                    EnginOrderItem orderItem = enginOrderItemService.getById(order.getOrderId());
                    DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                    depositManageRecordBean.setConsumNo(order.getInvoiceId());
                    depositManageRecordBean.handleEnginOrderItem(enginOrder, orderItem, order.getInvoiceNum(), orderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(order.getInvoiceNum()))));
                    depositManageRecordList.add(depositManageRecordBean);
                }
            }
        InvoiceApplication invoiceApplicationServiceById = invoiceApplicationService.getById(invoiceRequest.getId());
        if (!CollectionUtils.isEmpty(depositManageRecordList))
        depositManageLogic.reduceDepositAmount(invoiceApplicationServiceById.getRefEnginRecordNo(), depositManageRecordList);

        boolean save = invoiceApplicationService.updateById(invoiceRequest);
        invoiceApplicationOrderService.lambdaUpdate().eq(InvoiceApplicationOrder::getInvoiceId, invoiceRequest.getId()).remove();

        //存储图片
        salesOrderPictureService.lambdaUpdate().eq(SalesOrderPicture::getSalesId,invoiceRequest.getId()).remove();
        if (!CollectionUtils.isEmpty(invoiceRequest.getSalesOrderPictures())){
            for (SalesOrderPicture salesOrderPicture : invoiceRequest.getSalesOrderPictures()) {
                salesOrderPicture.setSalesId(invoiceRequest.getId());
            }
            salesOrderPictureService.saveBatch(invoiceRequest.getSalesOrderPictures());
        }

        String categoryId = null;

        Map<String, String> map = new HashMap<>();
        Map<String, String> mapBool = new HashMap<>();

        //存入订单明细
        List<InvoiceApplicationOrder> invoiceApplicationOrders = new ArrayList<>();
        for (InvoiceApplicationOrder order : invoiceRequest.getOrders()) {

            if (order.getInvoiceNum() == null || order.getInvoiceNum().equals(0))
                continue;

            order.setTheTime(new Date());
            order.setRefundableQty(order.getInvoiceNum());


            //添加零售订单的申请发货单详细
            if (order.getOrderType().equals("TRADE") || order.getOrderType().equals("HOME")) {

                map.put("2", order.getOrderType());
                EnginOrder enginOrder = enginOrderService.getById(order.getMainOrderId());
                EnginOrderItem enginOrderItem = enginOrderItemService.getById(order.getOrderId());

                invoiceEnginOrder(enginOrderItem.getId(), order.getInvoiceNum());

                //判断发货品类是否是同一品类
                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(enginOrderItem.getMaterialId());
                if (categoryId == null)
                    categoryId = kingDeeMaterial.getCategoryId();
                if (!categoryId.equals(kingDeeMaterial.getCategoryId()))
                    throw new RemoteServiceException("产品类别不同，无法申请发货");

                if (adminUser.getIsCustomer() && stockForceCategoryService.lambdaQuery()
                        .eq(StockForceCategory::getCategoryId, kingDeeMaterial.getCategoryId())
                        .eq(StockForceCategory::getCorrespondId,invoiceRequest.getCorrespondId()).count() < 1) {
                    //强制仓返回，有强制仓，判断强制是否有库存，有库存都返回0,没返回正常库存
                    List<StockForceCategory> list = stockForceCategoryService.lambdaQuery()
                            .eq(StockForceCategory::getCategoryId, kingDeeMaterial.getCategoryId())
                            .ne(StockForceCategory::getCorrespondId, invoiceRequest.getCorrespondId()).list();
                    if (!CollectionUtils.isEmpty(list) ) {
                        for (StockForceCategory stockForceCategory : list) {
                            if (stockCommonLogic.stockCorrespondStatus(null, stockForceCategory.getCorrespondId(), order.getMaterialId(), null) > 0) {
                                throw new RemoteServiceException("物料规格"+order.getSpecification()+"没有库存请去"+stockForceCategory.getCorrespondName());
                            }
                        }


                    }
                }


                //判断是否直调发货未完成
                if (enginOrderItem.getIsDirectTransfer().equals(1) && enginOrderItem.getDirectTransferStatus().equals(0))
                    throw new RemoteServiceException(enginOrderItem.getMaterialName() + "直调未完成不能申请发货");


                invoiceRequest.setEnginOrderType(enginOrder.getEnginOrderType());
                invoiceRequest.setRefEnginRecordNo(enginOrder.getRefEnginRecordNo());
                invoiceRequest.setRefRegionWork(enginOrder.getRefRegionWork());
                invoiceRequest.setRefProjectCategory(enginOrder.getRefProjectCategory());
                invoiceRequest.setRefBuyUnitName(enginOrder.getRefBuyUnitName());
                invoiceRequest.setRefDeclareNo(enginOrder.getRefDeclareNo());
                invoiceRequest.setRefFactoryNo(enginOrder.getRefFactoryNo());
                invoiceRequest.setRefInstallAddress(enginOrder.getRefInstallAddress());
                invoiceRequest.setRefLinkman(enginOrder.getRefLinkman());
                invoiceRequest.setRefMachineType(enginOrder.getRefMachineType());
                invoiceRequest.setRefOtherAnnexIdea(enginOrder.getRefOtherAnnexIdea());
                invoiceRequest.setRefPhone(enginOrder.getRefPhone());
                invoiceRequest.setRefPowerCategory(enginOrder.getRefPowerCategory());
                invoiceRequest.setRefProjectName(enginOrder.getRefProjectName());
                invoiceRequest.setRefProjectNo(enginOrder.getRefProjectNo());
                invoiceRequest.setRefProjectNote(enginOrder.getRefProjectNote());
                invoiceRequest.setRefProjectType(enginOrder.getRefProjectType());
                invoiceRequest.setRefPromiseProvide(enginOrder.getRefPromiseProvide());
                invoiceRequest.setRefPromiseStatus(enginOrder.getRefPromiseStatus());
                invoiceRequest.setRefTel(enginOrder.getRefTel());
                invoiceRequest.setRefTradeCategory(enginOrder.getRefTradeCategory());
                invoiceRequest.setRefUseUnit(enginOrder.getRefUseUnit());
                invoiceRequest.setEnginOrderNo(enginOrder.getEnginOrderNo());
                invoiceRequest.setFileNo(enginOrder.getFileNo());
                invoiceRequest.setCustomerNumber(enginOrder.getCustomerNumber());
                invoiceRequest.setCustomerId(enginOrder.getCustomerId());
                invoiceRequest.setCustomerName(enginOrder.getCustomerName());

                order.setMainOrderId(enginOrder.getEnginOrderId());
                order.setInvoiceId(invoiceRequest.getId());
                order.setSaleTypeId(enginOrderItem.getSaleTypeId());
                order.setSaleTypeCode(enginOrderItem.getSaleTypeCode());
                order.setSaleTypeName(enginOrderItem.getSaleTypeName());
                order.setTheTime(enginOrder.getOrderDate());
                order.setMaterialName(enginOrderItem.getMaterialName());
                order.setMaterialId(enginOrderItem.getMaterialId());
                order.setMaterialCode(enginOrderItem.getMaterialNumber());
                order.setMaterialOldNumber(enginOrderItem.getMaterialOldNumber());
                order.setSpecification(enginOrderItem.getSpecification());
                order.setUnit(enginOrderItem.getUnit());

                order.setPayAmount(enginOrderItem.getSinglePayPrice()
                        .multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTotalAmount(enginOrderItem.getPrice().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setPayRebateAmount(enginOrderItem.getSingleRebateAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTotalDiscAmount(enginOrderItem.getDiscAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));
                order.setTax(enginOrderItem.getTax());

                order.setQty(enginOrderItem.getQty());
                order.setSingleRebateAmount(enginOrderItem.getSingleRebateAmount());
                order.setPrice(enginOrderItem.getPrice());
                order.setSinglePayPrice(enginOrderItem.getSinglePayPrice());
                order.setSingleDepositAmount(enginOrderItem.getSingleDepositAmount());
                order.setServiceId(enginOrderItem.getServiceId());
                order.setRefundableQty(order.getInvoiceNum());
                order.setVarietyQty(order.getInvoiceNum());
                order.setServiceName(enginOrderItem.getServiceName());
                order.setDiscAmount(enginOrderItem.getDiscAmount());
                order.setKingDeeSeq(enginOrderItem.getKingDeeSeq());
                order.setKingDeeEntryId(enginOrderItem.getKingDeeEntryId());
                order.setTotalAmount(enginOrderItem.getTotalAmount().divide(new BigDecimal(Convert.toStr(order.getQty()))).multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));
                order.setK3ServiceId(enginOrder.getServiceId());
                order.setK3ServiceName(enginOrder.getServiceName());
                order.setK3CategoryId(enginOrderItem.getK3CategoryId());
                order.setK3CategoryName(enginOrderItem.getK3CategoryName());
                order.setK3CategoryNumber(enginOrderItem.getK3CategoryNumber());
                order.setCustomerWalletId(enginOrderItem.getCustomerWalletId());
                order.setCustomerWalletName(enginOrderItem.getCustomerWalletName());
                order.setCustomerWalletNumber(enginOrderItem.getCustomerWalletNumber());
                order.setCustomerWalletId2(enginOrderItem.getCustomerWalletId2());
                order.setCustomerWalletName2(enginOrderItem.getCustomerWalletName2());
                order.setRealMaterialId(enginOrderItem.getRealMaterialId());
                order.setRealMaterialName(enginOrderItem.getRealMaterialName());
                order.setRealMaterialNumber(enginOrderItem.getMaterialNumber());
                order.setRealMaterialOldNumber(enginOrderItem.getMaterialOldNumber());
                order.setRealSpecification(enginOrderItem.getRealSpecification());

            }
            //置换单存入申请发货单详细
            if (order.getOrderType().equals("PERMU_TRADE") || order.getOrderType().equals("PERMU_HOME")) {
                map.put("2", order.getOrderType());
                DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(order.getOrderId());
                DisplaceOrder displaceOrder = displaceOrderService.getById(order.getMainOrderId());
                EnginOrder one = enginOrderService.lambdaQuery().eq(EnginOrder::getEnginOrderNo, displaceOrderItem.getOrderNo()).one();

                //判断发货品类是否是同一品类
                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(displaceOrderItem.getMaterialId());
                if (categoryId == null)
                    categoryId = kingDeeMaterial.getCategoryId();
                if (!categoryId.equals(kingDeeMaterial.getCategoryId()))
                    throw new RemoteServiceException("产品类别不同，无法申请发货");

                invoiceRequest.setEnginOrderType(one.getEnginOrderType());
                invoiceRequest.setRefEnginRecordNo(displaceOrder.getEnginRecordNo());
                invoiceRequest.setEnginOrderNo(displaceOrder.getDisplaceOrderId());
                invoiceRequest.setFileNo(one.getFileNo());
                invoiceRequest.setCustomerNumber(displaceOrder.getCustomerNumber());
                invoiceRequest.setCustomerId(displaceOrder.getCustomerId());
                invoiceRequest.setCustomerName(displaceOrder.getCustomerName());


                order.setMainOrderId(displaceOrderItem.getParentId());
                order.setInvoiceId(invoiceRequest.getId());
                order.setSaleTypeId(displaceOrderItem.getSaleTypeId());
                order.setSaleTypeCode(displaceOrderItem.getSaleTypeCode());
                order.setSaleTypeName(displaceOrderItem.getSaleTypeName());
                order.setTheTime(displaceOrder.getOrderDate());
                order.setMaterialName(displaceOrderItem.getMaterialName());
                order.setMaterialId(displaceOrderItem.getMaterialId());
                order.setMaterialCode(displaceOrderItem.getMaterialNumber());
                order.setMaterialOldNumber(displaceOrderItem.getMaterialOldNumber());
                order.setSpecification(displaceOrderItem.getSpecification());
                order.setUnit(displaceOrderItem.getUnit());
                order.setPayAmount(displaceOrderItem.getSinglePayPrice()
                        .multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTotalAmount(displaceOrderItem.getPrice().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setPayRebateAmount(displaceOrderItem.getSingleRebateAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTotalDiscAmount(displaceOrderItem.getDiscAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));
                order.setTax(displaceOrderItem.getTax());

                order.setQty(displaceOrderItem.getQty());
                order.setSingleRebateAmount(displaceOrderItem.getSingleRebateAmount());

                order.setQty(displaceOrderItem.getQty());
                order.setRefundableQty(order.getInvoiceNum());
                order.setVarietyQty(order.getInvoiceNum());
                order.setPrice(displaceOrderItem.getPrice());
                order.setSinglePayPrice(displaceOrderItem.getSinglePayPrice());
                order.setSingleDepositAmount(displaceOrderItem.getSingleDepositAmount());
                order.setServiceId(displaceOrderItem.getServiceId());
                order.setServiceName(displaceOrderItem.getServiceName());
                order.setDiscAmount(displaceOrderItem.getDiscAmount());
                order.setKingDeeSeq(displaceOrderItem.getKingDeeSeq());
                order.setKingDeeEntryId(displaceOrderItem.getKingDeeEntryId());
                order.setTotalAmount(displaceOrderItem.getTotalAmount().divide(new BigDecimal(Convert.toStr(order.getQty()))).multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));
                order.setCustomerWalletId(displaceOrderItem.getCustomerWalletId());
                order.setCustomerWalletName(displaceOrderItem.getCustomerWalletName());
                order.setCustomerWalletNumber(displaceOrderItem.getCustomerWalletNumber());
                order.setCustomerWalletId2(displaceOrderItem.getCustomerWalletId2());
                order.setCustomerWalletName2(displaceOrderItem.getCustomerWalletName2());

            }

            //调拨单存入申请发货单详细
            if (order.getOrderType().equals("REQUISITION_TRADE") || order.getOrderType().equals("REQUISITION_HOME")) {

                map.put("1", order.getOrderType());
                //检查订单可申请数量是否大于申请数量
                invoiceRequisitionOrder(order.getOrderId(), order.getInvoiceNum());

                EnginOrder enginOrder = enginOrderService.getById(order.getMainOrderId());
                EnginOrderItem enginOrderItem = enginOrderItemService.getById(order.getOrderId());

                RequisitionOrderItem requisitionOrderItem = requisitionOrderItemService.lambdaQuery().eq(RequisitionOrderItem::getOrderId, order.getOrderId()).one();
                RequisitionOrder requisitionOrder = requisitionOrderService.getById(requisitionOrderItem.getRequisitionOrderId());
                //判断发货品类是否是同一品类
                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(requisitionOrderItem.getMaterialId());
                if (categoryId == null)
                    categoryId = kingDeeMaterial.getCategoryId();
                if (!categoryId.equals(kingDeeMaterial.getCategoryId()))
                    throw new RemoteServiceException("产品类别不同，无法申请发货");

                EnginOrder one = enginOrderService.getById(requisitionOrder.getMainOrderId());
                invoiceRequest.setEnginOrderType(one.getEnginOrderType());
                invoiceRequest.setRefEnginRecordNo(one.getRefEnginRecordNo());
                invoiceRequest.setEnginOrderNo(one.getEnginOrderNo());
                invoiceRequest.setFileNo(one.getFileNo());
                invoiceRequest.setCustomerNumber(requisitionOrder.getCustomerNumber());
                invoiceRequest.setCustomerId(requisitionOrder.getCustomerId());
                invoiceRequest.setCustomerName(requisitionOrder.getCustomerName());


                order.setMainOrderId(requisitionOrder.getOrderNo());
                order.setOrderId(requisitionOrderItem.getOrderId());
                order.setRequisitionId(requisitionOrder.getId());
                order.setRequisitionItemId(requisitionOrderItem.getId());
                order.setInvoiceId(invoiceRequest.getId());
                order.setSaleTypeId(requisitionOrderItem.getSaleTypeId());
                order.setSaleTypeCode(requisitionOrderItem.getSaleTypeCode());
                order.setSaleTypeName(requisitionOrderItem.getSaleTypeName());
                order.setTheTime(requisitionOrder.getOrderTime());
                order.setMaterialName(requisitionOrderItem.getMaterialName());
                order.setMaterialId(requisitionOrderItem.getMaterialId());
                order.setMaterialCode(requisitionOrderItem.getMaterialCode());
                order.setMaterialOldNumber(requisitionOrderItem.getMaterialOldNumber());
                order.setSpecification(requisitionOrderItem.getSpecification());
                order.setUnit(requisitionOrderItem.getUnit());
                order.setPrice(requisitionOrderItem.getPrice());

                order.setPayAmount(requisitionOrderItem.getSinglePayPrice()
                        .multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTotalAmount(requisitionOrderItem.getPrice().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setPayRebateAmount(requisitionOrderItem.getSingleRebateAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTotalDiscAmount(requisitionOrderItem.getDiscAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

                order.setTax(requisitionOrderItem.getTax());
                order.setSingleRebateAmount(requisitionOrderItem.getSingleRebateAmount());
                order.setQty(requisitionOrderItem.getQty());
                order.setRefundableQty(order.getInvoiceNum());
                order.setVarietyQty(order.getInvoiceNum());
                order.setSinglePayPrice(requisitionOrderItem.getSinglePayPrice());
                order.setServiceId(requisitionOrderItem.getServiceId());
                order.setServiceName(requisitionOrderItem.getServiceName());
                order.setDiscAmount(requisitionOrderItem.getDiscAmount());
                order.setKingDeeSeq(requisitionOrderItem.getKingDeeSeq());
                order.setKingDeeEntryId(requisitionOrderItem.getKingDeeEntryId());
                order.setK3ServiceId(enginOrder.getServiceId());
                order.setK3ServiceName(enginOrder.getServiceName());
                order.setCustomerWalletId(enginOrderItem.getCustomerWalletId());
                order.setCustomerWalletName(enginOrderItem.getCustomerWalletName());
                order.setCustomerWalletNumber(enginOrderItem.getCustomerWalletNumber());
                order.setCustomerWalletId2(enginOrderItem.getCustomerWalletId2());
                order.setCustomerWalletName2(enginOrderItem.getCustomerWalletName2());

            }

            if ( StringUtils.isEmpty(order.getKingDeeEntryId())) {
                mapBool.put("1","1");
                invoiceRequest.setSyncType(2);
            }else if  (!StringUtils.isEmpty(order.getKingDeeEntryId())){
                mapBool.put("2","2");
            }
            if (mapBool.size() > 1){
                throw new RemoteServiceException("新单旧单发货逻辑更改，需分别发货");
            }
            invoiceApplicationOrders.add(order);
        }

        if (map.get("1") != null) {
            if (map.get("2") != null) {
                throw new RemoteServiceException("类型不一致，调拨单需单独申请发货");
            }
        }

        invoiceApplicationService.updateById(invoiceRequest);
        invoiceApplicationOrderService.saveBatch(invoiceApplicationOrders);

        List<DepositManageRecordBean> depositManageRecordListOne = new ArrayList<>();
            for (InvoiceApplicationOrder order : invoiceRequest.getOrders()) {
                if (order.getInvoiceNum() == null || order.getInvoiceNum().equals(0))
                    continue;

                if (order.getOrderType().equals("PERMU_HOME")) {
                    DisplaceOrder displaceOrder = displaceOrderService.getById(order.getMainOrderId());
                    DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(order.getOrderId());
                    DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                    depositManageRecordBean.setConsumNo(order.getInvoiceId());
                    depositManageRecordBean.handleEnginOrderItem(displaceOrder, displaceOrderItem, order.getInvoiceNum(), displaceOrderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(order.getInvoiceNum()))));
                    depositManageRecordListOne.add(depositManageRecordBean);
                }

                if (order.getOrderType().equals("REQUISITION_HOME")) {
                    RequisitionOrder requisitionOrder = requisitionOrderService.getById(order.getMainOrderId());
                    RequisitionOrderItem requisitionOrderItemServiceById = requisitionOrderItemService.getById(order.getOrderId());
                    EnginOrder enginOrder = enginOrderService.getById(requisitionOrderItemServiceById.getMainOrderId());
                    EnginOrderItem orderItem = enginOrderItemService.getById(requisitionOrderItemServiceById.getOrderId());
                    DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                    depositManageRecordBean.setConsumNo(order.getInvoiceId());
                    depositManageRecordBean.handleEnginOrderItem(enginOrder, orderItem, order.getInvoiceNum(), orderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(order.getInvoiceNum()))));
                    depositManageRecordListOne.add(depositManageRecordBean);
                }
                //工程扣除押金
                if (order.getOrderType().equals("HOME")) {
                    EnginOrder enginOrder = enginOrderService.getById(order.getMainOrderId());
                    EnginOrderItem orderItem = enginOrderItemService.getById(order.getOrderId());
                    DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                    depositManageRecordBean.setConsumNo(order.getInvoiceId());
                    depositManageRecordBean.handleEnginOrderItem(enginOrder, orderItem, order.getInvoiceNum(), orderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(order.getInvoiceNum()))));
                    depositManageRecordListOne.add(depositManageRecordBean);
                }
            }
            if (!CollectionUtils.isEmpty(depositManageRecordListOne))
            depositManageLogic.addDepositAmount(invoiceApplicationServiceById.getRefEnginRecordNo(), depositManageRecordListOne);
        invoiceMapper.updateStatus(invoiceRequest.getId());
        invoiceMapper.updateInvoice(invoiceRequest.getId());
        invoiceMapper.updateWithold(invoiceRequest.getId(),Constant.ENGIN_UPDATE);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteProject(String id) throws InterruptedException {
        InvoiceApplication byId = invoiceApplicationService.getById(id);
        if (!byId.getExamineStatus().equals("SAVE")) {
            throw new RemoteServiceException("该申请单不为保存状态，不可删除");
        }

        List<DepositManageRecordBean> depositManageRecordList = new ArrayList<>();


        List<String> orderId = new ArrayList<>();
        for (InvoiceApplicationOrder invoiceApplicationOrder : invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, id).list()) {
            //减少经销商暂扣库存
            stockCommonLogic.reduceStockCustomerSuspended(invoiceApplicationOrder.getMaterialId(), byId.getCustomerId(), invoiceApplicationOrder.getRefundableQty());
            if (invoiceApplicationOrder.getOrderType().equals("PERMU_HOME")) {
                DisplaceOrder displaceOrder = displaceOrderService.getById(invoiceApplicationOrder.getMainOrderId());
                DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(invoiceApplicationOrder.getOrderId());
                DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                depositManageRecordBean.setConsumNo(invoiceApplicationOrder.getInvoiceId());
                depositManageRecordBean.handleEnginOrderItem(displaceOrder, displaceOrderItem, invoiceApplicationOrder.getRefundableQty(), displaceOrderItem.getSingleDepositAmount()
                        .multiply(new BigDecimal(Convert.toStr(invoiceApplicationOrder.getRefundableQty()))));
                depositManageRecordList.add(depositManageRecordBean);
            }

            if (invoiceApplicationOrder.getOrderType().equals("REQUISITION_HOME")) {
                RequisitionOrder requisitionOrder = requisitionOrderService.getById(invoiceApplicationOrder.getMainOrderId());
                RequisitionOrderItem requisitionOrderItemServiceById = requisitionOrderItemService.getById(invoiceApplicationOrder.getOrderId());
                EnginOrder enginOrder = enginOrderService.getById(requisitionOrderItemServiceById.getMainOrderId());
                EnginOrderItem orderItem = enginOrderItemService.getById(requisitionOrderItemServiceById.getOrderId());
                DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                depositManageRecordBean.setConsumNo(invoiceApplicationOrder.getInvoiceId());
                depositManageRecordBean.handleEnginOrderItem(enginOrder, orderItem, invoiceApplicationOrder.getRefundableQty(), orderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(invoiceApplicationOrder.getRefundableQty()))));
                depositManageRecordList.add(depositManageRecordBean);
            }

            //工程扣除押金
            if (invoiceApplicationOrder.getOrderType().equals("HOME")) {
                EnginOrder enginOrder = enginOrderService.getById(invoiceApplicationOrder.getMainOrderId());
                EnginOrderItem orderItem = enginOrderItemService.getById(invoiceApplicationOrder.getOrderId());
                DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                depositManageRecordBean.setConsumNo(invoiceApplicationOrder.getInvoiceId());
                depositManageRecordBean.handleEnginOrderItem(enginOrder, orderItem, invoiceApplicationOrder.getRefundableQty(), orderItem.getSingleDepositAmount()
                        .multiply(new BigDecimal(Convert.toStr(invoiceApplicationOrder.getRefundableQty()))));
                depositManageRecordList.add(depositManageRecordBean);

            }
            orderId.add(invoiceApplicationOrder.getOrderId());
        }
        if (!CollectionUtils.isEmpty(depositManageRecordList))
        depositManageLogic.reduceDepositAmount(byId.getRefEnginRecordNo(), depositManageRecordList);

        invoiceApplicationService.removeById(id);
        invoiceApplicationOrderService.lambdaUpdate().eq(InvoiceApplicationOrder::getInvoiceId, id).remove();
        invoiceMapper.updateWithold(id,Constant.ENGIN_UPDATE);

        for (String s : orderId) {
            invoiceMapper.updateWitholdOrder(s,Constant.ENGIN_UPDATE);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void submitProject(String id, String examineStatus ) throws Exception {
        InvoiceApplication byId = invoiceApplicationService.getById(id);

        if (!byId.getExamineStatus().equals(ExamineStatusEnum.SAVE.toString()) && !byId.getExamineStatus().equals(ExamineStatusEnum.WAIT.toString())) {
            throw new RemoteServiceException("该申请单不为保存或提审状态");
        }

        List<InvoiceApplicationOrder> list = invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, byId.getId()).list();
        List<InvoiceApplicationOrderRequest> invoiceApplicationOrderRequests = BeanUtil.copyToList(list, InvoiceApplicationOrderRequest.class);
        //1查看发货单即时库存是否充足
        if (examineStatus.equals("WAIT")) {
            checkUpdate(invoiceApplicationOrderRequests, byId.getCorrespondId(), examineStatus);
        }
        InvoiceApplication invoiceApplication = new InvoiceApplication();
        invoiceApplication.setId(id);
        invoiceApplication.setExamineStatus(examineStatus);
        invoiceApplicationService.updateById(invoiceApplication);
        invoiceMapper.updateStatus(invoiceApplication.getId());
        invoiceMapper.updateWithold(invoiceApplication.getId(),Constant.ENGIN_UPDATE);

    }

    @Transactional(rollbackFor = Exception.class)
    public void approvalInvoiceProject(InvoiceRequestJson invoiceRequestJson ) throws Exception {
        //保存申请发货单
        AdminUserCom adminUser = commonLogic.getAdminUser();



        InvoiceApplication invoiceApplication = invoiceApplicationService.getById(invoiceRequestJson.getId());
        if (!invoiceApplication.getExamineStatus().equals(ExamineStatusEnum.WAIT.toString())) {
            throw new RemoteServiceException("非审核单，无法审核");
        }

        //修改订单
        invoiceRequestJson.setApprovalName(adminUser.getNickName());
        invoiceRequestJson.setApprovalTime(new Date());
        invoiceApplicationService.updateById(invoiceRequestJson);

        for (InvoiceApplicationOrderRequest order : invoiceRequestJson.getOrders()) {
            InvoiceApplicationOrder invoiceApplicationOrder = invoiceApplicationOrderService.getById(order.getId());
            order.setApprovalNumber(invoiceApplicationOrder.getInvoiceNum());
            order.setRefundableQty(order.getApprovalNumber());
            order.setVarietyQty(order.getApprovalNumber());

            order.setPayAmount(invoiceApplicationOrder.getSinglePayPrice()
                    .multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setTotalAmount(invoiceApplicationOrder.getPrice().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setPayRebateAmount(invoiceApplicationOrder.getSingleRebateAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setTotalDiscAmount(invoiceApplicationOrder.getDiscAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setAfterTaxPrice(invoiceApplicationOrder.getPrice().subtract(invoiceApplicationOrder.getPrice().multiply(invoiceApplicationOrder.getTax())));
            order.setNoTotalAmount(order.getPayAmount().subtract(order.getPayAmount().multiply(invoiceApplicationOrder.getTax())));

            Integer integer = stockCommonLogic.stockKingDeeNumber(invoiceApplication.getCorrespondId(), order.getMaterialId());

            if (order.getApprovalNumber() > integer)
                throw new RemoteServiceException(order.getMaterialName()+"/"+order.getSpecification()  + "库存不足");

            invoiceApplicationOrderService.updateById(order);
        }

        if (invoiceRequestJson.getExamineStatus().equals(ExamineStatusEnum.SAVE.toString()))
            return;

        //查看发货单即时库存是否充足
        //checkAdd(invoiceRequestJson.getOrders(), invoiceApplication.getCorrespondId(), ExamineStatusEnum.OK.toString(),invoiceApplication.getCustomerId());

        //生成发货单
        ShipDocument shipDocument = BeanUtil.toBean(invoiceApplication, ShipDocument.class);

        shipDocument.setExamineStatus(ExamineStatusEnum.OK.toString());
        shipDocument.insert();


        //生成销售出库单
        SalesOrder salesOrder = BeanUtil.toBean(invoiceApplication, SalesOrder.class);


        String yyyyMM = DateUtil.format(new Date(), "yyyyMM");
        String orderWater = yyyyMM.substring(yyyyMM.length() - 4);
        if (redisUtil.get("sales" + orderWater) == null) {
            redisUtil.set("sales" + orderWater, "0000", 60 * 60 * 24 * 31);
        }
        Object water = redisUtil.get("sales" + orderWater);
        String s = pickLogic.generateNum(4, Convert.toStr(water));

        if (salesOrderService.lambdaQuery().eq(SalesOrder::getId, orderWater + s).count() > 0) {
            throw new RemoteServiceException("请勿频繁新增，稍等一会");
        }
        redisUtil.set("sales" + orderWater, s, 60 * 60 * 24 * 31);


        salesOrder.setId(orderWater + s);

        invoiceRequestJson.setSalesId(orderWater + s);
        invoiceRequestJson.setSalesOrderId(orderWater + s);
        invoiceRequestJson.updateById();

        salesOrder.setOrderNo(invoiceRequestJson.getId());
        salesOrder.setOrderTime(new Date());
        salesOrder.setExamineStatus(ExamineStatusEnum.WAIT.toString());
        salesOrder.insert();
        List<InvoiceApplicationOrder> list = invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, invoiceApplication.getId()).list();
        List<SalesOrderItem> salesOrders = new ArrayList<>();
        for (InvoiceApplicationOrder invoiceApplicationOrder : list) {
            SalesOrderItem salesOrderItem = BeanUtil.toBean(invoiceApplicationOrder, SalesOrderItem.class);
            salesOrderItem.setId(null);
            salesOrderItem.setSalesOrderNo(salesOrder.getId());
            salesOrderItem.setInvoiceItemId(invoiceApplicationOrder.getId());
            salesOrders.add(salesOrderItem);
        }
        salesOrderItemService.saveBatch(salesOrders);


        List<DepositManageRecordBean> depositManageRecordList = new ArrayList<>();
        for (InvoiceApplicationOrderRequest order : invoiceRequestJson.getOrders()) {
            //增加经销商暂扣库存
            if (order.getRefundableQty() - order.getInvoiceNum() >= 0) {
                stockCommonLogic.inventoryStockCustomerSuspended(order.getMaterialId(), invoiceApplication.getCustomerId(), order.getRefundableQty());
            } else {
                stockCommonLogic.reduceStockCustomerSuspended(order.getMaterialId(), invoiceApplication.getCustomerId(), order.getInvoiceNum() - order.getRefundableQty());
            }

            //变更可退货数量
            if (order.getOrderType().equals("TRADE") || order.getOrderType().equals("HOME"))
                changeEnginRefundableQty(order.getOrderId(), order.getApprovalNumber());

            if (order.getOrderType().equals("PERMU_TRADE") || order.getOrderType().equals("PERMU_HOME"))
                changeDiplaceRefundableQty(order.getOrderId(), order.getApprovalNumber());

            if (order.getOrderType().equals("REQUISITION_TRADE") || order.getOrderType().equals("REQUISITION_HOME"))
                changeRqquisitionEnginRefundableQty(order.getRequisitionItemId(), order.getApprovalNumber());

            //记录台账记录
            String customerWalletId = null;
            if (order.getOrderType().equals("HOME") || order.getOrderType().equals("TRADE")) {
                EnginOrderItem engin = enginOrderItemService.getById(order.getOrderId());
                if (engin.getRefundableQty().equals("0") && engin.getIsDirectTransfer() == false) {
                    order.setPayAmount(
                            engin.getPayAmount().subtract(new BigDecimal((engin.getHasSendQty() - engin.getDirectTransferQty())).multiply(engin.getSinglePayPrice())));
                }
                customerWalletId = engin.getCustomerWalletId();
            }
            if (order.getOrderType().equals("PERMU_TRADE") || order.getOrderType().equals("PERMU_HOME")) {
                DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(order.getOrderId());
                if (displaceOrderItem.getRefundableQty().equals("0")) {
                    order.setPayAmount(
                            displaceOrderItem.getPayAmount().subtract(new BigDecimal((displaceOrderItem.getHasSendQty())).multiply(displaceOrderItem.getSinglePayPrice())));
                }
                customerWalletId = displaceOrderItem.getCustomerWalletId();
            }

            if (order.getOrderType().equals("REQUISITION_TRADE") || order.getOrderType().equals("REQUISITION_HOME")) {
                RequisitionOrderItem requisitionOrderItem = requisitionOrderItemService.getById(order.getRequisitionItemId());
                if (requisitionOrderItem.getRefundableQty().equals("0")) {
                    order.setPayAmount(
                            requisitionOrderItem.getPayAmount().subtract(new BigDecimal((requisitionOrderItem.getHasSendQty())).multiply(requisitionOrderItem.getSinglePayPrice())));
                }
                customerWalletId = requisitionOrderItem.getCustomerWalletId();
            }
            CustomerWallet customerWallet = customerWalletService.getById(customerWalletId);
            walletLogic.saveCustomerWalletRecord(customerWallet, order.getPayAmount(), "工程申请发货单流水", "申请发货单", new Date(), invoiceRequestJson.getId(), 3, "OUT");


            //工程扣除押金

   /*         EnginOrderItem orderItem = enginOrderItemService.getById(order.getOrderId());
            EnginOrder enginOrder = enginOrderService.getById(orderItem.getParentId());
            if (order.getOrderType().equals("HOME") || order.getOrderType().equals("PERMU_HOME") || order.getOrderType().equals("REQUISITION_HOME")) {
                DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                enginOrder.setEnginOrderNo(invoiceApplication.getId());
                enginOrder.setOrderDate(invoiceApplication.getOrderTime());
                depositManageRecordBean.handleEnginOrderItem(enginOrder, orderItem, order.getRefundableQty(), orderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));
                depositManageRecordList.add(depositManageRecordBean);
            }*/
        }
        //格匠同步采购入库单
        if (invoiceApplication.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_FOSHAN.getCode()) ||
                invoiceApplication.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU.getCode())){
            InvoiceApplication invoiceApplication1 = new InvoiceApplication();
            invoiceApplication1.setId(invoiceApplication.getId());
            invoiceApplication1.setGejiangSync(0);
            invoiceApplication1.updateById();
            InvoiceApplicationSyncGejiang invoiceApplicationSyncGejiang = new InvoiceApplicationSyncGejiang();
            invoiceApplicationSyncGejiang.setInvoiceId(invoiceApplication.getId());
            invoiceApplicationSyncGejiang.setStatus(0);
            invoiceApplicationSyncGejiang.insert();
        }

        /*depositManageLogic.addDepositAmount(invoiceApplication.getRefEnginRecordNo(), depositManageRecordList);*/
        invoiceMapper.updateStatus(invoiceApplication.getId());
        invoiceMapper.updateInvoice(invoiceApplication.getId());
        invoiceMapper.updateTaiZhang(invoiceApplication.getId());
        invoiceMapper.updateWithold(invoiceApplication.getId(),Constant.ENGIN_UPDATE);
    }


    @Transactional(rollbackFor = Exception.class)
    public void approvalInvoiceProject(InvoiceApplication invoiceApplicationRequest, HttpServletRequest request, String examineStatus, String approvalRemark) throws Exception {
        //保存申请发货单
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        InvoiceApplication invoiceApplication = invoiceApplicationService.getById(invoiceApplicationRequest.getId());

        if (invoiceApplication.getExamineStatus().equals("OK")){
            throw new RemoteServiceException("订单已审核");
        }

        if (examineStatus.equals(ExamineStatusEnum.SAVE.toString()))
            return;

        //修改订单
        invoiceApplicationRequest.setApprovalName(adminUser.getNickName());
        invoiceApplicationRequest.setApprovalRemark(approvalRemark);
        invoiceApplicationRequest.setApprovalTime(new Date());
        invoiceApplicationRequest.setExamineStatus(examineStatus);
        invoiceApplicationService.updateById(invoiceApplicationRequest);
        List<InvoiceApplicationOrder> list = invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, invoiceApplication.getId()).list();
        for (InvoiceApplicationOrder order : list) {
            InvoiceApplicationOrder invoiceApplicationOrder = invoiceApplicationOrderService.getById(order.getId());
            order.setRefundableQty(order.getInvoiceNum());
            order.setApprovalNumber(order.getInvoiceNum());
            order.setVarietyQty(order.getApprovalNumber());

            order.setPayAmount(invoiceApplicationOrder.getSinglePayPrice()
                    .multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setTotalAmount(invoiceApplicationOrder.getPrice().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setPayRebateAmount(invoiceApplicationOrder.getSingleRebateAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setTotalDiscAmount(invoiceApplicationOrder.getDiscAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));

            order.setAfterTaxPrice(invoiceApplicationOrder.getPrice().subtract(invoiceApplicationOrder.getPrice().multiply(invoiceApplicationOrder.getTax())));
            order.setNoTotalAmount(order.getPayAmount().subtract(order.getPayAmount().multiply(invoiceApplicationOrder.getTax())));
            invoiceApplicationOrderService.updateById(order);
        }



        //查看发货单即时库存是否充足
        List<InvoiceApplicationOrderRequest> invoiceApplicationOrderRequests = BeanUtil.copyToList(list, InvoiceApplicationOrderRequest.class);
        checkAdd(invoiceApplicationOrderRequests, invoiceApplication.getCorrespondId(), ExamineStatusEnum.OK.toString(),invoiceApplication.getCustomerId());

        //生成发货单
        ShipDocument shipDocument = BeanUtil.toBean(invoiceApplication, ShipDocument.class);

        shipDocument.setExamineStatus(ExamineStatusEnum.OK.toString());
        shipDocument.insert();


        //生成销售出库单
        SalesOrder salesOrder = BeanUtil.toBean(invoiceApplication, SalesOrder.class);


        String yyyyMM = DateUtil.format(new Date(), "yyyyMM");
        String orderWater = yyyyMM.substring(yyyyMM.length() - 4);
        if (redisUtil.get("sales" + orderWater) == null) {
            redisUtil.set("sales" + orderWater, "0000", 60 * 60 * 24 * 31);
        }
        Object water = redisUtil.get("sales" + orderWater);
        String s = pickLogic.generateNum(4, Convert.toStr(water));

        if (salesOrderService.lambdaQuery().eq(SalesOrder::getId, orderWater + s).count() > 0) {
            throw new RemoteServiceException("请勿频繁新增，稍等一会");
        }
        redisUtil.set("sales" + orderWater, s, 60 * 60 * 24 * 31);


        salesOrder.setId(orderWater + s);
        invoiceApplicationRequest.setSalesId(orderWater + s);
        invoiceApplicationRequest.setSalesOrderId(orderWater + s);
        invoiceApplicationRequest.updateById();

        salesOrder.setOrderNo(invoiceApplicationRequest.getId());
        salesOrder.setOrderTime(new Date());
        salesOrder.setExamineStatus(ExamineStatusEnum.WAIT.toString());
        salesOrder.insert();
        List<SalesOrderItem> salesOrders = new ArrayList<>();
        for (InvoiceApplicationOrder invoiceApplicationOrder : list) {
            SalesOrderItem salesOrderItem = BeanUtil.toBean(invoiceApplicationOrder, SalesOrderItem.class);
            salesOrderItem.setId(null);
            salesOrderItem.setSalesOrderNo(salesOrder.getId());
            salesOrderItem.setInvoiceItemId(invoiceApplicationOrder.getId());
            salesOrders.add(salesOrderItem);
        }
        salesOrderItemService.saveBatch(salesOrders);


        List<DepositManageRecordBean> depositManageRecordList = new ArrayList<>();
        for (InvoiceApplicationOrder order : list) {
            //增加经销商暂扣库存
            if (order.getRefundableQty() - order.getInvoiceNum() >= 0) {
                stockCommonLogic.inventoryStockCustomerSuspended(order.getMaterialId(), invoiceApplication.getCustomerId(), order.getRefundableQty());
            } else {
                stockCommonLogic.reduceStockCustomerSuspended(order.getMaterialId(), invoiceApplication.getCustomerId(), order.getInvoiceNum() - order.getRefundableQty());
            }

            //变更可退货数量
            if (order.getOrderType().equals("TRADE") || order.getOrderType().equals("HOME"))
                changeEnginRefundableQty(order.getOrderId(), order.getApprovalNumber());

            if (order.getOrderType().equals("PERMU_TRADE") || order.getOrderType().equals("PERMU_HOME"))
                changeDiplaceRefundableQty(order.getOrderId(), order.getApprovalNumber());

            if (order.getOrderType().equals("REQUISITION_TRADE") || order.getOrderType().equals("REQUISITION_HOME"))
                changeRqquisitionRefundableQty(order.getRequisitionItemId(), order.getApprovalNumber());

            //记录台账记录
            String customerWalletId = null;
            if (order.getOrderType().equals("HOME") || order.getOrderType().equals("TRADE")) {
                EnginOrderItem engin = enginOrderItemService.getById(order.getOrderId());
                if (engin.getRefundableQty().equals("0") && engin.getIsDirectTransfer() == false) {
                    order.setPayAmount(
                            engin.getPayAmount().subtract(new BigDecimal((engin.getHasSendQty() - engin.getDirectTransferQty())).multiply(engin.getSinglePayPrice())));
                }
                customerWalletId = engin.getCustomerWalletId();
            }
            if (order.getOrderType().equals("PERMU_TRADE") || order.getOrderType().equals("PERMU_HOME")) {
                DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(order.getOrderId());
                if (displaceOrderItem.getRefundableQty().equals("0")) {
                    order.setPayAmount(
                            displaceOrderItem.getPayAmount().subtract(new BigDecimal((displaceOrderItem.getHasSendQty())).multiply(displaceOrderItem.getSinglePayPrice())));
                }
                customerWalletId = displaceOrderItem.getCustomerWalletId();
            }

            if (order.getOrderType().equals("REQUISITION_TRADE") || order.getOrderType().equals("REQUISITION_HOME")) {
                RequisitionOrderItem requisitionOrderItem = requisitionOrderItemService.getById(order.getRequisitionItemId());
                if (requisitionOrderItem.getRefundableQty().equals("0")) {
                    order.setPayAmount(
                            requisitionOrderItem.getPayAmount().subtract(new BigDecimal((requisitionOrderItem.getHasSendQty())).multiply(requisitionOrderItem.getSinglePayPrice())));
                }
                customerWalletId = requisitionOrderItem.getCustomerWalletId();
            }
            CustomerWallet customerWallet = customerWalletService.getById(customerWalletId);
            walletLogic.saveCustomerWalletRecord(customerWallet, order.getPayAmount(), "工程申请发货单流水", "申请发货单", new Date(), invoiceApplication.getId(), 3, "OUT");

            //工程扣除押金

   /*         EnginOrderItem orderItem = enginOrderItemService.getById(order.getOrderId());
            EnginOrder enginOrder = enginOrderService.getById(orderItem.getParentId());
            if (order.getOrderType().equals("HOME") || order.getOrderType().equals("PERMU_HOME") || order.getOrderType().equals("REQUISITION_HOME")) {
                DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                enginOrder.setEnginOrderNo(invoiceApplication.getId());
                enginOrder.setOrderDate(invoiceApplication.getOrderTime());
                depositManageRecordBean.handleEnginOrderItem(enginOrder, orderItem, order.getRefundableQty(), orderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));
                depositManageRecordList.add(depositManageRecordBean);
            }*/
        }

        //格匠同步采购入库单
        if (invoiceApplication.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_FOSHAN.getCode()) ||
                invoiceApplication.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU.getCode())){
            InvoiceApplication invoiceApplication1 = new InvoiceApplication();
            invoiceApplication1.setId(invoiceApplication.getId());
            invoiceApplication1.setGejiangSync(0);
            invoiceApplication1.updateById();
            InvoiceApplicationSyncGejiang invoiceApplicationSyncGejiang = new InvoiceApplicationSyncGejiang();
            invoiceApplicationSyncGejiang.setInvoiceId(invoiceApplication.getId());
            invoiceApplicationSyncGejiang.setStatus(0);
            invoiceApplicationSyncGejiang.insert();
        }

        /*depositManageLogic.addDepositAmount(invoiceApplication.getRefEnginRecordNo(), depositManageRecordList);*/
        invoiceMapper.updateStatus(invoiceApplication.getId());
        invoiceMapper.updateInvoice(invoiceApplication.getId());
    }

    /**
     * 扣除置换单数量
     */
    public void changeDiplaceRefundableQty(String orderId, Integer qty) {
        DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(orderId);
        if (displaceOrderItem == null) {
            return;
        }
        if (displaceOrderItem.getRefundableQty().intValue() < qty.intValue()) {
            throw new RemoteServiceException("可退货数量不足!");
        }
        displaceOrderItem.setRefundableQty(displaceOrderItem.getRefundableQty() - qty);
        displaceOrderItem.updateById();
    }

    /**
     * 退回置换单数量
     */
    public void changeSubDiplaceRefundableQty(String orderId, Integer qty) {
        DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(orderId);
        if (displaceOrderItem == null) {
            return;
        }

        displaceOrderItem.setRefundableQty(displaceOrderItem.getRefundableQty() + qty);
        displaceOrderItem.updateById();
    }

    /**
     * 更变可退货数量 -扣除
     *
     * @param orderId 明细id
     * @param qty     数量
     */
    public void changeEnginRefundableQty(String orderId, Integer qty) {
        EnginOrderItem enginOrderItem = enginOrderItemService.getById(orderId);
        if (enginOrderItem == null) {
            return;
        }
        if (enginOrderItem.getRefundableQty().intValue() < qty.intValue()) {
            throw new RemoteServiceException("可申请货数量不足!");
        }

        if (enginOrderItem.getQty() < (enginOrderItem.getRefundableQty()+enginOrderItem.getHasSendQty()))
            throw new RemoteServiceException("可退数量大于了订单数量!");

        enginOrderItem.setRefundableQty(enginOrderItem.getRefundableQty() - qty);
        enginOrderItem.updateById();
    }

    /**
     * 更变可退货数量-新增
     *
     * @param orderId 明细id
     * @param qty     数量
     */
    public void changeAddEnginRefundableQty(String orderId, Integer qty) {
        EnginOrderItem enginOrderItem = enginOrderItemService.getById(orderId);
        if (enginOrderItem == null) {
            return;
        }
        enginOrderItem.setRefundableQty(enginOrderItem.getRefundableQty() + qty);
        enginOrderItem.updateById();
    }




    public IPage<InvoiceOrder> listOrder(String specification,String id, String categoryName, String correspondId, Integer pageNum, Integer pageSize) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        Long num = invoiceMapper.listOrderNum( specification,id, categoryName, customerId, adminUser.getServiceIds(),
                adminUser.getAdminCompanyIds(), adminUser.getK3CategoryIds());

        IPage<InvoiceOrder> invoiceOrderIPage = invoiceMapper.listOrder(new Page<>(pageNum, pageSize,num,false), specification,id, categoryName, customerId, adminUser.getServiceIds(),
                adminUser.getAdminCompanyIds(), adminUser.getK3CategoryIds());
        List<InvoiceOrder> records = invoiceOrderIPage.getRecords();
        records.forEach(item -> {
            if (StringUtils.isNotBlank(correspondId)) {

                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(item.getMaterialId());

                item.setStockCorrespond(0);

                //用户拥有此仓库
                Integer stockCount = adminUserStockService.lambdaQuery().eq(AdminUserStock::getCorrespondId, correspondId)
                        .eq(AdminUserStock::getAdminUserId,adminUser.getAdminUserId()).count();
                if (stockCount > 0){
                    item.setStockCorrespond(stockCommonLogic.stockCorrespondStatus(item.getOrderId(), correspondId, item.getMaterialId(),null));
                }

                //仓库无配置分类 无拥有仓库有分类
                List<StockCorrespondCategory> stockCorrespondCategories = stockCorrespondCategoryService.lambdaQuery().in(StockCorrespondCategory::getCorrespondId, correspondId)
                        .eq(StockCorrespondCategory::getCategoryId,kingDeeMaterial.getCategoryId()).list();
                if (!org.springframework.util.CollectionUtils.isEmpty(stockCorrespondCategories)){
                    item.setStockCorrespond(stockCommonLogic.stockCorrespondStatus(item.getOrderId(), correspondId, item.getMaterialId(),null));

                }

                //查不到这个仓库得强制仓，才进去查是否有强制仓
                if (adminUser.getIsCustomer() && adminUserForceStockService.lambdaQuery()
                        .eq(AdminUserForceStock::getCategoryId, kingDeeMaterial.getCategoryId())
                        .eq(AdminUserForceStock::getCorrespondId,correspondId)
                        .eq(AdminUserForceStock::getAdminUserId,adminUser.getAdminUserId())
                        .count() < 1) {
                    //强制仓返回，有强制仓，判断强制是否有库存，有库存都返回0,没返回正常库存
                    List<AdminUserForceStock> list = adminUserForceStockService.lambdaQuery()
                            .eq(AdminUserForceStock::getCategoryId, kingDeeMaterial.getCategoryId())
                            .eq(AdminUserForceStock::getAdminUserId,adminUser.getAdminUserId())
                            .ne(AdminUserForceStock::getCorrespondId, correspondId)
                            .list();
                    if (!CollectionUtils.isEmpty(list) ) {
                        for (AdminUserForceStock adminUserForceStock : list) {
                            if (stockCommonLogic.stockCorrespondStatus(item.getOrderId(), adminUserForceStock.getCorrespondId(), item.getMaterialId(), null) > 0) {
                                item.setStockCorrespond(0);
                            }
                        }


                    }
                }




                //可用数
                item.setStockAdequate(stockCommonLogic.stockAdequate(null, item.getMaterialId()));
                //对应仓库库存

                Integer integer = invoiceMapper.selectInvoiceOk(item.getOrderId());
                item.setAlreadyInvoiceNum(integer);
                item.setCanApply(item.getRefundableQty());
                Integer integerSales = invoiceMapper.selectSalesNum(item.getOrderId());
                item.setSendQty(integerSales);
            }
        });
        detection();

        invoiceOrderIPage.setRecords(records);
        return invoiceOrderIPage;
    }


    public void detection() {

        List<String> orderIds = invoiceMapper.detection();

        if (CollectionUtils.isEmpty(orderIds))
            return;

        for (String s : orderIds) {
            invoiceMapper.updateWitholdOrder(s,Constant.RETAIL_UPDATE);
        }
    }


    public IPage<InvoiceProjectOrder> listProjectOrder(String enginOrderNo, String refEnginRecordNo, String categoryName, String refProjectName, String specification, String startTime, String endTime, Integer pageNum, Integer pageSize, String correspondId) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        IPage<InvoiceProjectOrder> invoiceProjectOrderIPage = invoiceMapper.listProjectOrder(new Page<>(pageNum, pageSize), enginOrderNo, refEnginRecordNo, categoryName, refProjectName,
                specification, startTime, endTime, customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds());
        List<InvoiceProjectOrder> records = invoiceProjectOrderIPage.getRecords();
        for (InvoiceProjectOrder item : records) {

            if (StringUtils.isNotBlank(correspondId)) {

                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(item.getMaterialId());

                item.setStockCorrespond(0);

                //用户拥有此仓库
                Integer stockCount = adminUserStockService.lambdaQuery().eq(AdminUserStock::getCorrespondId, correspondId)
                        .eq(AdminUserStock::getAdminUserId,adminUser.getAdminUserId()).count();
                if (stockCount > 0){
                    item.setStockCorrespond(stockCommonLogic.stockCorrespondStatus(item.getOrderId(), correspondId, item.getMaterialId(),null));
                }

                //仓库无配置分类 无拥有仓库有分类
                List<StockCorrespondCategory> stockCorrespondCategories = stockCorrespondCategoryService.lambdaQuery().in(StockCorrespondCategory::getCorrespondId, correspondId)
                        .eq(StockCorrespondCategory::getCategoryId,kingDeeMaterial.getCategoryId()).list();
                if (!org.springframework.util.CollectionUtils.isEmpty(stockCorrespondCategories)){
                    item.setStockCorrespond(stockCommonLogic.stockCorrespondStatus(item.getOrderId(), correspondId, item.getMaterialId(),null));

                }

                //可用数
                item.setStockAdequate(stockCommonLogic.stockAdequate(null, item.getMaterialId()));

                //查不到这个仓库得强制仓，才进去查是否有强制仓
                if (adminUser.getIsCustomer() && adminUserForceStockService.lambdaQuery()
                        .eq(AdminUserForceStock::getCategoryId, kingDeeMaterial.getCategoryId())
                        .eq(AdminUserForceStock::getCorrespondId,correspondId)
                        .eq(AdminUserForceStock::getAdminUserId,adminUser.getAdminUserId())
                        .count() < 1) {
                    //强制仓返回，有强制仓，判断强制是否有库存，有库存都返回0,没返回正常库存
                    List<AdminUserForceStock> list = adminUserForceStockService.lambdaQuery()
                            .eq(AdminUserForceStock::getCategoryId, kingDeeMaterial.getCategoryId())
                            .eq(AdminUserForceStock::getAdminUserId,adminUser.getAdminUserId())
                            .ne(AdminUserForceStock::getCorrespondId, correspondId)
                            .list();
                    if (!CollectionUtils.isEmpty(list) ) {
                        for (AdminUserForceStock adminUserForceStock : list) {
                            if (stockCommonLogic.stockCorrespondStatus(item.getOrderId(), adminUserForceStock.getCorrespondId(), item.getMaterialId(), null) > 0) {
                                item.setStockCorrespond(0);
                            }
                        }


                    }
                }


                Integer integer = invoiceMapper.selectInvoiceOk(item.getOrderId());
                item.setAlreadyInvoiceNum(integer);
                Integer invoiceInteger = invoiceMapper.selectSalesNum(item.getOrderId());
                item.setSendQty(invoiceInteger);
            }
        }
        invoiceProjectOrderIPage.setRecords(records);
        return invoiceProjectOrderIPage;
    }

    public EnginOrder listProjectOrderDetail(String enginOrderNo) {
        return enginOrderService.lambdaQuery().eq(EnginOrder::getEnginOrderNo, enginOrderNo).one();
    }

    public ExcelData listExport(List<InvoiceBean> records) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String[] titles;
        if (adminUser.getIsCustomer() && (adminUser.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_FOSHAN.getCode())
                || adminUser.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_FOSHAN.getCode()))){
             titles = new String[]{"订单类型", "状态", "发货申请单", "发货申请日期", "订单日期", "仓库", "订单号",
                    "经销商编码", "经销商名称", "物料编码", "厂产品代码","物料分组", "产品名称", "规格型号", "存货类别", "销售政策名称", "文件编号", "计量单位", "数量", "已退数量", "含税单价",
                    "价税合计", "返利金额", "格力折扣", "订单备注", "发货申请备注",
                    "表体备注", "审批说明", "业务员", "表头业务员", "制单人", "制单日期", "审单人", "审单日期","同步到格匠采购入库单","同步失败原因"};
        }else {
             titles = new String[]{"订单类型", "状态", "发货申请单", "发货申请日期", "订单日期", "仓库", "订单号",
                    "经销商编码", "经销商名称", "物料编码", "厂产品代码","物料分组","产品名称", "规格型号", "存货类别", "销售政策名称", "文件编号", "计量单位", "数量", "已退数量", "含税单价",
                    "价税合计", "返利金额", "格力折扣", "订单备注", "发货申请备注",
                    "表体备注", "审批说明", "业务员", "表头业务员", "制单人", "制单日期", "审单人", "审单日期"};
        }
        List<List<Object>> rows = new ArrayList<>();
        for (InvoiceBean invoiceBean : records) {
            List<Object> row = new ArrayList<>();
            row.add(invoiceBean.getType().equals(1)?"发货申请单":invoiceBean.getType().equals(2)?"退货单":"直调发货单");
//            row.add(ExamineStatusEnum.valueOf(invoiceBean.getExamineStatus()).getMsg());
            row.add(EnumUtil.getNameFieldMap(ExamineStatusEnum.class, "value").get(invoiceBean.getExamineStatus()));
            row.add(invoiceBean.getInvoiceId());
            row.add(DateUtil.formatDate(invoiceBean.getOrderTime()));
            row.add(DateUtil.formatDate(invoiceBean.getTheTime()));
            row.add(invoiceBean.getCorrespondName());
            row.add(invoiceBean.getMainOrderId());
            row.add(invoiceBean.getCustomerNumber());
            row.add(invoiceBean.getCustomerName());
            row.add(invoiceBean.getMaterialCode());
            row.add(invoiceBean.getMaterialOldNumber());
            row.add(invoiceBean.getMaterialGroupName());
            row.add(invoiceBean.getMaterialName());
            row.add(invoiceBean.getSpecification());
            row.add(invoiceBean.getCategoryName());
            row.add(invoiceBean.getPolicyTitle());
            row.add(invoiceBean.getItemFileNo());
            row.add(invoiceBean.getUnit());
            row.add(invoiceBean.getRefundableQty());
            row.add(invoiceBean.getRetiredQty());
            row.add(invoiceBean.getSinglePayPrice());
            row.add(invoiceBean.getPayAmount());
            row.add(invoiceBean.getPayRebateAmount());
            row.add(invoiceBean.getTotalDiscAmount());
            row.add(invoiceBean.getHeaderRemark());
            row.add(invoiceBean.getRemark());
            row.add(invoiceBean.getInvoiceRemark());
            row.add(invoiceBean.getApprovalRemark());
            row.add(invoiceBean.getServiceName());
            row.add(invoiceBean.getK3ServiceName());
            row.add(invoiceBean.getCreateBy());
            row.add(DateUtil.formatDate(invoiceBean.getCreateTime()));
            row.add(invoiceBean.getApprovalName());
            row.add(DateUtil.formatDate(invoiceBean.getApprovalTime()));
            if (StringUtils.isNotEmpty(adminUser.getCustomerNumber()) && (adminUser.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU.getCode())
                    || adminUser.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_FOSHAN.getCode()))){
                row.add(invoiceBean.getGejiangSync() != null?invoiceBean.getGejiangSync().equals(1)?"同步成功":invoiceBean.getGejiangSync().equals(0)?"等待同步":"同步失败":"");
                row.add(invoiceBean.getGejiangSyncRemark());
            }
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public ExcelData listProjectExport(List<InvoiceProjectBean> records) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String[] titles;
        if (adminUser.getIsCustomer() && (adminUser.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_FOSHAN.getCode())
                || adminUser.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_FOSHAN.getCode()))) {
             titles = new String[]{"发货申请单", "发货申请日期", "仓库", "工程登录编码", "工程名称",
                    "使用单位", "经销商编码", "经销商名称", "物料编码", "厂产品代码", "产品名称","物料分组","存货分类", "规格型号", "计量单位", "数量","含税价格","价税合计","返利金额","格力折扣", "表体备注",
                    "制单人", "制单日期", "审核人", "审核日期", "审核状态", "订单备注", "发货申请备注", "表体业务员", "区域", "表头业务员","文件编号","同步到格匠采购入库单","同步失败原因"};
        }else {
             titles = new String[]{"发货申请单", "发货申请日期", "仓库", "工程登录编码", "工程名称",
                    "使用单位", "经销商编码", "经销商名称", "物料编码", "厂产品代码", "产品名称","物料分组","存货分类", "规格型号", "计量单位", "数量","含税价格","价税合计","返利金额","格力折扣","表体备注",
                    "制单人", "制单日期", "审核人", "审核日期", "审核状态", "订单备注", "发货申请备注", "表体业务员", "区域", "表头业务员","文件编号"};
        }
        List<List<Object>> rows = new ArrayList<>();
        for (InvoiceProjectBean invoiceProjectBean : records) {
            List<Object> row = new ArrayList<>();
            row.add(invoiceProjectBean.getId());
            row.add(DateUtil.formatDate(invoiceProjectBean.getCreateTime()));
            row.add(invoiceProjectBean.getCorrespondName());
            row.add(invoiceProjectBean.getRefEnginRecordNo());
            row.add(invoiceProjectBean.getRefProjectName());
            row.add(invoiceProjectBean.getRefUseUnit());
            row.add(invoiceProjectBean.getCustomerNumber());
            row.add(invoiceProjectBean.getCustomerName());
            row.add(invoiceProjectBean.getMaterialCode());
            row.add(invoiceProjectBean.getMaterialOldNumber());
            row.add(invoiceProjectBean.getMaterialName());
            row.add(invoiceProjectBean.getMaterialGroupName());
            row.add(invoiceProjectBean.getCategoryName());
            row.add(invoiceProjectBean.getSpecification());
            row.add(invoiceProjectBean.getUnit());
            row.add(invoiceProjectBean.getRefundableQty());
            row.add(invoiceProjectBean.getSinglePayPrice());
            row.add(invoiceProjectBean.getPayAmount());
            row.add(invoiceProjectBean.getPayRebateAmount());
            row.add(invoiceProjectBean.getTotalDiscAmount());
            row.add(invoiceProjectBean.getInvoiceRemark());
            row.add(invoiceProjectBean.getCreateBy());
            row.add(DateUtil.formatDate(invoiceProjectBean.getCreateTime()));
            row.add(invoiceProjectBean.getApprovalName());
            row.add(DateUtil.formatDate(invoiceProjectBean.getApprovalTime()));
//            row.add(ExamineStatusEnum.valueOf(invoiceProjectBean.getExamineStatus()).getMsg());
            row.add(EnumUtil.getNameFieldMap(ExamineStatusEnum.class, "value").get(invoiceProjectBean.getExamineStatus()));
            row.add(invoiceProjectBean.getHeaderRemark());
            row.add(invoiceProjectBean.getRemark());
            row.add(invoiceProjectBean.getK3ServiceName());
            row.add(invoiceProjectBean.getRefRegionWork());
            row.add(invoiceProjectBean.getServiceName());
            row.add(invoiceProjectBean.getItemFileNo());
            if (StringUtils.isNotEmpty(adminUser.getCustomerNumber()) && (adminUser.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU.getCode())
                    || adminUser.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_FOSHAN.getCode()))){
                row.add(invoiceProjectBean.getGejiangSync() != null?invoiceProjectBean.getGejiangSync().equals(1)?"同步成功":invoiceProjectBean.getGejiangSync().equals(0)?"等待同步":"同步失败":"");

                row.add(invoiceProjectBean.getGejiangSyncRemark());
            }
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public List<InvoiceRetreatOrder> listInvoiceRetreat(String mainOrderId) {
        List<InvoiceRetreatOrder> invoiceRetreatOrders = invoiceMapper.listInvoiceRetreat(mainOrderId);
        return invoiceRetreatOrders;
    }

    @Transactional(rollbackFor = Exception.class)
    public String giveUp(String id) {
        //2，添加发货申请单
        InvoiceApplication invoiceApplication = invoiceApplicationService.getById(id);
        if (!invoiceApplication.getExamineStatus().equals(ExamineStatusEnum.OK.toString()))
            throw new RemoteServiceException("当前单非审核状态");
        SalesOrder salesOrder = salesOrderService.lambdaQuery().eq(SalesOrder::getOrderNo, invoiceApplication.getId()).one();
        if (salesOrder.getExamineStatus().equals(ExamineStatusEnum.OK.toString()))
            throw new RemoteServiceException("销售出库单已审核通过无法弃审");
        if (invoiceApplicationService.lambdaQuery().eq(InvoiceApplication::getSalesId, invoiceApplication.getSalesId()).eq(InvoiceApplication::getType, 2).count() > 0)
            throw new RemoteServiceException("该申请发货单有退货操作不可弃审");


        //1,删除销售出库单和发货单
        salesOrderItemService.lambdaUpdate().eq(SalesOrderItem::getInvoiceId, invoiceApplication.getId()).remove();
        salesOrderService.lambdaUpdate().eq(SalesOrder::getOrderNo, invoiceApplication.getId()).remove();
        shipDocumentService.lambdaUpdate().eq(ShipDocument::getId, invoiceApplication.getId()).remove();
        //2返还数量到销售订单

        //生成订单流水号
        String substring = invoiceApplication.getId().substring(0, 2);
        String yyyyMM = DateUtil.format(new Date(), "yyyyMM");
        String orderWater = yyyyMM.substring(yyyyMM.length() - 4);
        if (redisUtil.get(Constant.RedisPrefix.INVOICE_APPLICATION + orderWater) == null) {
            redisUtil.set(Constant.RedisPrefix.INVOICE_APPLICATION + orderWater, "0000", 2726560);
        }
        Object water = redisUtil.get(Constant.RedisPrefix.INVOICE_APPLICATION + orderWater);
        String s = pickLogic.generateNum(4, Convert.toStr(water));

        if (invoiceApplicationService.lambdaQuery().eq(InvoiceApplication::getId, substring + orderWater + s).count() > 0) {
            throw new RemoteServiceException("请勿频繁新增，稍等一会");
        }
        redisUtil.set(Constant.RedisPrefix.INVOICE_APPLICATION + orderWater, s, 2726560);
        invoiceApplicationService.removeById(invoiceApplication.getId());



        List<InvoiceApplicationOrder> list = invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, invoiceApplication.getId()).list();
        invoiceApplication.setId(substring + orderWater + s);
        for (InvoiceApplicationOrder order : list) {
            if (pickManagerShipService.lambdaQuery().eq(PickManagerShip::getInvoiceOrderId, order.getId()).count() > 0)
                throw new RemoteServiceException("该申请发货单有提货预约操作不可弃审");

            if (order.getOrderType().equals("RETAIL") || order.getOrderType().equals("RETAIL_POLICY"))
                retailOrderLogic.changeSubRefundableQty(order.getOrderId(), order.getApprovalNumber() + order.getRetiredQty());

            if (order.getOrderType().equals("PERMU_RETAIL") || order.getOrderType().equals("PERMU_RETAIL_POLICY"))
                changeSubDiplaceRefundableQty(order.getOrderId(), order.getApprovalNumber() + order.getRetiredQty());

            if (order.getOrderType().equals("REQUISITION_RETAIL") || order.getOrderType().equals("REQUISITION_RETAIL_POLICY"))
                changeSubRequisitonRefundableQty(order.getRequisitionItemId(), order.getApprovalNumber() + order.getRetiredQty());

            stockCommonLogic.reduceStockCustomerSuspended(order.getMaterialId(), invoiceApplication.getCustomerId(), order.getRefundableQty());


            //记录台账记录
            String customerWalletId = null;
            if (order.getOrderType().equals("RETAIL") || order.getOrderType().equals("RETAIL_POLICY")) {
                RetailOrderItem retailOrderItem = retailOrderItemService.getById(order.getOrderId());
                if (retailOrderItem.getRefundableQty().equals("0") && retailOrderItem.getIsDirectTransfer() == false) {
                    order.setPayAmount(
                            retailOrderItem.getPayAmount().subtract(new BigDecimal((retailOrderItem.getHasSendQty() - retailOrderItem.getDirectTransferQty())).multiply(retailOrderItem.getSinglePayPrice())));
                }
                customerWalletId = retailOrderItem.getCustomerWalletId();
            }
            if (order.getOrderType().equals("PERMU_RETAIL") || order.getOrderType().equals("PERMU_RETAIL_POLICY")) {
                DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(order.getOrderId());
                if (displaceOrderItem.getRefundableQty().equals("0")) {
                    order.setPayAmount(
                            displaceOrderItem.getPayAmount().subtract(new BigDecimal((displaceOrderItem.getHasSendQty())).multiply(displaceOrderItem.getSinglePayPrice())));
                }
                customerWalletId = displaceOrderItem.getCustomerWalletId();
            }

            if (order.getOrderType().equals("REQUISITION_RETAIL") || order.getOrderType().equals("REQUISITION_RETAIL_POLICY")) {
                RequisitionOrderItem requisitionOrderItem = requisitionOrderItemService.getById(order.getRequisitionItemId());
                if (requisitionOrderItem.getRefundableQty().equals("0")) {
                    order.setPayAmount(
                            requisitionOrderItem.getPayAmount().subtract(new BigDecimal((requisitionOrderItem.getHasSendQty())).multiply(requisitionOrderItem.getSinglePayPrice())));
                }
                customerWalletId = requisitionOrderItem.getCustomerWalletId();
            }
            CustomerWallet customerWallet = customerWalletService.getById(customerWalletId);
            walletLogic.saveCustomerWalletRecord(customerWallet, order.getPayAmount(), "申请发货单流水弃审", "申请发货单", new Date(), invoiceApplication.getId(), 3, "IN");

            order.setInvoiceId(invoiceApplication.getId());
            order.updateById();

        }

        if (invoiceApplication.getGejiangSync() != null && invoiceApplication.getGejiangSync().equals(1)){
            geJiangInStockLogic.unAuditByBillNo(id);
        }

        //3订单改为提审状态
        invoiceApplication.setExamineStatus(ExamineStatusEnum.WAIT.toString());
        invoiceApplication.setCounterclaim(true);
        invoiceApplication.updateById();
        invoiceApplicationService.save(invoiceApplication);
        invoiceMapper.updateStatus(invoiceApplication.getId());
        invoiceMapper.updateWithold(invoiceApplication.getId(),Constant.RETAIL_UPDATE);
        return invoiceApplication.getId();
    }

    public void changeSubRequisitonRefundableQty(String orderId, Integer approvalNumber) {
        RequisitionOrderItem requisitionOrderItem = requisitionOrderItemService.getById(orderId);
        RetailOrderItem retailOrderItem = retailOrderItemService.getById(requisitionOrderItem.getOrderId());
        if (requisitionOrderItem == null) {
            return;
        }

        requisitionOrderItem.setRefundableQty(requisitionOrderItem.getRefundableQty() + approvalNumber);
        requisitionOrderItem.updateById();

        retailOrderItem.setRefundableQty(retailOrderItem.getRefundableQty() + approvalNumber);
        retailOrderItem.updateById();
    }

    @Transactional(rollbackFor = Exception.class)
    public String projectGiveUp(String id) throws InterruptedException {
        InvoiceApplication invoiceApplication = invoiceApplicationService.getById(id);
        if (!invoiceApplication.getExamineStatus().equals(ExamineStatusEnum.OK.toString()))
            throw new RemoteServiceException("当前单非审核状态");

        if (invoiceApplication.getGejiangSync() != null && invoiceApplication.getGejiangSync().equals(0))
            throw new RemoteServiceException("当前单未同步采购入库单无法弃审");

        SalesOrder salesOrder = salesOrderService.lambdaQuery().eq(SalesOrder::getOrderNo, invoiceApplication.getId()).one();
        if (salesOrder.getExamineStatus().equals(ExamineStatusEnum.OK.toString()))
            throw new RemoteServiceException("销售出库单已审核通过无法弃审");
        if (retreatDocumentOrderService.lambdaQuery().eq(RetreatDocumentOrder::getInvoiceId, invoiceApplication.getId()).count() > 0)
            throw new RemoteServiceException("该申请发货单有退货操作不可弃审");

        if (invoiceApplication.getGejiangSync() != null && invoiceApplication.getGejiangSync().equals(0))
            throw new RemoteServiceException("当前单未同步采购入库单无法弃审");


        //1,删除销售出库单和发货单
        salesOrderItemService.lambdaUpdate().eq(SalesOrderItem::getInvoiceId, invoiceApplication.getId()).remove();
        salesOrderService.lambdaUpdate().eq(SalesOrder::getOrderNo, invoiceApplication.getId()).remove();
        shipDocumentService.lambdaUpdate().eq(ShipDocument::getId, invoiceApplication.getId()).remove();


        //2返还数量到销售订单

        //生成订单流水号
        String substring = invoiceApplication.getId().substring(0, 2);
        String yyyyMM = DateUtil.format(new Date(), "yyyyMM");
        String orderWater = yyyyMM.substring(yyyyMM.length() - 4);
        if (redisUtil.get(Constant.RedisPrefix.INVOICE_APPLICATION + orderWater) == null) {
            redisUtil.set(Constant.RedisPrefix.INVOICE_APPLICATION + orderWater, "0000", 2726560);
        }
        Object water = redisUtil.get(Constant.RedisPrefix.INVOICE_APPLICATION + orderWater);
        String s = pickLogic.generateNum(4, Convert.toStr(water));

        if (invoiceApplicationService.lambdaQuery().eq(InvoiceApplication::getId, substring + orderWater + s).count() > 0) {
            throw new RemoteServiceException("请勿频繁新增，稍等一会");
        }
        redisUtil.set(Constant.RedisPrefix.INVOICE_APPLICATION + orderWater, s, 2726560);

        invoiceApplicationService.removeById(invoiceApplication.getId());




        List<InvoiceApplicationOrder> list = invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, invoiceApplication.getId()).list();
        invoiceApplication.setId(substring + orderWater + s);
        List<DepositManageRecordBean> depositManageRecordList = new ArrayList<>();
        for (InvoiceApplicationOrder order : list) {

            order.setInvoiceId(invoiceApplication.getId());
            order.updateById();

            if (pickManagerShipService.lambdaQuery().eq(PickManagerShip::getInvoiceOrderId, order.getId()).count() > 0)
                throw new RemoteServiceException("该申请发货单有提货预约操作不可弃审");
            //变更可退货数量
            if (order.getOrderType().equals("TRADE") || order.getOrderType().equals("HOME"))
                changeAddEnginRefundableQty(order.getOrderId(), order.getApprovalNumber());

            if (order.getOrderType().equals("PERMU_TRADE") || order.getOrderType().equals("PERMU_HOME"))
                changeSubDiplaceRefundableQty(order.getOrderId(), order.getApprovalNumber());

            if (order.getOrderType().equals("REQUISITION_TRADE") || order.getOrderType().equals("REQUISITION_HOME"))
                changeSubRequisitonRefundableQty(order.getRequisitionItemId(), order.getApprovalNumber());

            //增加经销商暂扣库存

            stockCommonLogic.reduceStockCustomerSuspended(order.getMaterialId(), invoiceApplication.getCustomerId(), order.getRefundableQty());

            //记录台账记录
            String customerWalletId = null;
            if (order.getOrderType().equals("HOME") || order.getOrderType().equals("TRADE")) {
                EnginOrderItem engin = enginOrderItemService.getById(order.getOrderId());
                if (engin.getRefundableQty().equals("0") && engin.getIsDirectTransfer() == false) {
                    order.setPayAmount(
                            engin.getPayAmount().subtract(new BigDecimal((engin.getHasSendQty() - engin.getDirectTransferQty())).multiply(engin.getSinglePayPrice())));
                }
                customerWalletId = engin.getCustomerWalletId();
            }
            if (order.getOrderType().equals("PERMU_TRADE") || order.getOrderType().equals("PERMU_HOME")) {
                DisplaceOrderItem displaceOrderItem = displaceOrderItemService.getById(order.getOrderId());
                if (displaceOrderItem.getRefundableQty().equals("0")) {
                    order.setPayAmount(
                            displaceOrderItem.getPayAmount().subtract(new BigDecimal((displaceOrderItem.getHasSendQty())).multiply(displaceOrderItem.getSinglePayPrice())));
                }
                customerWalletId = displaceOrderItem.getCustomerWalletId();
            }

            if (order.getOrderType().equals("REQUISITION_TRADE") || order.getOrderType().equals("REQUISITION_HOME")) {
                RequisitionOrderItem requisitionOrderItem = requisitionOrderItemService.getById(order.getRequisitionItemId());
                if (requisitionOrderItem.getRefundableQty().equals("0")) {
                    order.setPayAmount(
                            requisitionOrderItem.getPayAmount().subtract(new BigDecimal((requisitionOrderItem.getHasSendQty())).multiply(requisitionOrderItem.getSinglePayPrice())));
                }
                customerWalletId = requisitionOrderItem.getCustomerWalletId();
            }
            CustomerWallet customerWallet = customerWalletService.getById(customerWalletId);
            walletLogic.saveCustomerWalletRecord(customerWallet, order.getPayAmount(), "工程申请发货单流水弃审", "申请发货单", new Date(), invoiceApplication.getId(), 3, "IN");


            //工程扣除押金
            EnginOrder enginOrder = enginOrderService.getById(order.getMainOrderId());
            EnginOrderItem orderItem = enginOrderItemService.getById(order.getOrderId());
   /*         if (order.getOrderType().equals("HOME") || order.getOrderType().equals("PERMU_HOME")) {
                DepositManageRecordBean depositManageRecordBean = new DepositManageRecordBean();
                enginOrder.setEnginOrderNo(invoiceApplication.getId());
                enginOrder.setOrderDate(invoiceApplication.getOrderTime());
                depositManageRecordBean.handleEnginOrderItem(enginOrder, orderItem, order.getRefundableQty(), orderItem.getSingleDepositAmount().multiply(new BigDecimal(Convert.toStr(order.getRefundableQty()))));
                depositManageRecordList.add(depositManageRecordBean);
            }*/
        }

        /*depositManageLogic.reduceDepositAmount(invoiceApplication.getRefEnginRecordNo(), depositManageRecordList);*/
        //3订单改为提审状态
        invoiceApplication.setExamineStatus(ExamineStatusEnum.WAIT.toString());
        invoiceApplication.setCounterclaim(true);
        invoiceApplicationService.save(invoiceApplication);

        if (invoiceApplication.getGejiangSync() != null && invoiceApplication.getGejiangSync().equals(1)){
            geJiangInStockLogic.unAuditByBillNo(id);
        }
        invoiceMapper.updateWithold(id,Constant.ENGIN_UPDATE);
        return invoiceApplication.getId();
    }

    public IPage<InvoiceBean> listInvoice(Integer invoicePrintStatus,String createBy,String refEnginRecordNo,String discriminate,String materialOldNumber,Integer printStatus,Integer type,String approvalStartTime,String approvalEndTime,String categoryId,String k3ServiceId,String mainOrderId,
                                          String id, String categoryName, String customerName, List<String> correspondId, String correspondName, String materialName,
                                          String materialNumber,
                                          String createStartTime, String createEndTime, String specification, String startTime, String endTime, String customerNumber, String examineStatus,
                                          Integer pageNum, Integer pageSize, String serviceId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        Integer count= invoiceMapper.listInvoiceHuiZongCount(invoicePrintStatus,createBy, refEnginRecordNo, discriminate, materialOldNumber, printStatus, type, approvalStartTime, approvalEndTime, categoryId, k3ServiceId, mainOrderId, id, categoryName, customerName, correspondId, correspondName, materialName, specification,
                startTime, endTime, customerNumber, examineStatus, materialNumber, customerId, adminUser.getServiceIds(), createStartTime, createEndTime,
                serviceId, adminUser.getK3CategoryIds());

        IPage<InvoiceBean> invoiceBeanIPage = invoiceMapper.listInvoiceHuiZong(new Page<>(pageNum, pageSize, count, false), invoicePrintStatus, createBy, refEnginRecordNo, discriminate, materialOldNumber, printStatus, type, approvalStartTime, approvalEndTime, categoryId, k3ServiceId, mainOrderId, id, categoryName, customerName, correspondId, correspondName, materialName, specification,
                startTime, endTime, customerNumber, examineStatus, materialNumber, customerId, adminUser.getServiceIds(), createStartTime, createEndTime,
                serviceId, adminUser.getK3CategoryIds());

        Map<String, String> kingDeeMap = kingDeeDepartmentService.lambdaQuery()
                .select(KingDeeDepartment::getNumber, KingDeeDepartment::getName).list()
                .stream().collect(Collectors.toMap(KingDeeDepartment::getNumber, KingDeeDepartment::getName));
        for (InvoiceBean record : invoiceBeanIPage.getRecords()) {
            record.setK3OrgName(kingDeeMap.get(record.getK3OrgNumber()));
        }

        return invoiceBeanIPage;
    }


  /*  public ExcelData exportData(List<InvoiceBean> invoiceBeans) {
        String[] titles = new String[]{"厂产品代码", "制单日期", "受订日期", "订单日期", "订单制单日期",
                "发货单号", "经销商编码", "客户简称", "销售类型", "存货名称", "存货编码",
                "规格型号","仓库", "发货金额", "发货返利金额", "发货折扣金额", "折扣额合计","含税单价","含税总额", "发货数量", "业务员",
                "政策单号", "政策名称", "区域", "业务区域", "月份", "项目编码", "项目名称", "表头备注", "备注", "表头业务员", "表体业务员"};

        List<List<Object>> rows = new ArrayList<>();
        for (InvoiceBean invoiceBean : invoiceBeans) {
            List<Object> row = new ArrayList<>();
            row.add(invoiceBean.getMaterialOldNumber());
            row.add(DateUtil.formatDate(invoiceBean.getCreateTime()));
            row.add(DateUtil.formatDate(invoiceBean.getTheTime()));
            row.add(DateUtil.formatDate(invoiceBean.getCreateTime()));
            row.add(DateUtil.formatDate(invoiceBean.getCreateTime()));
            row.add(invoiceBean.getId());
            row.add(invoiceBean.getCustomerNumber());
            row.add(invoiceBean.getCustomerName());
            row.add(invoiceBean.getSaleTypeName());
            row.add(invoiceBean.getMaterialName());
            row.add(invoiceBean.getMaterialCode());
            row.add(invoiceBean.getSpecification());
            row.add(invoiceBean.getCorrespondName());
            row.add(invoiceBean.getPayAmount());
            row.add(invoiceBean.getPayRebateAmount());
            row.add(invoiceBean.getTotalDiscAmount());
            row.add(invoiceBean.getTotalDiscAmount().add(invoiceBean.getPayRebateAmount()));
            row.add(invoiceBean.getSinglePayPrice());
            row.add(invoiceBean.getPayAmount());
            row.add(invoiceBean.getRefundableQty());
            row.add(invoiceBean.getServiceName());
            row.add(invoiceBean.getPolicyCode());
            row.add(invoiceBean.getPolicyTitle());
            row.add(invoiceBean.getAdminArea());
            row.add(invoiceBean.getServiceArea());
            row.add(invoiceBean.getMonth());
            row.add(invoiceBean.getRefEnginRecordNo());
            row.add(invoiceBean.getRefProjectName());
            row.add(invoiceBean.getRemark());
            row.add(invoiceBean.getInvoiceRemark());
            row.add(invoiceBean.getK3ServiceName());
            row.add(invoiceBean.getServiceName());
            row.add(invoiceBean.getCorrespondName());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }*/

    public ExcelData exportData(List<InvoiceBean> invoiceBeans) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        Boolean customer = adminUser.getIsCustomer();
        String[] titles ;
        if (customer == false) {
             titles = new String[]{"状态","审核时间", "发货日期", "订单时间", "发货单号","订单号", "经销商编码", "经销商名称", "销售类型", "物料编码", "厂产品代码",
                    "产品名称","物料分组", "规格型号", "仓库", "发货金额", "发货返利金额", "发货折扣金额", "折扣额合计", "含税单价", "含税总额", "发货数量","未出库数量",
                    "政策单号", "政策名称", "区域", "业务区域", "月份", "工程登录编号","存货类别", "项目名称", "表头备注", "表体备注", "发货单申请备注", "表头业务员", "表体业务员",
                    "现金钱包", "返利钱包", "文件编号", "集团", "工程订单号", "订单日期", "单据状态", "项目类别", "行业类别", "区域", "跨区厂编号", "安装地址", "联系人", "固定电话", "移动电话", "不扣押金", "工程文件编号", "项目说明"
                    , "项目类型", "格力内部备注", "订单备注", "第几次申报", "制单人", "制单日期", "审核人", "审核日期", "关闭日期", "审批说明","工程编号","机型类别","权限分类","是否打印","二级经销商代码","存货分类","金蝶部门"};
        }else {
            titles = new String[]{"状态","审核时间",  "发货日期", "订单时间", "发货单号","订单号",  "经销商编码", "经销商名称", "销售类型", "物料编码", "厂产品代码",
                    "产品名称","物料分组", "规格型号", "仓库", "发货金额", "发货返利金额", "发货折扣金额", "折扣额合计", "含税单价", "含税总额", "发货数量","未出库数量",
                    "政策单号", "政策名称", "区域", "业务区域", "月份", "工程登录编号","存货类别", "项目名称", "表头备注", "表体备注", "发货单申请备注", "表头业务员", "表体业务员",
                    "现金钱包", "返利钱包", "文件编号", "集团", "工程订单号", "订单日期", "单据状态", "项目类别", "行业类别", "区域", "跨区厂编号", "安装地址", "联系人", "固定电话", "移动电话", "不扣押金", "工程文件编号", "项目说明"
                    , "项目类型", "订单备注", "第几次申报", "制单人", "制单日期", "审核人", "审核日期", "关闭日期", "审批说明","工程编号","机型类别","是否打印","二级经销商代码","存货分类","金蝶部门"};
        }


        List<List<Object>> rows = new ArrayList<>();
        for (InvoiceBean invoiceBean : invoiceBeans) {
            List<Object> row = new ArrayList<>();
//            row.add(ExamineStatusEnum.valueOf(invoiceBean.getExamineStatus()).getMsg());
            row.add(EnumUtil.getNameFieldMap(ExamineStatusEnum.class, "value").get(invoiceBean.getExamineStatus()));
            row.add(DateUtil.formatDate(invoiceBean.getApprovalTime()));
            row.add(DateUtil.formatDate(invoiceBean.getOrderTime()));
            row.add(DateUtil.formatDate(invoiceBean.getTheTime()));
            row.add(invoiceBean.getId());
            row.add(invoiceBean.getOrderType().equals("HOME") || invoiceBean.getOrderType().equals("TRADE")
                    || invoiceBean.getOrderType().equals("REQUISITION_TRADE") || invoiceBean.getOrderType().equals("REQUISITION_HOME") ? invoiceBean.getEnginOrderNo():invoiceBean.getMainOrderId());
            row.add(invoiceBean.getCustomerNumber());
            row.add(invoiceBean.getCustomerName());
            row.add(invoiceBean.getSaleTypeName());
            row.add(invoiceBean.getMaterialCode());
            row.add(invoiceBean.getMaterialOldNumber());
            row.add(invoiceBean.getMaterialName());
            row.add(invoiceBean.getMaterialGroupName());
            row.add(invoiceBean.getSpecification());
            row.add(invoiceBean.getCorrespondName());
            row.add(invoiceBean.getPayAmount());
            row.add(invoiceBean.getPayRebateAmount());
            row.add(invoiceBean.getTotalDiscAmount());
            row.add(invoiceBean.getTotalDiscAmount().add(invoiceBean.getPayRebateAmount()));
            row.add(invoiceBean.getSinglePayPrice());
            row.add(invoiceBean.getPayAmount());
            row.add(invoiceBean.getRefundableQty());
            row.add(StringUtils.isNotEmpty(invoiceBean.getSalesExamineStatus())&&invoiceBean.getSalesExamineStatus().equals("OK")?0:invoiceBean.getRefundableQty());
            row.add(invoiceBean.getPolicyCode());
            row.add(invoiceBean.getPolicyTitle());
            row.add(invoiceBean.getAdminArea());
            row.add(invoiceBean.getServiceArea());
            row.add(invoiceBean.getMonth());
            row.add(invoiceBean.getRefEnginRecordNo());
            row.add(invoiceBean.getCategoryName());
            row.add(invoiceBean.getRefProjectName());
            row.add(invoiceBean.getHeaderRemark());
            row.add(invoiceBean.getInvoiceRemark());
            row.add(invoiceBean.getRemark());
            row.add(invoiceBean.getK3ServiceName());
            row.add(invoiceBean.getServiceName());
            row.add(invoiceBean.getCustomerWalletName());
            row.add(invoiceBean.getCustomerWalletName2());
            row.add(invoiceBean.getItemFileNo());
            row.add(invoiceBean.getCustomerGroupName());
            row.add(invoiceBean.getEnginOrderNo());
            row.add(DateUtil.formatDate(invoiceBean.getOrderDate()));
//            row.add(ExamineStatusEnum.valueOf(invoiceBean.getExamineStatus()).getMsg());
            row.add(EnumUtil.getNameFieldMap(ExamineStatusEnum.class, "value").get(invoiceBean.getExamineStatus()));
            row.add(invoiceBean.getRefProjectCategory());
            row.add(invoiceBean.getRefTradeCategory());
            row.add(invoiceBean.getRefRegionWork());
            row.add(invoiceBean.getRefFactoryNo());
            row.add(invoiceBean.getRefInstallAddress());
            row.add(invoiceBean.getRefLinkman());
            row.add(invoiceBean.getRefTel());
            row.add(invoiceBean.getRefPhone());
            row.add(invoiceBean.getTakeDeposit() != null ? invoiceBean.getTakeDeposit() == true ?"不扣":"扣":"");
            row.add(invoiceBean.getEnginFileNo() );
            row.add(invoiceBean.getRefProjectNote() );
            row.add(invoiceBean.getRefProjectType() );
            if (customer == false) {
                row.add(invoiceBean.getGeLiInerNote());
            }
            row.add(invoiceBean.getEnginRemark() );
            row.add(invoiceBean.getRefDeclareNo() );
            row.add(invoiceBean.getEnginCreateBy() );
            row.add(DateUtil.formatDate(invoiceBean.getEnginCreateTime()) );
            row.add(invoiceBean.getConfirmName() );
            row.add(DateUtil.formatDate(invoiceBean.getConfirmTime()) );
            row.add(DateUtil.formatDate(invoiceBean.getCloseTime()) );
            row.add(invoiceBean.getExamineNote() );
            row.add(invoiceBean.getRefProjectNo() );
            row.add(invoiceBean.getRefMachineType() );
            if (customer == false) {
                row.add(invoiceBean.getRefPowerCategory());
            }
            row.add(!StringUtils.isEmpty(invoiceBean.getPrintStatus()) && invoiceBean.getPrintStatus().equals(1)?"已打印":"未打印");
            row.add(invoiceBean.getSecondCustomerNumber());
            row.add(invoiceBean.getK3CategoryName());
            row.add(invoiceBean.getK3OrgName());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }


    public void printAdd(List<String> ids, HttpServletRequest request) {
        invoiceMapper.printAdd(ids);
    }

    public IPage<InvoiceBean> listInvoiceHuizong(Integer invoicePrintStatus,String createBy,String refEnginRecordNo,String discriminate,String materialOldNumber,Integer printStatus,Integer type,String approvalStartTime,String approvalEndTime,String categoryId,String k3ServiceId, String mainOrderId, String id, String categoryName,
                                                 String customerName, List<String> correspondId, String correspondName,
                                                 String materialName, String materialNumber, String createStartTime, String createEndTime, String specification, String startTime, String endTime,
                                                 String customerNumber, String examineStatus, Integer pageNum, Integer pageSize, String serviceId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        IPage<InvoiceBean> invoiceBeanIPage = invoiceMapper.listInvoiceHuiZong(new Page<>(pageNum, pageSize),invoicePrintStatus,createBy,refEnginRecordNo,discriminate,materialOldNumber,printStatus,type,approvalStartTime,approvalEndTime,categoryId, k3ServiceId, mainOrderId, id, categoryName, customerName, correspondId, correspondName, materialName, specification,
                startTime, endTime, customerNumber, examineStatus, materialNumber, customerId, adminUser.getServiceIds(), createStartTime, createEndTime,
                serviceId, adminUser.getK3CategoryIds());
        List<KingDeeCustomer> list = kingDeeCustomerService.lambdaQuery().eq(KingDeeCustomer::getIsGroupCompany, 1).list();
        Map<String, String> collect1 = list.stream().collect(Collectors.toMap(KingDeeCustomer::getId, KingDeeCustomer::getName));
        Map<String, String> kingDeeMap = kingDeeDepartmentService.lambdaQuery()
                .select(KingDeeDepartment::getNumber, KingDeeDepartment::getName).list()
                .stream().collect(Collectors.toMap(KingDeeDepartment::getNumber, KingDeeDepartment::getName));

        for (InvoiceBean record : invoiceBeanIPage.getRecords()) {
            record.setK3OrgName(kingDeeMap.get(record.getK3OrgNumber()));
            if (StringUtils.isNotEmpty(record.getParentId())) {
                record.setCustomerGroupName(collect1.get(record.getParentId()));

            }
        }
        return invoiceBeanIPage;
    }

    public InvoiceNumber listInvoiceNumber(Integer invoicePrintStatus,String createBy,String refEnginRecordNo,String discriminate,String materialOldNumber,Integer printStatus,Integer type,String approvalStartTime, String approvalEndTime, String categoryId, String k3ServiceId, String mainOrderId, String id, String categoryName, String customerName,
                                     List<String> correspondId, String correspondName, String materialName, String materialNumber, String createStartTime, String createEndTime, String specification, String startTime, String endTime, String customerNumber, String examineStatus, Integer pageNum, Integer pageSize, String serviceId) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        return invoiceMapper.listInvoiceNumber(new Page<>(pageNum, pageSize),invoicePrintStatus,createBy,refEnginRecordNo,discriminate,materialOldNumber,printStatus,type,approvalStartTime,approvalEndTime,categoryId, k3ServiceId,mainOrderId, id, categoryName, customerName, correspondId, correspondName, materialName, specification,
                startTime, endTime, customerNumber, examineStatus, materialNumber, customerId, adminUser.getServiceIds(), createStartTime, createEndTime,
                serviceId, adminUser.getK3CategoryIds());
    }


    /*
    * 发货单生订单号
    * */
    public String generateInvoiceOrder(String websitNumber) {

        //生成订单流水号
        String yyyyMM = DateUtil.format(new Date(), "yyyyMM");
        String orderWater = yyyyMM.substring(yyyyMM.length() - 4);
        if (redisUtil.get(Constant.RedisPrefix.INVOICE_APPLICATION + orderWater) == null) {
            redisUtil.set(Constant.RedisPrefix.INVOICE_APPLICATION + orderWater, "0000", 2726560);
        }
        Object water = redisUtil.get(Constant.RedisPrefix.INVOICE_APPLICATION + orderWater);
        String s = pickLogic.generateNum(4, Convert.toStr(water));

        if (invoiceApplicationService.lambdaQuery().eq(InvoiceApplication::getId, websitNumber + orderWater + s).count() > 0) {
            throw new RemoteServiceException("请勿频繁新增，稍等一会");
        }
        redisUtil.set(Constant.RedisPrefix.INVOICE_APPLICATION + orderWater, s, 2726560);

        return orderWater + s;
    }

    public IPage<InvoiceVO> listV2(ZfireParamBean zfireParamBean) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";


        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);


       // Integer count = invoiceMapper.listCountV2(zfireParamBean, customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds());

        IPage<InvoiceVO> stockBeanToDayIPage = invoiceMapper.listV2(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean
                , customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds());

        List<String> collect = stockBeanToDayIPage.getRecords().stream().map(InvoiceVO::getItemId).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(collect))
            return stockBeanToDayIPage;

        List<InvoiceVO> invoiceRetailVOS = invoiceMapper.huiZongList(collect);
        stockBeanToDayIPage.setRecords(invoiceRetailVOS);


        Map<String, String> kingDeeMap = kingDeeDepartmentService.lambdaQuery()
                .select(KingDeeDepartment::getNumber, KingDeeDepartment::getName).list()
                .stream().collect(Collectors.toMap(KingDeeDepartment::getNumber, KingDeeDepartment::getName));
        for (InvoiceVO record : stockBeanToDayIPage.getRecords()) {
            record.setK3OrgName(kingDeeMap.get(record.getK3OrgNumber()));
        }

        return stockBeanToDayIPage;

    }

    public IPage<InvoiceRetailVO> listRetailV2(ZfireParamBean zfireParamBean,Integer integer) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);

        IPage<InvoiceRetailVO> invoiceRetailVOIPage = invoiceMapper.listRetailV2(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()),
                zfireParam
                , customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds(),integer);

        List<String> collect = invoiceRetailVOIPage.getRecords().stream().map(InvoiceRetailVO::getItemId).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(collect))
            return invoiceRetailVOIPage;


        List<InvoiceRetailVO> invoiceRetailVOS = invoiceMapper.retailList(collect);
        invoiceRetailVOIPage.setRecords(invoiceRetailVOS);
        return invoiceRetailVOIPage;
    }

    public IPage<InvoiceProjectVO> listProjectV2(InvoiceProjectDTO zfireParamBean) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean);

        IPage<InvoiceProjectVO> invoiceProjectVOIPage = invoiceMapper.listProjectV2(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()),
                zfireParam
                , customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds(),zfireParamBean.getOrderType());

        List<String> collect = invoiceProjectVOIPage.getRecords().stream().map(InvoiceProjectVO::getItemId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect))
            return invoiceProjectVOIPage;

        List<InvoiceProjectVO> invoiceRetailVOS = invoiceMapper.projectList(collect);
        invoiceProjectVOIPage.setRecords(invoiceRetailVOS);

        return invoiceProjectVOIPage;
    }

    public InvoiceNumber listInvoiceNumberV2(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        //1.组装查询条件
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        return invoiceMapper.listInvoiceNumberV2( zfireParamBean
                , customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds());
    }
}
