package com.yh.saas.plugin.yiliangyiyun.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsea.svc.base.base.entity.CommonCompany;
import com.winsea.svc.base.base.entity.CommonStaff;
import com.winsea.svc.base.base.service.ICommonCompanyService;
import com.winsea.svc.base.base.service.ICommonStaffService;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.winsea.svc.base.workflow.entity.Workflow;
import com.winsea.svc.notice.entity.NoticeTaskInfo;
import com.winsea.svc.notice.entity.base.BaseNotice;
import com.winsea.svc.notice.service.INoticeService;
import com.winsea.svc.notice.service.INoticeTaskService;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.yiliangyiyun.constant.NumberConstant;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.WarehouseInOutInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.plugins.Page;
import com.yh.saas.common.support.util.StringUtils;
import com.yh.saas.plugin.yiliangyiyun.entity.WarehouseBaseInfo;
import com.yh.saas.plugin.yiliangyiyun.entity.WarehouseInOutDetail;
import com.yh.saas.plugin.yiliangyiyun.entity.WarehouseInOutInfo;
import com.google.common.collect.Lists;
import com.yh.saas.plugin.yiliangyiyun.service.IWarehouseInOutDetailService;
import com.yh.saas.plugin.yiliangyiyun.service.IWarehouseInOutInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.util.CalculationUtil;
import com.yh.saas.plugin.yiliangyiyun.util.Const;
import com.yh.saas.plugin.yiliangyiyun.util.GeTuiUtils;
import com.yh.saas.plugin.yiliangyiyun.util.WebSocket;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 记录出入库信息 服务实现类
 * </p>
 *
 * @author Gongdc
 * @since 2021-05-21
 */
@Service
public class WarehouseInOutInfoServiceImpl extends ServiceImpl<WarehouseInOutInfoMapper, WarehouseInOutInfo> implements IWarehouseInOutInfoService {
    @Autowired
    private IWarehouseInOutDetailService warehouseInOutDetailService;
    @Autowired
    private IWarehousePositionStorageInfoService warehousePositionStorageInfoService;
    @Autowired
    private  IIdentityAuthenticationInfoService identityAuthenticationInfoService;
    @Autowired
    private IWarehouseBaseInfoService warehouseBaseInfoService;
    @Autowired
    private IWarehousePositionInfoService warehousePositionInfoService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    private ITranCarInfoService tranCarInfoService;
    @Autowired
    private IPurchaseReceiptReportService purchaseReceiptReportService;
    @Autowired
    private IPurchaseOrderService purchaseOrderService;
    @Autowired
    private ISalesDeliveryReportService salesDeliveryReportService;
    @Autowired
    private ISaleOrderService saleOrderService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private INoticeTaskService noticeTaskService;
    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private ICommonStaffService staffService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private GeTuiUtils geTuiUtils;
    @Autowired
    private IStockSaleReceiptReportService stockSaleReceiptReportService;
    @Autowired
    private IStockPurchaseReceiptReportService stockPurchaseReceiptReportService;
    @Autowired
    private IWeightedDetailsService weightedDetailsService;
    @Autowired
    private ICostManagementInfoService costManagementInfoService;
    @Autowired
    private IInOutWarehouseTaskService inOutWarehouseTaskService;
    @Autowired
    private IWarehousingOrderService warehousingOrderService;
    @Autowired
    private ITranTaskInfoService tranTaskInfoService;
    @Autowired
    private ITranProcessInfoService tranProcessInfoService;
    @Autowired
    private ITranSettlementReportService tranSettlementReportService;
    @Autowired
    private WebSocket webSocket;
    @Autowired
    private IWeighingManagementService weighingManagementService;
    @Autowired
    private IQualityInspectionManagementService qualityInspectionManagementService;
    @Autowired
    private IPaymentManagementService paymentManagementService;
    @Autowired
    private ISourceRelationInfoService sourceRelationInfoService;
    @Autowired
    private IContractInventoryDistributionService contractInventoryDistributionService;

    @Autowired
    private CacheComponent cacheComponent;
    /**
     * 待完成页面列表
     *
     * @param warehouseInOutInfo
     * @return
     */
    @Override
    public Page<WarehouseInOutInfo> selectWarehouseInOutInfo(WarehouseInOutInfo warehouseInOutInfo) {
        //查询页面信息
        Wrapper<WarehouseInOutInfo> warehouseInOutInfoWrapper = new EntityWrapper<WarehouseInOutInfo>();
        if (warehouseInOutInfo.getInOutFlag() != null) {
            warehouseInOutInfoWrapper.eq("in_out_flag", warehouseInOutInfo.getInOutFlag());
        }
        warehouseInOutInfoWrapper.eq("base_id", warehouseInOutInfo.getBaseId())
                .eq("position_id", warehouseInOutInfo.getPositionId())
                .eq("status_flag", StatusEnum.TEMPORARILY_STORED.getFlag())
                .orderBy("update_date", false);
        WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectById(warehouseInOutInfo.getBaseId());
        Page<WarehouseInOutInfo> warehouseInOutInfoPage = this.selectPage(warehouseInOutInfo.getQueryPage(), warehouseInOutInfoWrapper);
        List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoPage.getRecords();
        if (warehouseInOutInfoList != null) {
            for (WarehouseInOutInfo warehouseInOutInfo1 : warehouseInOutInfoList) {
                //查询化验数据
                Wrapper<WarehouseInOutDetail> warehouseInOutDetailWrapper = new EntityWrapper<>();
                warehouseInOutDetailWrapper.eq("info_id", warehouseInOutInfo1.getId());
                warehouseInOutDetailWrapper.eq("delete_flag", "0");
                WarehouseInOutDetail warehouseInOutDetail = warehouseInOutDetailService.selectOne(warehouseInOutDetailWrapper);
                warehouseInOutInfo1.setWarehouseInOutDetail(warehouseInOutDetail);
                warehouseInOutInfo1.setAllowEdit(warehouseBaseInfo.getAllowEdit());
                warehouseInOutInfo1.setAutomaticWeightAcquisition(warehouseBaseInfo.getAutomaticWeightAcquisition());
            }
        }
        warehouseInOutInfoPage.setRecords(warehouseInOutInfoList);
        //查询总数
        Integer count = this.selectCount(new EntityWrapper<WarehouseInOutInfo>()
                .eq("base_id", warehouseInOutInfo.getBaseId())
                .eq("status_flag", StatusEnum.TEMPORARILY_STORED.getFlag())
                .eq("position_id", warehouseInOutInfo.getPositionId()));
        warehouseInOutInfoPage.setSize(count);
        return warehouseInOutInfoPage;
    }

    /**
     * 待完成页面列表(临时仓库)
     *
     * @param warehouseInOutInfo
     * @return
     */
    @Override
    public Page<WarehouseInOutInfo> selectWarehouseInOutInfoTemporary(WarehouseInOutInfo warehouseInOutInfo) {
        //查询页面信息
        Page<WarehouseInOutInfo> warehouseInOutInfoPage = this.selectPage(warehouseInOutInfo.getQueryPage(), new EntityWrapper<WarehouseInOutInfo>()
                .eq("base_id", warehouseInOutInfo.getBaseId())
                .eq("status_flag", StatusEnum.TEMPORARILY_STORED.getFlag())
                .orderBy("update_date", true));
        List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoPage.getRecords();
        if (warehouseInOutInfoList != null) {
            for (WarehouseInOutInfo warehouseInOutInfo1 : warehouseInOutInfoList) {
                //查询化验数据
                Wrapper<WarehouseInOutDetail> warehouseInOutDetailWrapper = new EntityWrapper<>();
                warehouseInOutDetailWrapper.eq("info_id", warehouseInOutInfo1.getId());
                warehouseInOutDetailWrapper.eq("delete_flag", "0");
                WarehouseInOutDetail warehouseInOutDetail = warehouseInOutDetailService.selectOne(warehouseInOutDetailWrapper);
                warehouseInOutInfo1.setWarehouseInOutDetail(warehouseInOutDetail);
            }
        }
        warehouseInOutInfoPage.setRecords(warehouseInOutInfoList);
        //查询总数
        Integer count = this.selectCount(new EntityWrapper<WarehouseInOutInfo>()
                .eq("base_id", warehouseInOutInfo.getBaseId())
                .eq("status_flag", StatusEnum.TEMPORARILY_STORED.getFlag()));
        warehouseInOutInfoPage.setSize(count);
        return warehouseInOutInfoPage;
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWarehouse(String id) {
        WarehouseInOutInfo warehouseInOutInfo = this.selectById(id);
        if (warehouseInOutInfo != null) {
            //记录
            this.deleteById(warehouseInOutInfo.getId());
            //化验信息
            WarehouseInOutDetail warehouseInOutDetail = warehouseInOutDetailService.selectOne(new EntityWrapper<WarehouseInOutDetail>().eq("info_id", id));
            warehouseInOutDetailService.deleteById(warehouseInOutDetail.getId());

        }
    }


    /**
     * 出入库
     *
     * @param warehouseInOutInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String InOutWarehouse(WarehouseInOutInfo warehouseInOutInfo) {
        CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        warehouseInOutInfo.setBackOffice(commonStaff.getStaffName());
        WarehouseInOutDetail warehouseInOutDetail = warehouseInOutInfo.getWarehouseInOutDetail();
        // 查询仓库
        WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectById(warehouseInOutInfo.getBaseId());
        //判断暂存提交(前端传参1暂存3提交)
        if ("1".equals(warehouseInOutInfo.getStatusFlag())) {
            //插入记录
            if (StringUtils.isEmpty(warehouseInOutInfo.getId())) {
                warehouseInOutInfo.setId(IdGenerator.generateUUID());
                warehouseInOutInfo.setStatusFlag(StatusEnum.TEMPORARILY_STORED.getFlag());
                warehouseInOutInfo.setStatus(StatusEnum.TEMPORARILY_STORED.getName());
                this.insert(warehouseInOutInfo);
                // 详情
                warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
                warehouseInOutDetail.setId(IdGenerator.generateUUID());
                List<WarehouseInOutDetail> ll = warehouseInOutDetailService.selectList(new EntityWrapper<WarehouseInOutDetail>().eq("info_id", warehouseInOutInfo.getId()));
                if (ll.size() == 0) {
                    warehouseInOutDetailService.insert(warehouseInOutDetail);
                }
            }
            // 编辑修改记录
            else {
                this.updateById(warehouseInOutInfo);
                //app暂存判断详情表是否存在
                if (StringUtils.isEmpty(warehouseInOutDetail.getId())) {
                    // 详情
                    warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
                    warehouseInOutDetail.setId(IdGenerator.generateUUID());
                    List<WarehouseInOutDetail> ll = warehouseInOutDetailService.selectList(new EntityWrapper<WarehouseInOutDetail>().eq("info_id", warehouseInOutInfo.getId()));
                    if (ll.size() == 0) {
                        warehouseInOutDetailService.insert(warehouseInOutDetail);
                    }
                } else {
                    warehouseInOutDetailService.updateById(warehouseInOutDetail);
                }
            }
            //入库
            if ("2".equals(warehouseInOutInfo.getInOutFlag())) {
                Wrapper wrapper = new EntityWrapper<TranCarInfo>()
                        .eq("contract_no", warehouseInOutInfo.getContractNo())
                        .eq("car_no", warehouseInOutInfo.getCarNo())
                        .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                        .eq("tran_car_no", warehouseInOutInfo.getTranCarNo());
                TranCarInfo tranCarInfo = tranCarInfoService.selectOne(wrapper);
                if (tranCarInfo != null) {
                    //将车改成已被选
                    tranCarInfo.setSubmit("2");
                    tranCarInfo.setStatusFlag(StatusEnum.DELIVERED.getFlag());
                    tranCarInfo.setStatus(StatusEnum.DELIVERED.getName());
                    tranCarInfoService.updateById(tranCarInfo);
                }
            }
            //出库
            else {
                Wrapper wrapper = new EntityWrapper<TranCarInfo>()
                        .eq("contract_no", warehouseInOutInfo.getContractNo())
                        .eq("car_no", warehouseInOutInfo.getCarNo())
                        .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                        .eq("tran_car_no", warehouseInOutInfo.getTranCarNo());
                TranCarInfo tranCarInfo = tranCarInfoService.selectOne(wrapper);
                if (tranCarInfo != null) {
                    if ("1".equals(tranCarInfo.getSubmit())) {
                        throw new YException(YExceptionEnum.CARNO_SUBMITTED_ERROR);
                    } else {
                        tranCarInfo.setSubmit("1");
                    }
                    tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                    tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                    tranCarInfoService.updateById(tranCarInfo);
                }
            }

        } else {
            //插入记录
            if (StringUtils.isEmpty(warehouseInOutInfo.getId())) {
                warehouseInOutInfo.setId(IdGenerator.generateUUID());
                warehouseInOutInfo.setStatusFlag(StatusEnum.SUBMITTED.getFlag());
                warehouseInOutInfo.setStatus(StatusEnum.SUBMITTED.getName());
                this.insert(warehouseInOutInfo);
                //更新出入库任务表已完成量
                InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                        .eq("in_out_task_no", warehouseInOutInfo.getInOutTaskNo()));
                if (inOutWarehouseTask != null) {
                    //更新货源实际出库重量
                    List<SourceRelationInfo> sourceRelationInfoList=sourceRelationInfoService.selectList(new EntityWrapper<SourceRelationInfo>()
                    .eq("task_id",inOutWarehouseTask.getId()));
                    if (!CollectionUtils.isEmpty(sourceRelationInfoList)){
                        for (SourceRelationInfo sourceRelationInfo:sourceRelationInfoList){
                            //实际重量
                            sourceRelationInfo.setActualOutWarehouseWeight(sourceRelationInfo.getActualOutWarehouseWeight()+Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()*sourceRelationInfo.getProportion())));
                            //剩余重量
                            sourceRelationInfo.setSurplusWeight(sourceRelationInfo.getSurplusWeight()-Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()*sourceRelationInfo.getProportion())));
                            sourceRelationInfoService.updateById(sourceRelationInfo);
                        }
                    }
                    //可超出重量
                    Float overNeight = 0.0f;
                    ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                            .eq("comp_id", inOutWarehouseTask.getCompId())
                            .eq("contract_no", inOutWarehouseTask.getContractNo()));
                    //入库
                    if (contractManagementInfo != null && "2".equals(inOutWarehouseTask.getInOutFlag())) {
                        overNeight = inOutWarehouseTask.getWeight() * (contractManagementInfo.getOverShort() / 100);
                    } else {
                        contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("comp_id", inOutWarehouseTask.getCompId())
                                .eq("contract_no", inOutWarehouseTask.getWarehouseName()));
                        //移库入库
                        if (contractManagementInfo == null && "2".equals(inOutWarehouseTask.getInOutFlag())) {
                            overNeight = inOutWarehouseTask.getWeight() * 0.08f;
                        }
                    }
                    inOutWarehouseTask.setCompletedQuantity(inOutWarehouseTask.getCompletedQuantity() + warehouseInOutInfo.getNetWeight());
                    if (inOutWarehouseTask.getCompletedQuantity() > inOutWarehouseTask.getWeight() + overNeight) {
                        throw new YException(YExceptionEnum.TASK_WEIGHT_EXCEEDED_ERROR);
                    } else {
                        inOutWarehouseTaskService.updateById(inOutWarehouseTask);
                    }
                }
                // 详情
                warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
                warehouseInOutDetail.setId(IdGenerator.generateUUID());
                List<WarehouseInOutDetail> ll = warehouseInOutDetailService.selectList(new EntityWrapper<WarehouseInOutDetail>().eq("info_id", warehouseInOutInfo.getId()));
                if (ll.size() == 0) {
                    warehouseInOutDetailService.insert(warehouseInOutDetail);
                }

            }
            // 编辑修改记录
            else {
                //更新出入库任务表已完成量
                InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                        .eq("in_out_task_no", warehouseInOutInfo.getInOutTaskNo()));
                if (inOutWarehouseTask != null) {
                    //可超出重量
                    Float overNeight = 0.0f;
                    ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                            .eq("comp_id", inOutWarehouseTask.getCompId())
                            .eq("contract_no", inOutWarehouseTask.getContractNo()));
                    //入库
                    if (contractManagementInfo != null && "2".equals(inOutWarehouseTask.getInOutFlag())) {
                        overNeight = inOutWarehouseTask.getWeight() * (contractManagementInfo.getOverShort() / 100);
                    } else {
                        contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("comp_id", inOutWarehouseTask.getCompId())
                                .eq("contract_no", inOutWarehouseTask.getWarehouseName()));
                        //移库入库
                        if (contractManagementInfo == null && "2".equals(inOutWarehouseTask.getInOutFlag())) {
                            overNeight = inOutWarehouseTask.getWeight() * 0.08f;
                        }
                    }
                    inOutWarehouseTask.setCompletedQuantity(inOutWarehouseTask.getCompletedQuantity() + warehouseInOutInfo.getNetWeight());
                    if (inOutWarehouseTask.getCompletedQuantity() > inOutWarehouseTask.getWeight() + overNeight) {
                        throw new YException(YExceptionEnum.TASK_WEIGHT_EXCEEDED_ERROR);
                    } else {
                        inOutWarehouseTaskService.updateById(inOutWarehouseTask);
                    }
                }
                warehouseInOutInfo.setInOutDate(new Date());
                warehouseInOutInfo.setStatusFlag(StatusEnum.SUBMITTED.getFlag());
                warehouseInOutInfo.setStatus(StatusEnum.SUBMITTED.getName());
                this.updateById(warehouseInOutInfo);
                warehouseInOutDetailService.updateById(warehouseInOutDetail);
            }
            // 采购订单
            PurchaseOrder purchaseOrder = purchaseOrderService.selectOne(new EntityWrapper<PurchaseOrder>().eq("contract_no", warehouseInOutInfo.getContractNo())
                    .eq("delete_flag", "0"));
            // 销售订单
            SaleOrder saleOrder = saleOrderService.selectOne(new EntityWrapper<SaleOrder>().eq("contract_no", warehouseInOutInfo.getContractNo())
                    .eq("delete_flag", "0"));
            //APP线上订单
            if (purchaseOrder != null || saleOrder != null) {
                // 先删除任务
                noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "INOUTTASK-TASK-APPROVE",
                        warehouseInOutInfo.getId(), null);
                //APP线上订单入库
                if ("2".equals(warehouseInOutInfo.getInOutFlag())) {
                    TranCarInfo tranCarInfo = tranCarInfoService.selectOne(new EntityWrapper<TranCarInfo>()
                            .eq("contract_no", warehouseInOutInfo.getContractNo())
                            .eq("car_no", warehouseInOutInfo.getCarNo())
                            .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0));
                    // 合同表
                    ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>().eq("contract_no", warehouseInOutInfo.getContractNo())
                            .eq("delete_flag", "0"));
                    //更新库存量
                    if (warehouseBaseInfo != null) {
                        float original = 0f;
                        //  查询库位
                        WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectById(warehouseInOutInfo.getPositionId());
                        if (warehousePositionInfo != null) {
                            // 查询货物库存量
                            WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                                    .eq("position_id", warehouseInOutInfo.getPositionId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName())
                                    .eq("delete_flag", "0"));
                            // 判断是否有货
                            if (warehousePositionStorageInfo != null) {
                                original = Float.valueOf(String.valueOf(warehousePositionStorageInfo.getStorage() + warehouseInOutInfo.getNetWeight()));
                                ;
                                // 更新库存量
                                warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
                            }
                            // 没有货
                            else {
                                original = 0f;
                                WarehousePositionStorageInfo warehousePositionStorageInfo1 = new WarehousePositionStorageInfo();
                                warehousePositionStorageInfo1.setId(IdGenerator.generateUUID());
                                warehousePositionStorageInfo1.setPositionId(warehouseInOutInfo.getPositionId());
                                warehousePositionStorageInfo1.setBinNumber(warehouseInOutInfo.getBinNumber());
                                warehousePositionStorageInfo1.setGoodsName(warehouseInOutInfo.getGoodsName());
                                warehousePositionStorageInfo1.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
                                warehousePositionStorageInfo1.setStorage(warehouseInOutInfo.getNetWeight());
                                warehousePositionStorageInfoService.insert(warehousePositionStorageInfo1);
                            }
                        }
//                    // 生成加权成本数据
//                    WeightedDetails weightedDetails = new WeightedDetails();
//                    weightedDetails.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
//                    weightedDetails.setId(IdGenerator.generateUUID());
//                    weightedDetails.setWarehouseId(warehouseInOutInfo.getBaseId());
//                    weightedDetails.setWarehouseName(warehouseInOutInfo.getWarehouseName());
//                    weightedDetails.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
//                    weightedDetails.setGoodsName(warehouseInOutInfo.getGoodsName());
//                    weightedDetails.setGrainType(warehouseInOutInfo.getType());
//                    weightedDetails.setInTypeKey(warehouseInOutInfo.getTaskTypeKey());
//                    weightedDetails.setInType(warehouseInOutInfo.getTaskType());
//                    weightedDetails.setNetWeight(warehouseInOutInfo.getNetWeight());
//                    weightedDetails.setPureWeight(warehouseInOutInfo.getPureWeight());
//                    weightedDetails.setUnitPrice(warehouseInOutInfo.getUnitPrice());
//                    weightedDetails.setDeductionAmount(warehouseInOutInfo.getDeductionAmount());
//                    weightedDetails.setFreight(warehouseInOutInfo.getFreight());
//                    weightedDetails.setOriginalStock(original);
//                    // 查询入库全加权成本
//                    List<WeightedDetails> weightedDetailsList = weightedDetailsService.selectList(new EntityWrapper<WeightedDetails>().eq("warehouse_id", warehouseInOutInfo.getWarehouseName())
//                            .eq("goods_name_key", warehouseInOutInfo.getGoodsNameKey()).orderBy("update_date", false));
//                    if (CollectionUtils.isEmpty(weightedDetailsList)) {
//                        weightedDetails.setCostBefore(0f);
//                    } else {
//                        weightedDetails.setCostBefore(weightedDetailsList.get(0).getCostBefore());
//                    }
//                    // 计算新加权成本
//                    Float newCost = 0f;
//                    if ("干粮".equals(warehouseInOutInfo.getType())) {
//                        newCost = ((warehouseInOutInfo.getCost() + warehouseInOutInfo.getFreight()) * warehouseInOutInfo.getNetWeight() + original * weightedDetails.getCostBefore()) / (warehouseInOutInfo.getNetWeight() + original);
//
//                    } else {
//                        newCost = ((warehouseInOutInfo.getCost() + warehouseInOutInfo.getFreight()) * warehouseInOutInfo.getNetWeight() + original * weightedDetails.getCostBefore()) / (warehouseInOutInfo.getPureWeight() + original);
//
//                    }
//                    weightedDetails.setCostAfter(newCost);
//                    weightedDetailsService.insert(weightedDetails);
//                    // 修改成本信息表
//                    CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", weightedDetails.getWarehouseId())
//                            .eq("goods_name_key", weightedDetails.getGoodsNameKey()));
//                    List<WeightedDetails> weightedDetailsLists = weightedDetailsService.selectList(new EntityWrapper<WeightedDetails>().eq("warehouse_id", warehouseInOutInfo.getWarehouseName())
//                            .eq("goods_name_key", warehouseInOutInfo.getGoodsNameKey()).orderBy("update_date", false));
//                    Float net = 0f;
//                    for(int i=0;i<weightedDetailsLists.size();i++){
//                        net = net +weightedDetailsLists.get(i).getNetWeight();
//                    }
//                    if(costManagementInfo ==null){
//                        CostManagementInfo costManagementInfo1= new CostManagementInfo();
//                        costManagementInfo1.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
//                        costManagementInfo1.setId(IdGenerator.generateUUID());
//                        costManagementInfo1.setWarehouseId(weightedDetails.getWarehouseId());
//                        costManagementInfo1.setWarehouseName(weightedDetails.getWarehouseName());
//                        costManagementInfo1.setGoodsNameKey(weightedDetails.getGoodsNameKey());
//                        costManagementInfo1.setGoodsName(weightedDetails.getGoodsName());
//                        costManagementInfo1.setWarehouseType(warehouseBaseInfo.getWarehouseType());
//
//                        costManagementInfo1.setStorage(net);
//                        costManagementInfo1.setCost(weightedDetails.getCostAfter());
//                        costManagementInfoService.insert(costManagementInfo1);
//                    }
//                    else{
//                        costManagementInfo.setCost(weightedDetails.getCostAfter());
//                        costManagementInfo.setStorage(net);
//                        costManagementInfoService.updateById(costManagementInfo);
//                    }
                    }
                    // 期货采购入库统计
                    if (contractManagementInfo != null && "2".equals(contractManagementInfo.getGoodsType())) {
                        PurchaseReceiptReport purchaseReceiptReport = new PurchaseReceiptReport();
                        purchaseReceiptReport.setId(IdGenerator.generateUUID());
                        purchaseReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                        purchaseReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                        purchaseReceiptReport.setGoodsName(warehouseInOutInfo.getGoodsName());
                        purchaseReceiptReport.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
                        purchaseReceiptReport.setPositionNumber(warehouseInOutInfo.getBinNumber());
                        purchaseReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                        purchaseReceiptReport.setTranCarNo(warehouseInOutInfo.getTranCarNo());
                        purchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                        purchaseReceiptReport.setProtein(warehouseInOutDetail.getProtein());
                        purchaseReceiptReport.setWaterContent(warehouseInOutDetail.getWaterContent());
                        purchaseReceiptReport.setDeductionAmount(warehouseInOutInfo.getDeductionAmount());
                        purchaseReceiptReport.setNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        purchaseReceiptReport.setDeductionItems(warehouseInOutInfo.getDeductionItems());
                        purchaseReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                        purchaseReceiptReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                        purchaseReceiptReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
                        if (purchaseOrder != null) {
                            purchaseReceiptReport.setUnitPrice(purchaseOrder.getUnitPrice());
                            purchaseReceiptReport.setUnloadingCharge(purchaseOrder.getUnloadingCharge());
                            purchaseReceiptReport.setInvoiceFee(purchaseOrder.getInvoiceFee());
                            //期货
                            if (purchaseOrder.getBasis() != null) {
                                purchaseReceiptReport.setBasisPrice(purchaseOrder.getBasis());
                                BigDecimal unitPrice = new BigDecimal(Float.toString(purchaseReceiptReport.getUnitPrice()));
                                BigDecimal basis = new BigDecimal(Float.toString(purchaseReceiptReport.getBasisPrice()));
                                BigDecimal unloadingCharge = new BigDecimal(Float.toString(purchaseReceiptReport.getUnloadingCharge()));
                                BigDecimal invoiceFee = new BigDecimal(Float.toString(purchaseReceiptReport.getInvoiceFee()));
                                BigDecimal deductionAmount = new BigDecimal(purchaseReceiptReport.getDeductionAmount());
                                purchaseReceiptReport.setSettlementPrice(unitPrice.add(basis).add(unloadingCharge).add(invoiceFee).add(deductionAmount).floatValue());
                            }
                            purchaseReceiptReport.setCustomerName(purchaseOrder.getSeller());
                            purchaseReceiptReport.setInvoiceType(purchaseOrder.getType());
                            purchaseReceiptReport.setInvoiceTypeKey(purchaseOrder.getType());
                            purchaseReceiptReport.setAmountIngPayable(CalculationUtil.mulToFloat(purchaseReceiptReport.getSettlementPrice(), purchaseReceiptReport.getNetWeight()));
                            purchaseReceiptReport.setAmountEdPayable(0f);
                            purchaseReceiptReport.setAmountNotPayable(purchaseReceiptReport.getAmountIngPayable());
                            if (tranCarInfo != null) {
                                //将到货数据同步到派车表
                                tranCarInfo.setUnloadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                tranCarInfo.setUnloadPoundImg(warehouseInOutInfo.getAddressUrl());
                                tranCarInfo.setDeductionAmount(warehouseInOutInfo.getDeductionAmount());
                                tranCarInfo.setDeductionItems(warehouseInOutInfo.getDeductionItems());
                                tranCarInfo.setStatus(StatusEnum.DELIVERED.getName());
                                tranCarInfo.setStatusFlag(StatusEnum.DELIVERED.getFlag());
                                if (purchaseOrder != null) {
                                    tranCarInfo.setSettlementPrice(purchaseReceiptReport.getSettlementPrice());
                                }
                                tranCarInfoService.updateById(tranCarInfo);
                            }
                        }
                        // 客户确认
                        TranCarInfo tranCarInfo1 = tranCarInfoService.selectOne(new EntityWrapper<TranCarInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("car_no", warehouseInOutInfo.getCarNo())
                                .eq("delete_flag", "0"));
                        if (tranCarInfo1 != null && "3".equals(tranCarInfo1.getConfirmFlag())) {
                            purchaseReceiptReport.setCustomerConfirmationStatusFlag("1");
                            purchaseReceiptReport.setCustomerConfirmationStatus("是");
                            tesk(warehouseInOutInfo, "2");
                            geTuiUtils.pushByCid("卸货提醒", "您的合同车辆：" + warehouseInOutInfo.getCarNo() + "申请卸货，请及时确认", purchaseOrder.getCommonId());

                            UnimallMessage messageDO = new UnimallMessage();
                            messageDO.setAdminId(purchaseOrder.getCommonId());
                            messageDO.setCustomer(purchaseOrder.getCustomer());
                            messageDO.setOperation("卸货提醒");
                            messageDO.setResult("您的合同车辆：" + warehouseInOutInfo.getCarNo() + "申请卸货，请及时确认");
                            messageDO.setGmtUpdate(new java.util.Date());
                            messageDO.setGmtCreate(new Date());
                            messageDO.setTaskId(IdGenerator.generateUUID());
                            messageDO.setCompanyId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                            messageDO.setPath("XXXXX");
                            webSocket.sendOneMessage(messageDO);
                        } else {
                            purchaseReceiptReport.setCustomerConfirmationStatusFlag("3");
                            purchaseReceiptReport.setCustomerConfirmationStatus("否");
                        }
                        purchaseReceiptReportService.insert(purchaseReceiptReport);
                        boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(purchaseReceiptReport.getWorkflowId());
                        // 不是退回的单子
                        if (isStartWorkflow) {
                            Workflow workflow = workflowService
                                    .findLatestWorkflowByBusinessCodeByApp(purchaseReceiptReport.getCompId(), "PROCUREMENT-RECEIPT-REPORT");
                            // 没配置审核流程，直接结束并处理信息
                            if (workflow == null) {
                                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                            }
                            // 开启审核流
                            else {
                                // 设置状态 已提交审核
                                purchaseReceiptReport.setWorkflowId(workflow.getId());
                                purchaseReceiptReportService.updateById(purchaseReceiptReport);
                                workflowService.startInstance(workflow.getId(), purchaseReceiptReport.getId());
                            }
                        }
                        // 退回的单子 再启用
                        else {
                            purchaseReceiptReportService.updateById(purchaseReceiptReport);
                            workflowService.activateInstance(purchaseReceiptReport.getWorkflowId(), purchaseReceiptReport.getId());
                        }
                    }
                }
                //App线上订单出库
                else if ("1".equals(warehouseInOutInfo.getTaskType())) {
                    //状态改为已发车
                    warehouseInOutInfo.setTranFlag("1");

                    //判断是否第一次提交
                    if (StringUtils.isEmpty(warehouseInOutDetail.getId())) {
                        // 插入详情
                        warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
                        warehouseInOutDetail.setId(IdGenerator.generateUUID());
                        List<WarehouseInOutDetail> ll = warehouseInOutDetailService.selectList(new EntityWrapper<WarehouseInOutDetail>().eq("info_id", warehouseInOutInfo.getId()));
                        if (ll.size() == 0) {
                            warehouseInOutDetailService.insert(warehouseInOutDetail);
                        }
                    }
                    //更新库存量
                    //判断是否有货
                    if (warehouseBaseInfo != null) {
                        //  查询库位
                        WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectById(warehouseInOutInfo.getPositionId());
                        if (warehousePositionInfo != null) {
                            // 查询货物库存量
                            WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                                    .eq("position_id", warehouseInOutInfo.getPositionId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName())
                                    .eq("delete_flag", "0"));
                            // 判断是否有货
                            if (warehousePositionStorageInfo != null) {
                                if (warehouseInOutInfo.getNetWeight() <= warehousePositionStorageInfo.getStorage()) {
                                    // 更新库存量
                                    warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() - Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
                                }
                                //出库量大于库存量
                                else {
                                    throw new YException(YExceptionEnum.INVENTORY_NO_ERROR);
                                }
                            }
                            // 没有储存量
                            else {
                                throw new YException(YExceptionEnum.POSITIONSTORAGE_NO_ERROR);
                            }
                        }
                        //库位不存在
                        else {
                            throw new YException(YExceptionEnum.POSITION_NO_ERROR);
                        }
                    }
                    //仓库不存在
                    else {
                        throw new YException(YExceptionEnum.WAREHOUSE_NO_ERROR);
                    }
                    //查询期货现货合同
                    ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                            .eq("contract_no", warehouseInOutInfo.getContractNo()));
                    if (contractManagementInfo != null && "2".equals(contractManagementInfo.getGoodsType())) {
                        //客户生成收货信息
                        TranCarInfo tranCarInfo = new TranCarInfo();
                        tranCarInfo.setId(IdGenerator.generateUUID());
                        tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                        tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                        tranCarInfo.setTranCarNo(warehouseInOutInfo.getTranCarNo());
                        tranCarInfo.setLoadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        tranCarInfo.setLoadPoundImg(warehouseInOutInfo.getAddressUrl());
                        tranCarInfo.setConfirmFlag(StatusEnum.NOT_CONFIRM.getFlag());
                        // 期货销售出库统计
                        SalesDeliveryReport salesDeliveryReport = new SalesDeliveryReport();
                        salesDeliveryReport.setId(IdGenerator.generateUUID());
                        salesDeliveryReport.setCompId(warehouseBaseInfo.getCompId());
                        salesDeliveryReport.setContractNo(warehouseInOutInfo.getContractNo());
                        salesDeliveryReport.setGoodsName(warehouseInOutInfo.getGoodsName());
                        salesDeliveryReport.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
                        salesDeliveryReport.setPositionNumber(warehouseInOutInfo.getBinNumber());
                        salesDeliveryReport.setCarNo(warehouseInOutInfo.getCarNo());
                        salesDeliveryReport.setTranCarNo(warehouseInOutInfo.getTranCarNo());
                        salesDeliveryReport.setRetrievalDate(warehouseInOutInfo.getInOutDate());
                        salesDeliveryReport.setProtein(warehouseInOutDetail.getProtein());
                        salesDeliveryReport.setWaterContent(warehouseInOutDetail.getWaterContent());
                        salesDeliveryReport.setNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        salesDeliveryReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                        salesDeliveryReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                        salesDeliveryReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
                        if (saleOrder != null) {
                            salesDeliveryReport.setUnitPrice(saleOrder.getUnitPrice());
                            salesDeliveryReport.setInvoiceFee(saleOrder.getInvoiceFee());
                            //期货
                            if (saleOrder.getBasis() != null) {
                                salesDeliveryReport.setBasisPrice(saleOrder.getBasis());
                                BigDecimal unitPrice = new BigDecimal(Float.toString(salesDeliveryReport.getUnitPrice()));
                                BigDecimal basis = new BigDecimal(Float.toString(salesDeliveryReport.getBasisPrice()));
                                BigDecimal invoiceFee = new BigDecimal(Float.toString(salesDeliveryReport.getInvoiceFee()));
                                salesDeliveryReport.setSettlementPrice(unitPrice.add(basis).add(invoiceFee).floatValue());
                                tranCarInfo.setSettlementPrice(saleOrder.getUnitPrice() + saleOrder.getBasis() + saleOrder.getInvoiceFee());
                            }
                            salesDeliveryReport.setCustomerName(saleOrder.getBuyer());
                            salesDeliveryReport.setCollectionIngPayable(CalculationUtil.mulToFloat(salesDeliveryReport.getSettlementPrice(), salesDeliveryReport.getNetWeight()));
                            salesDeliveryReport.setCollectionEdPayable(0f);
                            salesDeliveryReport.setCollectionNotPayable(salesDeliveryReport.getCollectionIngPayable());
                            tranCarInfoService.insert(tranCarInfo);
                        }

                        // 客户确认
                        TranCarInfo tranCarInfo1 = tranCarInfoService.selectOne(new EntityWrapper<TranCarInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("car_no", warehouseInOutInfo.getCarNo())
                                .eq("delete_flag", "0"));
                        if (tranCarInfo1 != null && "3".equals(tranCarInfo1.getConfirmFlag())) {
                            salesDeliveryReport.setCustomerConfirmationStatusFlag("1");
                            salesDeliveryReport.setCustomerConfirmationStatus("是");
                            geTuiUtils.pushByCid("发货通知", "您的合同车辆：" + warehouseInOutInfo.getCarNo() + "已发出", saleOrder.getCommonId());
                            tesk(warehouseInOutInfo, "1");
                            UnimallMessage messageDO = new UnimallMessage();
                            messageDO.setAdminId(saleOrder.getCommonId());
                            messageDO.setCustomer(saleOrder.getCustomer());
                            messageDO.setOperation("发货通知");
                            messageDO.setResult("您的合同车辆：" + warehouseInOutInfo.getCarNo() + "已发出");
                            messageDO.setGmtUpdate(new java.util.Date());
                            messageDO.setGmtCreate(new Date());
                            messageDO.setTaskId(IdGenerator.generateUUID());
                            messageDO.setCompanyId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                            messageDO.setPath("XXXXX");
                            webSocket.sendOneMessage(messageDO);
                        } else {
                            salesDeliveryReport.setCustomerConfirmationStatusFlag("3");
                            salesDeliveryReport.setCustomerConfirmationStatus("否");
                        }
                        salesDeliveryReportService.insert(salesDeliveryReport);

                        boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(salesDeliveryReport.getWorkflowId());
                        // 不是退回的单子
                        if (isStartWorkflow) {
                            Workflow workflow = workflowService
                                    .findLatestWorkflowByBusinessCodeByApp(salesDeliveryReport.getCompId(), "SALE-RECEIPT-REPORT");
                            // 没配置审核流程，直接结束并处理信息
                            if (workflow == null) {
                                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                            }
                            // 开启审核流
                            else {

                                // 设置状态 已提交审核
                                salesDeliveryReport.setWorkflowId(workflow.getId());
                                salesDeliveryReportService.updateById(salesDeliveryReport);
                                workflowService.startInstance(workflow.getId(), salesDeliveryReport.getId());
                            }
                        }
                        // 退回的单子 再启用
                        else {

                            salesDeliveryReportService.updateById(salesDeliveryReport);
                            workflowService.activateInstance(salesDeliveryReport.getWorkflowId(), salesDeliveryReport.getId());
                        }
                    }
                }
            } else {
                //常用库入库
                if ("2".equals(warehouseInOutInfo.getInOutFlag()) && "1".equals(warehouseBaseInfo.getWarehouseType())) {
                    //常用库采购入库类型
                    if ("1".equals(warehouseInOutInfo.getInOutTypeKey())) {
                        //他运的采购合同
                        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("deliver_type", "2")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo != null) {
                            //现货采购入库报表
                            StockPurchaseReceiptReport stockPurchaseReceiptReport = new StockPurchaseReceiptReport();
                            stockPurchaseReceiptReport.setId(IdGenerator.generateUUID());
                            stockPurchaseReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            stockPurchaseReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockPurchaseReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                            stockPurchaseReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockPurchaseReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            stockPurchaseReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockPurchaseReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockPurchaseReceiptReport.setNetWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            stockPurchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                            stockPurchaseReceiptReport.setDeductionWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getDeductionWeight())));
                            stockPurchaseReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            stockPurchaseReceiptReport.setDeductionAmount(warehouseInOutInfo.getDeductionAmount());

                            if (contractManagementInfo.getUnitContractPrice() != null) {
                                BigDecimal cost = new BigDecimal(contractManagementInfo.getUnitContractPrice());
                                BigDecimal deductionAmount = new BigDecimal(warehouseInOutInfo.getDeductionAmount() != null ? warehouseInOutInfo.getDeductionAmount() : 0.0);
                                stockPurchaseReceiptReport.setSettlementPrice(cost.subtract(deductionAmount).doubleValue());
                                BigDecimal netWeight = new BigDecimal(warehouseInOutInfo.getNetWeight());
                                stockPurchaseReceiptReport.setAmountIngPayable(cost.subtract(deductionAmount).multiply(netWeight).doubleValue());
                            }
                            //随行就市
                            else {
                                BigDecimal cost = new BigDecimal(Float.toString(warehouseInOutInfo.getCost()));
                                BigDecimal deductionAmount = new BigDecimal(warehouseInOutInfo.getDeductionAmount() != null ? warehouseInOutInfo.getDeductionAmount() : 0.0);
                                stockPurchaseReceiptReport.setSettlementPrice(cost.subtract(deductionAmount).doubleValue());
                                BigDecimal netWeight = new BigDecimal(warehouseInOutInfo.getNetWeight());
                                stockPurchaseReceiptReport.setAmountIngPayable(cost.subtract(deductionAmount).multiply(netWeight).doubleValue());
                            }
                            stockPurchaseReceiptReport.setAmountEdPayable(0.0d);
                            stockPurchaseReceiptReport.setAmountNotPayable(stockPurchaseReceiptReport.getAmountIngPayable());
                            stockPurchaseReceiptReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                            stockPurchaseReceiptReport.setStatus(StatusEnum.FORM_REVIEWED.getName());

                            stockPurchaseReceiptReportService.insert(stockPurchaseReceiptReport);
                            boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(stockPurchaseReceiptReport.getWorkflowId());
                            // 不是退回的单子
                            if (isStartWorkflow) {
                                Workflow workflow = workflowService
                                        .findLatestWorkflowByBusinessCodeByApp(stockPurchaseReceiptReport.getCompId(), "STOCK-PROCUREMENT-RECEIPT-REPORT");
                                // 没配置审核流程，直接结束并处理信息
                                if (workflow == null) {
                                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                }
                                // 开启审核流
                                else {
                                    // 设置状态 已提交审核
                                    stockPurchaseReceiptReport.setWorkflowId(workflow.getId());
                                    stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                    workflowService.startInstance(workflow.getId(), stockPurchaseReceiptReport.getId());
                                }
                            }
                            // 退回的单子 再启用
                            else {
                                stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                workflowService.activateInstance(stockPurchaseReceiptReport.getWorkflowId(), stockPurchaseReceiptReport.getId());
                            }
                        }
                    }
                    //常用库移库入库类型
                    else if ("3".equals(warehouseInOutInfo.getInOutTypeKey())) {
                        InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                .eq("move_task_no", warehouseInOutInfo.getContractNo())
                                .eq("in_out_flag", "1")
                                .eq("delete_flag", "0"));
                        if (inOutWarehouseTask == null) {
                            throw new YException(YExceptionEnum.TASK_NO_NOT_EXSITS_ERROR);
                        } else {
                            //若移库的发货库为自动创建的临时库时
                            WarehouseBaseInfo warehouseBaseInfo1 = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                                    .eq("warehouse_name", inOutWarehouseTask.getWarehouseName())
                                    .eq("create_type", "1")
                                    .eq("warehouse_type", "2")
                                    .eq("delete_flag", "0"));
                            if (warehouseBaseInfo1 != null) {
                                //按入库重量结算
                                ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                        .eq("contract_no", warehouseBaseInfo1.getWarehouseName())
                                        .eq("settlement_weight_method", "2")
                                        .eq("deliver_type", "1")
                                        .eq("delete_flag", "0"));
//                                if (contractManagementInfo == null) {
//                                    throw new YException(YExceptionEnum.CONTRACT_NO_NOT_EXSITS_ERROR);
//                                }
                                if (contractManagementInfo != null) {
                                    //现货采购入库报表
                                    StockPurchaseReceiptReport stockPurchaseReceiptReport = new StockPurchaseReceiptReport();
                                    stockPurchaseReceiptReport.setId(IdGenerator.generateUUID());
                                    stockPurchaseReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                                    stockPurchaseReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                                    stockPurchaseReceiptReport.setContractNo(warehouseBaseInfo1.getWarehouseName());
                                    stockPurchaseReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                                    stockPurchaseReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                    stockPurchaseReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                                    stockPurchaseReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                                    stockPurchaseReceiptReport.setNetWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    stockPurchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                                    stockPurchaseReceiptReport.setDeductionWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getDeductionWeight())));
                                    stockPurchaseReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    if (contractManagementInfo.getUnitContractPrice() != null) {
                                        BigDecimal cost = new BigDecimal(contractManagementInfo.getUnitContractPrice());
                                        BigDecimal deductionAmount = new BigDecimal(warehouseInOutInfo.getDeductionAmount() != null ? warehouseInOutInfo.getDeductionAmount() : 0.0);
                                        stockPurchaseReceiptReport.setSettlementPrice(cost.subtract(deductionAmount).doubleValue());
                                        BigDecimal netWeight = new BigDecimal(warehouseInOutInfo.getNetWeight());
                                        stockPurchaseReceiptReport.setAmountIngPayable(cost.subtract(deductionAmount).multiply(netWeight).doubleValue());
                                    }
                                    //随行就市
                                    else {
                                        BigDecimal cost = new BigDecimal(warehouseInOutInfo.getCost());
                                        BigDecimal deductionAmount = new BigDecimal(warehouseInOutInfo.getDeductionAmount() != null ? warehouseInOutInfo.getDeductionAmount() : 0.0);
                                        stockPurchaseReceiptReport.setSettlementPrice(cost.subtract(deductionAmount).doubleValue());
                                        BigDecimal netWeight = new BigDecimal(warehouseInOutInfo.getNetWeight());
                                        stockPurchaseReceiptReport.setAmountIngPayable(cost.subtract(deductionAmount).multiply(netWeight).doubleValue());
                                    }
                                    stockPurchaseReceiptReport.setAmountEdPayable(0.0d);
                                    stockPurchaseReceiptReport.setAmountNotPayable(stockPurchaseReceiptReport.getAmountIngPayable());
                                    stockPurchaseReceiptReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                                    stockPurchaseReceiptReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
                                    stockPurchaseReceiptReportService.insert(stockPurchaseReceiptReport);
                                    boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(stockPurchaseReceiptReport.getWorkflowId());
                                    // 不是退回的单子
                                    if (isStartWorkflow) {
                                        Workflow workflow = workflowService
                                                .findLatestWorkflowByBusinessCodeByApp(stockPurchaseReceiptReport.getCompId(), "STOCK-PROCUREMENT-RECEIPT-REPORT");
                                        // 没配置审核流程，直接结束并处理信息
                                        if (workflow == null) {
                                            throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                        }
                                        // 开启审核流
                                        else {
                                            // 设置状态 已提交审核
                                            stockPurchaseReceiptReport.setWorkflowId(workflow.getId());
                                            stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                            workflowService.startInstance(workflow.getId(), stockPurchaseReceiptReport.getId());
                                        }
                                    }
                                    // 退回的单子 再启用
                                    else {
                                        stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                        workflowService.activateInstance(stockPurchaseReceiptReport.getWorkflowId(), stockPurchaseReceiptReport.getId());
                                    }
                                }
                            }
//                            //常用库之间的移库
//                            else{
//                                //查收货库
//                                InOutWarehouseTask inOutWarehouseTask1 = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
//                                        .eq("relevance_id", inOutWarehouseTask.getRelevanceId())
//                                        .eq("in_out_flag", "2")
//                                        .eq("delete_flag", "0"));
//                                //更新所在仓库收购库存
//                                ContractInventoryDistribution contractInventoryDistribution1=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
//                                        .eq("comp_id",inOutWarehouseTask1.getCompId()).eq("inventory_type","3").eq("warehouse",inOutWarehouseTask.getWarehouseName())
//                                        .eq("locus_warehouse",inOutWarehouseTask1.getWarehouseName())
//                                        .eq("goods_name",warehouseInOutInfo.getGoodsName()));
//                                if (contractInventoryDistribution1!=null){
//                                    contractInventoryDistribution1.setInventory(contractInventoryDistribution1.getInventory()+warehouseInOutInfo.getNetWeight());
//                                    contractInventoryDistributionService.updateById(contractInventoryDistribution1);
//                                }
//                                else {
//                                    ContractInventoryDistribution contractInventoryDistribution2=new ContractInventoryDistribution();
//                                    contractInventoryDistribution2.setId(IdGenerator.generateUUID());
//                                    contractInventoryDistribution2.setCompId(inOutWarehouseTask.getCompId());
//                                    //所属仓库  发货库
//                                    contractInventoryDistribution2.setWarehouse(inOutWarehouseTask.getWarehouseName());
//                                    contractInventoryDistribution2.setInventory(warehouseInOutInfo.getNetWeight());
//                                    //所在仓库  收货
//                                    contractInventoryDistribution2.setLocusWarehouse(inOutWarehouseTask1.getWarehouseName());
//                                    contractInventoryDistribution2.setGoodsName(warehouseInOutInfo.getGoodsName());
//                                    contractInventoryDistribution2.setInventoryType("3");
//                                    contractInventoryDistributionService.insert(contractInventoryDistribution2);
//
//                                }
//                            }
                        }
                        //入库时更新汽运报表卸车数据
                        TranSettlementReport tranSettlementReport = tranSettlementReportService.selectOne(new EntityWrapper<TranSettlementReport>()
                                .eq("car_id", warehouseInOutInfo.getCarId()));
                        if (tranSettlementReport!=null) {
                            tranSettlementReport.setUnloadingWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            tranSettlementReport.setUnloadingImg(warehouseInOutInfo.getAddressUrl());
                            //损耗
                            tranSettlementReport.setLossWeight(tranSettlementReport.getLoadingWeight() - tranSettlementReport.getUnloadingWeight());
                            //汽运类型
                            if (tranSettlementReport.getTranTypeKey().equals(NumberConstant.CONSTANT1)) {
                                //结算重量
                                if ("0".equals(tranSettlementReport.getManualFlag())) {
                                    //卸车不为空时，结算重量=装卸取小
                                    tranSettlementReport.setSettlementWeight(tranSettlementReport.getLoadingWeight() > tranSettlementReport.getUnloadingWeight() ? tranSettlementReport.getUnloadingWeight() : tranSettlementReport.getLoadingWeight());
                                }
                                if (tranSettlementReport.getTransportPrice()!=null) {
                                    //扣款
                                    if (tranSettlementReport.getLossWeight() <= (tranSettlementReport.getLoadingWeight() / 1000)) {
                                        tranSettlementReport.setDeductionAmount("0");
                                        //应付=单价x结算重量-扣款
                                        tranSettlementReport.setAmountIngPayable(tranSettlementReport.getTransportPrice() * tranSettlementReport.getSettlementWeight());
                                    } else {
                                        tranSettlementReport.setDeductionAmount(String.format("%.2f", (Float.valueOf(tranSettlementReport.getLoadingWeight() - tranSettlementReport.getUnloadingWeight()) - (tranSettlementReport.getLoadingWeight() / 1000)) * Float.valueOf(tranSettlementReport.getTransportPrice())));
                                        //应付=单价x结算重量-扣款
                                        tranSettlementReport.setAmountIngPayable(tranSettlementReport.getTransportPrice() * tranSettlementReport.getSettlementWeight() - Float.valueOf(tranSettlementReport.getDeductionAmount()));
                                    }
                                }
                            }
                            tranSettlementReportService.updateById(tranSettlementReport);
                        }
                    }
                    //常用库退库入库类型
                    else if ("退库".equals(warehouseInOutInfo.getInOutType())) {
                        //他运的销售合同
                        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("deliver_type", "2")
                                .eq("contract_type", "1")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo != null) {
                            //现货销售出库报表
                            StockSaleReceiptReport stockSaleReceiptReport = new StockSaleReceiptReport();
                            stockSaleReceiptReport.setId(IdGenerator.generateUUID());
                            stockSaleReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            stockSaleReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockSaleReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                            stockSaleReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            stockSaleReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockSaleReceiptReport.setNetWeight(-warehouseInOutInfo.getNetWeight());
                            stockSaleReceiptReport.setSettlementPrice(contractManagementInfo.getUnitContractPrice());
                            stockSaleReceiptReport.setReturnDate(warehouseInOutInfo.getInOutDate());
                            stockSaleReceiptReport.setAmountIngReceivable(-warehouseInOutInfo.getNetWeight() * contractManagementInfo.getUnitContractPrice());
                            stockSaleReceiptReport.setSettlementWeight(-warehouseInOutInfo.getNetWeight());
                            stockSaleReceiptReport.setReturnFlag("1");
                            stockSaleReceiptReport.setStatusFlag(StatusEnum.TO_BE_RECEIVED.getFlag());
                            stockSaleReceiptReport.setStatus(StatusEnum.TO_BE_RECEIVED.getName());
                            stockSaleReceiptReport.setSettlementWeight(stockSaleReceiptReport.getNetWeight());
                            CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId()));
                            if (costManagementInfo != null) {
                                stockSaleReceiptReport.setCost(costManagementInfo.getCost());

                            }
                            stockSaleReceiptReportService.insert(stockSaleReceiptReport);
                        }
                        //自运的销售合同
                        ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("contract_type", "1")
                                .eq("deliver_type", "1")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo1 != null) {
                            //现货销售出库报表
                            StockSaleReceiptReport stockSaleReceiptReport = new StockSaleReceiptReport();
                            stockSaleReceiptReport.setId(IdGenerator.generateUUID());
                            stockSaleReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockSaleReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            stockSaleReceiptReport.setProcessNo("退库");
                            stockSaleReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                            stockSaleReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            stockSaleReceiptReport.setTranCarNo(warehouseInOutInfo.getTranCarNo());
                            stockSaleReceiptReport.setCaseNo(warehouseInOutInfo.getBoxNo() + "," + warehouseInOutInfo.getBoxNoOther());
                            stockSaleReceiptReport.setTitleNo(warehouseInOutInfo.getTitleNo());
                            stockSaleReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockSaleReceiptReport.setNetWeight(-warehouseInOutInfo.getNetWeight());
                            stockSaleReceiptReport.setReturnDate(warehouseInOutInfo.getInOutDate());
                            stockSaleReceiptReport.setAmountIngReceivable(-warehouseInOutInfo.getNetWeight() * contractManagementInfo1.getUnitContractPrice());
                            stockSaleReceiptReport.setSettlementWeight(-warehouseInOutInfo.getNetWeight());
                            stockSaleReceiptReport.setReturnFlag("1");
                            stockSaleReceiptReport.setStatusFlag(StatusEnum.TO_BE_RECEIVED.getFlag());
                            stockSaleReceiptReport.setStatus(StatusEnum.TO_BE_RECEIVED.getName());
                            stockSaleReceiptReport.setSettlementWeight(stockSaleReceiptReport.getNetWeight());
                            CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId()));
                            if (costManagementInfo != null) {
                                stockSaleReceiptReport.setCost(costManagementInfo.getCost());

                            }
                            stockSaleReceiptReportService.insert(stockSaleReceiptReport);
                        }
                    }
                    Wrapper wrapper = new EntityWrapper<TranCarInfo>()
                            .eq("contract_no", warehouseInOutInfo.getContractNo())
                            .eq("car_no", warehouseInOutInfo.getCarNo())
                            .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                            .eq("tran_car_no", warehouseInOutInfo.getTranCarNo());
                    TranCarInfo tranCarInfo = tranCarInfoService.selectOne(wrapper);
                    if (tranCarInfo != null) {
                        //将到货数据同步到派车表
                        tranCarInfo.setUnloadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        if (warehouseInOutInfo.getAddressUrl() != null) {
                            tranCarInfo.setUnloadPoundImg(warehouseInOutInfo.getAddressUrl());
                        }
                        tranCarInfo.setUnloadingDate(warehouseInOutInfo.getInOutDate());
//                        if ("2".equals(tranCarInfo.getSubmit())) {
//                            throw new YException(YExceptionEnum.CARNO_SUBMITTED_ERROR);
//                        } else {
                        tranCarInfo.setSubmit("2");
                        tranCarInfo.setStatusFlag(StatusEnum.DELIVERED.getFlag());
                        tranCarInfo.setStatus(StatusEnum.DELIVERED.getName());
//                        }
                        tranCarInfoService.updateById(tranCarInfo);
                    }
                    //更新库存量
                    float original = 0f;
                    //判断是否有库
                    if (warehouseBaseInfo != null) {
                        //  查询库位
                        WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectById(warehouseInOutInfo.getPositionId());
                        if (warehousePositionInfo != null) {
                            // 查询货物库存量
                            WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                                    .eq("position_id", warehouseInOutInfo.getPositionId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName())
                                    .eq("delete_flag", "0"));
                            // 判断是否有货
                            if (warehousePositionStorageInfo != null) {
                                original = Float.valueOf(String.valueOf(warehousePositionStorageInfo.getStorage()));
                                // 更新库存量
                                warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
                            }
                            // 没有货
                            else {
                                WarehousePositionStorageInfo warehousePositionStorageInfo1 = new WarehousePositionStorageInfo();
                                warehousePositionStorageInfo1.setId(IdGenerator.generateUUID());
                                warehousePositionStorageInfo1.setPositionId(warehouseInOutInfo.getPositionId());
                                warehousePositionStorageInfo1.setBinNumber(warehouseInOutInfo.getBinNumber());
                                warehousePositionStorageInfo1.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
                                warehousePositionStorageInfo1.setGoodsName(warehouseInOutInfo.getGoodsName());
                                warehousePositionStorageInfo1.setStorage(warehouseInOutInfo.getNetWeight());
                                warehousePositionStorageInfoService.insert(warehousePositionStorageInfo1);
                            }
                        }
                    }

                    // 生成加权成本数据
                    WeightedDetails weightedDetails = new WeightedDetails();
                    weightedDetails.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                    weightedDetails.setId(IdGenerator.generateUUID());
                    weightedDetails.setWarehouseId(warehouseInOutInfo.getBaseId());
                    weightedDetails.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                    weightedDetails.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
                    weightedDetails.setGoodsName(warehouseInOutInfo.getGoodsName());
                    weightedDetails.setGrainType(warehouseInOutInfo.getType());
                    weightedDetails.setInTypeKey(warehouseInOutInfo.getInOutTypeKey());
                    weightedDetails.setInType(warehouseInOutInfo.getInOutType());
                    weightedDetails.setNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                    weightedDetails.setPureWeight(warehouseInOutInfo.getPureWeight());
                    weightedDetails.setUnitPrice(warehouseInOutInfo.getCost());
                    weightedDetails.setDeductionAmount(warehouseInOutInfo.getDeductionAmount());
                    weightedDetails.setFreight(warehouseInOutInfo.getFreight());
                    weightedDetails.setOriginalStock(original);
                    // 查询入库全加权成本
                    List<WeightedDetails> weightedDetailsList = weightedDetailsService.selectList(new EntityWrapper<WeightedDetails>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                            .eq("goods_name", warehouseInOutInfo.getGoodsName()).orderBy("update_date", false));

                    // 计算新加权成本
                    Double newCost = 0d;
                    if (CollectionUtils.isEmpty(weightedDetailsList)) {
                        if ("干粮".equals(warehouseInOutInfo.getType())) {
                            newCost = ((warehouseInOutInfo.getCost() / 1.09 + warehouseInOutInfo.getFreight()) * Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()))) / (Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())) + original);

                        } else {
                            newCost = ((warehouseInOutInfo.getCost() / 1.09 + warehouseInOutInfo.getFreight()) * Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()))) / (warehouseInOutInfo.getPureWeight() + original);

                        }
                        weightedDetails.setCostBefore(Float.valueOf(String.valueOf(newCost)));
                        weightedDetails.setCostAfter(newCost);
                    } else {
                        weightedDetails.setCostBefore(weightedDetailsList.get(0).getCostBefore());
                        if ("干粮".equals(warehouseInOutInfo.getType())) {
                            newCost = ((warehouseInOutInfo.getCost() / 1.09 + warehouseInOutInfo.getFreight()) * Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())) + original * weightedDetails.getCostBefore()) / (Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())) + original);

                        } else {
                            newCost = ((warehouseInOutInfo.getCost() / 1.09 + warehouseInOutInfo.getFreight()) * Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())) + original * weightedDetails.getCostBefore()) / (warehouseInOutInfo.getPureWeight() + original);

                        }
                        weightedDetails.setCostAfter(newCost);
                    }

                    weightedDetails.setCostAfter(newCost);
                    if (CollectionUtils.isEmpty(weightedDetailsList)) {
                        weightedDetails.setCostBefore(Float.valueOf(String.valueOf(newCost)));
                    } else {
                        weightedDetails.setCostBefore(weightedDetailsList.get(0).getCostBefore());
                    }
                    weightedDetailsService.insert(weightedDetails);
                    // 修改成本信息表
                    CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", weightedDetails.getWarehouseId())
                            .eq("comp_id", weightedDetails.getCompId())
                            .eq("goods_name", weightedDetails.getGoodsName()));
//                    List<WeightedDetails> weightedDetailsLists = weightedDetailsService.selectList(new EntityWrapper<WeightedDetails>().eq("warehouse_id", warehouseInOutInfo.getWarehouseName())
//                            .eq("goods_name_key", warehouseInOutInfo.getGoodsNameKey()).orderBy("update_date", false));
                    Double net = 0d;
//                    for (int i = 0; i < weightedDetailsLists.size(); i++) {
//                        net = net + weightedDetailsLists.get(i).getNetWeight();
//                    }
                    List<WarehousePositionInfo> warehousePositionInfos = warehousePositionInfoService.selectList(new EntityWrapper<WarehousePositionInfo>()
                            .eq("base_id", warehouseInOutInfo.getBaseId()));
                    if (!CollectionUtils.isEmpty(warehousePositionInfos)) {
                        for (int i = 0; i < warehousePositionInfos.size(); i++) {
                            List<WarehousePositionStorageInfo> warehousePositionStorageInfos = warehousePositionStorageInfoService.selectList(new EntityWrapper<WarehousePositionStorageInfo>()
                                    .eq("position_id", warehousePositionInfos.get(i).getId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName()));
                            for (int j = 0; j < warehousePositionStorageInfos.size(); j++) {
                                net = net + warehousePositionStorageInfos.get(j).getStorage();
                            }
                        }
                    }
                    if (costManagementInfo == null) {
                        CostManagementInfo costManagementInfo1 = new CostManagementInfo();
                        costManagementInfo1.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                        costManagementInfo1.setId(IdGenerator.generateUUID());
                        costManagementInfo1.setWarehouseId(weightedDetails.getWarehouseId());
                        costManagementInfo1.setWarehouseName(weightedDetails.getWarehouseName());
                        costManagementInfo1.setGoodsNameKey(weightedDetails.getGoodsNameKey());
                        costManagementInfo1.setGoodsName(weightedDetails.getGoodsName());
                        costManagementInfo1.setWarehouseType(warehouseBaseInfo.getWarehouseType());

                        costManagementInfo1.setStorage(net);
                        costManagementInfo1.setCost(weightedDetails.getCostAfter());
                        costManagementInfoService.insert(costManagementInfo1);
                    } else {
                        costManagementInfo.setCost(weightedDetails.getCostAfter());
                        costManagementInfo.setStorage(net);
                        costManagementInfoService.updateById(costManagementInfo);
                    }
                }
                //临时库入库
                else if ("2".equals(warehouseInOutInfo.getInOutFlag()) && "2".equals(warehouseBaseInfo.getWarehouseType())) {
                    //更新库存量
                    float original = 0f;
                    //判断是否有库
                    if (warehouseBaseInfo != null) {
                        //  查询库位
                        WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectById(warehouseInOutInfo.getPositionId());
                        if (warehousePositionInfo != null) {
                            // 查询货物库存量
                            WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                                    .eq("position_id", warehouseInOutInfo.getPositionId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName())
                                    .eq("delete_flag", "0"));
                            // 判断是否有货
                            if (warehousePositionStorageInfo != null) {
                                original = Float.valueOf(String.valueOf(warehousePositionStorageInfo.getStorage()));
                                // 更新库存量
                                warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
                            }
                            // 没有货
                            else {
                                WarehousePositionStorageInfo warehousePositionStorageInfo1 = new WarehousePositionStorageInfo();
                                warehousePositionStorageInfo1.setId(IdGenerator.generateUUID());
                                warehousePositionStorageInfo1.setPositionId(warehouseInOutInfo.getPositionId());
                                warehousePositionStorageInfo1.setBinNumber(warehouseInOutInfo.getBinNumber());
                                warehousePositionStorageInfo1.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
                                warehousePositionStorageInfo1.setGoodsName(warehouseInOutInfo.getGoodsName());
                                warehousePositionStorageInfo1.setStorage(warehouseInOutInfo.getNetWeight());
                                warehousePositionStorageInfoService.insert(warehousePositionStorageInfo1);
                            }
                        }
                    }
                }
                //常用库出库
                else if ("1".equals(warehouseInOutInfo.getInOutFlag()) && "1".equals(warehouseBaseInfo.getWarehouseType())) {
                    //常用库销售出库类型
                    if ("1".equals(warehouseInOutInfo.getInOutTypeKey())) {
                        //查出库任务关联的货源
                        InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                .eq("in_out_task_no", warehouseInOutInfo.getInOutTaskNo()));
                        List<SourceRelationInfo> sourceRelationInfoList =sourceRelationInfoService.selectList(new EntityWrapper<SourceRelationInfo>()
                                .eq("task_id", inOutWarehouseTask.getId())
                                .eq("delete_flag", "0"));
                        if (!CollectionUtils.isEmpty(sourceRelationInfoList)){
                            for (SourceRelationInfo sourceRelationInfo:sourceRelationInfoList){
                                //查货源关联的入库单
                                WarehousingOrder warehousingOrder=warehousingOrderService.selectById(sourceRelationInfo.getSourceId());
                                if ("采购入库".equals(warehousingOrder.getInType())){
                                    //更新采购合同库存销售量
                                    ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                                            .eq("comp_id",warehousingOrder.getCompId()).eq("inventory_type","1").eq("contract_no",warehousingOrder.getContractNo())
                                            .eq("warehouse",warehouseInOutInfo.getWarehouseName()));
                                    if (contractInventoryDistribution!=null){
                                        contractInventoryDistribution.setInStorage(contractInventoryDistribution.getInStorage()-warehouseInOutInfo.getNetWeight()*sourceRelationInfo.getProportion());
                                        contractInventoryDistributionService.updateById(contractInventoryDistribution);
                                    }
                                }
                                else if ("收购入库".equals(warehousingOrder.getInType())){
                                    //查收购合同原始货源仓库
                                    InOutWarehouseTask inOutWarehouseTask1=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                            .eq("comp_id", warehousingOrder.getCompId())
                                            .eq("contract_no", warehousingOrder.getContractNo())
                                            .eq("delete_flag", "0"));
                                    //更新收货库库点库存剩余量 (所在仓库为出货库、所属仓库为原始货源仓库、货名一致)
                                    ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                                            .eq("comp_id",warehousingOrder.getCompId()).eq("inventory_type","3").eq("locus_warehouse",warehouseInOutInfo.getWarehouseName())
                                            .eq("warehouse",inOutWarehouseTask1.getWarehouseName())
                                            .eq("goods_name",warehouseInOutInfo.getGoodsName()));
                                    if (contractInventoryDistribution!=null){
                                        contractInventoryDistribution.setInventory(contractInventoryDistribution.getInventory()-warehouseInOutInfo.getNetWeight()*sourceRelationInfo.getProportion());
                                        contractInventoryDistributionService.updateById(contractInventoryDistribution);
                                    }
                                }
                            }

                        }
                        //他运的销售合同
                        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("deliver_type", "2")
                                .eq("contract_type", "1")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo != null) {
                            if (contractManagementInfo.getUnitContractPrice() == null) {
                                contractManagementInfo.setUnitContractPrice(0d);
                            }
                            //现货销售出库报表
                            StockSaleReceiptReport stockSaleReceiptReport = new StockSaleReceiptReport();
                            stockSaleReceiptReport.setId(IdGenerator.generateUUID());
                            stockSaleReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockSaleReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            TranTaskInfo tranTaskInfo = tranTaskInfoService.selectOne(new EntityWrapper<TranTaskInfo>()
                                    .eq("contract_no", contractManagementInfo.getContractNo())
                                    .eq("comp_id", contractManagementInfo.getCompId()));
                            if (tranTaskInfo != null) {
                                TranProcessInfo tranProcessInfo = tranProcessInfoService.selectOne(new EntityWrapper<TranProcessInfo>()
                                        .eq("info_id", tranTaskInfo.getId()));
                                if (tranProcessInfo != null) {
                                    if (tranProcessInfo.getThreeTranType() == null) {
                                        tranProcessInfo.setThreeTranType(warehouseInOutInfo.getOutType());

                                    } else if (!tranProcessInfo.getThreeTranType().contains(warehouseInOutInfo.getOutType())) {
                                        tranProcessInfo.setThreeTranType(tranProcessInfo.getThreeTranType() + "," + warehouseInOutInfo.getOutType());
                                    }
                                    tranProcessInfoService.updateById(tranProcessInfo);
                                    stockSaleReceiptReport.setProcessId(tranProcessInfo.getId());
                                    TranCarInfo tranCarInfo = new TranCarInfo();
                                    tranCarInfo.setId(IdGenerator.generateUUID());
                                    tranCarInfo.setProcessId(tranProcessInfo.getId());
                                    tranCarInfo.setCompId(tranTaskInfo.getCompId());
                                    tranCarInfo.setInfoId(tranProcessInfo.getInfoId());
                                    tranCarInfo.setTranType("4");
                                    tranCarInfo.setSubmit("1");
                                    tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                                    tranCarInfo.setLoadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                                    tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                                    if ("汽运".equals(warehouseInOutInfo.getOutType())) {
                                        tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                                        tranCarInfo.setCaseNo(warehouseInOutInfo.getBoxNo());
                                        tranCarInfo.setThreeTranType("汽运");
                                        tranCarInfo.setTitleNo(warehouseInOutInfo.getTitleNo());
                                        tranCarInfo.setCaseNoOther(warehouseInOutInfo.getBoxNoOther());
                                        tranCarInfo.setTitleNoOther(warehouseInOutInfo.getTitleNoOther());
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setCaseNo(warehouseInOutInfo.getBoxNo());
                                        stockSaleReceiptReport.setTitleNo(warehouseInOutInfo.getTitleNo());
                                        stockSaleReceiptReport.setCaseNoOther(warehouseInOutInfo.getBoxNoOther());
                                        stockSaleReceiptReport.setTitleNoOther(warehouseInOutInfo.getTitleNoOther());
                                    } else if ("火运".equals(warehouseInOutInfo.getOutType())) {
                                        tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                                        tranCarInfo.setBoxNo(warehouseInOutInfo.getWingNumber());
                                        tranCarInfo.setThreeTranType("火运");
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setBoxNo(warehouseInOutInfo.getWingNumber());
                                    } else if ("散船".equals(warehouseInOutInfo.getOutType())) {
                                        tranCarInfo.setShipName(warehouseInOutInfo.getShipName());
                                        tranCarInfo.setShipNo(warehouseInOutInfo.getShipNumber());
                                        tranCarInfo.setThreeTranType("散船");
                                        tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setShipName(warehouseInOutInfo.getShipName());
                                        stockSaleReceiptReport.setShipNo(warehouseInOutInfo.getShipNumber());
                                    } else if ("集装箱船".equals(warehouseInOutInfo.getOutType())) {
                                        tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                                        tranCarInfo.setCaseNo(warehouseInOutInfo.getBoxNo());
                                        tranCarInfo.setTitleNo(warehouseInOutInfo.getTitleNo());
                                        tranCarInfo.setThreeTranType("集装箱船");
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setCaseNoOther(warehouseInOutInfo.getBoxNoOther());
                                        stockSaleReceiptReport.setTitleNoOther(warehouseInOutInfo.getTitleNoOther());
                                        stockSaleReceiptReport.setCaseNo(warehouseInOutInfo.getBoxNo());
                                        stockSaleReceiptReport.setTitleNo(warehouseInOutInfo.getTitleNo());
                                    }
                                    tranCarInfoService.insert(tranCarInfo);
                                }
                            }
                            stockSaleReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                            stockSaleReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockSaleReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockSaleReceiptReport.setNetWeight(warehouseInOutInfo.getNetWeight());
                            stockSaleReceiptReport.setDeliveryDate(warehouseInOutInfo.getInOutDate());
                            //按出库重量结算时
                            if ("1".equals(contractManagementInfo.getSettlementWeightMethod())) {
                                stockSaleReceiptReport.setSettlementWeight(warehouseInOutInfo.getNetWeight());
                            }
                            //定价销售
                            if (contractManagementInfo.getUnitContractPrice() != null) {
                                stockSaleReceiptReport.setSettlementPrice(contractManagementInfo.getUnitContractPrice());
                                stockSaleReceiptReport.setAmountIngReceivable(warehouseInOutInfo.getNetWeight() *
                                        (contractManagementInfo.getUnitContractPrice()));
                                stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                            }
                            stockSaleReceiptReport.setStatusFlag(StatusEnum.TO_BE_RECEIVED.getFlag());
                            stockSaleReceiptReport.setStatus(StatusEnum.TO_BE_RECEIVED.getName());
                            stockSaleReceiptReport.setSettlementWeight(stockSaleReceiptReport.getNetWeight());
                            CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId()));
                            if (costManagementInfo != null) {
                                stockSaleReceiptReport.setCost(costManagementInfo.getCost());

                            }
                            stockSaleReceiptReportService.insert(stockSaleReceiptReport);
                        }
                        //自运的销售合同
                        ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("deliver_type", "1")
                                .eq("contract_type", "1")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo1 != null) {
                            //现货销售出库报表
                            StockSaleReceiptReport stockSaleReceiptReport = new StockSaleReceiptReport();
                            stockSaleReceiptReport.setId(IdGenerator.generateUUID());
                            stockSaleReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockSaleReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            TranTaskInfo tranTaskInfo = tranTaskInfoService.selectOne(new EntityWrapper<TranTaskInfo>()
                                    .eq("contract_no", contractManagementInfo1.getContractNo())
                                    .eq("comp_id", contractManagementInfo1.getCompId()));
                            if (tranTaskInfo != null) {
                                TranProcessInfo tranProcessInfo = tranProcessInfoService.selectOne(new EntityWrapper<TranProcessInfo>()
                                        .eq("info_id", tranTaskInfo.getId()));
                                if (tranProcessInfo != null) {
                                    stockSaleReceiptReport.setProcessId(tranProcessInfo.getId());
                                    stockSaleReceiptReport.setProcessNo(tranProcessInfo.getProcessNo());
                                    if ("汽运".equals(warehouseInOutInfo.getOutType())) {
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setTranCarNo(warehouseInOutInfo.getTranCarNo());
                                        stockSaleReceiptReport.setCaseNo(warehouseInOutInfo.getBoxNo());
                                        stockSaleReceiptReport.setTitleNo(warehouseInOutInfo.getTitleNo());
                                        stockSaleReceiptReport.setCaseNoOther(warehouseInOutInfo.getBoxNoOther());
                                        stockSaleReceiptReport.setTitleNoOther(warehouseInOutInfo.getTitleNoOther());
                                    } else if ("火运".equals(warehouseInOutInfo.getOutType())) {
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setBoxNo(warehouseInOutInfo.getWingNumber());
                                    } else if ("散船".equals(warehouseInOutInfo.getOutType())) {
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setShipName(warehouseInOutInfo.getShipName());
                                        stockSaleReceiptReport.setShipNo(warehouseInOutInfo.getShipNumber());
                                    } else if ("集装箱船".equals(warehouseInOutInfo.getOutType())) {
                                        stockSaleReceiptReport.setCaseNo(warehouseInOutInfo.getBoxNo());
                                        stockSaleReceiptReport.setCaseNoOther(warehouseInOutInfo.getBoxNoOther());
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setTitleNoOther(warehouseInOutInfo.getTitleNoOther());
                                        stockSaleReceiptReport.setTitleNo(warehouseInOutInfo.getTitleNo());
                                    }
                                    //自运出库时手动加的车
                                    if ("1".equals(warehouseInOutInfo.getSelfLoading())) {
                                        List<TranCarInfo> tranCarInfoList = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                                                .eq("contract_no", contractManagementInfo1.getContractNo()).eq("tran_type", "1"));
                                        TranCarInfo tranCarInfo = new TranCarInfo();
                                        tranCarInfo.setProcessId(tranProcessInfo.getId());
                                        tranCarInfo.setTranPrice(String.valueOf(tranProcessInfo.getTranPrice() != null ? tranProcessInfo.getTranPrice() : 0f));
                                        tranCarInfo.setInfoId(tranTaskInfo.getId());
                                        tranCarInfo.setCompId(warehouseBaseInfo.getCompId());
                                        tranCarInfo.setTranType("1");
                                        tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                                        String tranCarNo = "";
                                        if ((tranCarInfoList.size() + 1) < 10) {
                                            tranCarNo = "C00" + (tranCarInfoList.size() + 1);
                                        } else if (tranCarInfoList.size() + 1 < 100) {
                                            tranCarNo = "C0" + (tranCarInfoList.size() + 1);
                                        } else {
                                            tranCarNo = "C" + (tranCarInfoList.size() + 1);
                                        }
                                        tranCarInfo.setTranCarNo(tranCarNo);
                                        tranCarInfo.setId(IdGenerator.generateUUID());
                                        tranCarInfo.setContractNo(contractManagementInfo1.getContractNo());
                                        tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                                        tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                                        warehouseInOutInfo.setCarId(tranCarInfo.getId());
                                        warehouseInOutInfo.setTranCarNo(tranCarNo);
                                        stockSaleReceiptReport.setTranCarNo(tranCarNo);
                                        warehouseInOutInfoService.updateById(warehouseInOutInfo);
                                        tranCarInfoService.insert(tranCarInfo);
                                    }
                                    //生成汽运报表
                                    TranSettlementReport tranSettlementReport = new TranSettlementReport();
                                    tranSettlementReport.setCompId(warehouseBaseInfo.getCompId());
                                    tranSettlementReport.setCarId(warehouseInOutInfo.getCarId());
                                    tranSettlementReport.setId(IdGenerator.generateUUID());
                                    if ("汽运".equals(warehouseInOutInfo.getOutType())) {
                                        tranSettlementReport.setTranType("汽运");
                                        tranSettlementReport.setTranTypeKey("1");
                                    } else if ("火运".equals(warehouseInOutInfo.getOutType())) {
                                        tranSettlementReport.setTranType("火运");
                                        tranSettlementReport.setTranTypeKey("2");
                                    } else {
                                        tranSettlementReport.setTranType("船运");
                                        tranSettlementReport.setTranTypeKey("3");
                                    }
                                    tranSettlementReport.setContractNo(warehouseInOutInfo.getContractNo());
                                    tranSettlementReport.setCarNo(warehouseInOutInfo.getCarNo());
                                    tranSettlementReport.setSettlementWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    //运输单价不为空
                                    if (tranProcessInfo.getTranPrice()!=null){
                                        //应付
                                        tranSettlementReport.setAmountIngPayable(Float.valueOf(tranProcessInfo.getTranPrice()) * tranSettlementReport.getSettlementWeight());
                                        //未付
                                        tranSettlementReport.setAmountNotPayable(Float.valueOf(tranProcessInfo.getTranPrice()) * tranSettlementReport.getSettlementWeight());
                                        tranSettlementReport.setTransportPrice(Float.valueOf(tranProcessInfo.getTranPrice()));
                                    }
                                    tranSettlementReport.setLoadingImg(warehouseInOutInfo.getAddressUrl());
                                    tranSettlementReport.setLoadingWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    tranSettlementReportService.insert(tranSettlementReport);
                                    boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(tranSettlementReport.getWorkflowId());
                                    // 不是退回的单子
                                    if (isStartWorkflow) {
                                        Workflow workflow = workflowService
                                                .findLatestWorkflowByBusinessCodeByApp(tranSettlementReport.getCompId(), "TRANSPORTATION-SETTLEMENT-REPORT");
                                        // 没配置审核流程，直接结束并处理信息
                                        if (workflow == null) {
                                            throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                        }
                                        // 开启审核流
                                        else {

                                            // 设置状态 已提交审核
                                            tranSettlementReport.setWorkflowId(workflow.getId());
                                            tranSettlementReportService.updateById(tranSettlementReport);
                                            workflowService.startInstance(workflow.getId(), tranSettlementReport.getId());
                                        }
                                    }
                                    // 退回的单子 再启用
                                    else {

                                        tranSettlementReportService.updateById(tranSettlementReport);
                                        workflowService.activateInstance(tranSettlementReport.getWorkflowId(), tranSettlementReport.getId());
                                    }
                                }
                            } else {
                                throw new YException(YExceptionEnum.TRANTASK_NOT_CREATED_ERROR);
                            }
                            stockSaleReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                            stockSaleReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockSaleReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockSaleReceiptReport.setNetWeight(warehouseInOutInfo.getNetWeight());
                            stockSaleReceiptReport.setDeliveryDate(warehouseInOutInfo.getInOutDate());
                            stockSaleReceiptReport.setSettlementWeight(warehouseInOutInfo.getNetWeight());
                            //按出库重量结算时
                            if ("1".equals(contractManagementInfo1.getSettlementWeightMethod())) {
                                stockSaleReceiptReport.setSettlementWeight(warehouseInOutInfo.getNetWeight());
                                //定价销售
                                if (contractManagementInfo1.getUnitContractPrice() != null) {
                                    stockSaleReceiptReport.setSettlementPrice(contractManagementInfo1.getUnitContractPrice());
                                    stockSaleReceiptReport.setAmountIngReceivable(warehouseInOutInfo.getNetWeight() *
                                            (contractManagementInfo1.getUnitContractPrice()));
                                    stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                    stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                }
                            }
                            stockSaleReceiptReport.setStatusFlag(StatusEnum.TO_BE_RECEIVED.getFlag());
                            stockSaleReceiptReport.setStatus(StatusEnum.TO_BE_RECEIVED.getName());
                            stockSaleReceiptReport.setSettlementWeight(stockSaleReceiptReport.getNetWeight());
                            CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId()));
                            if (costManagementInfo != null) {
                                stockSaleReceiptReport.setCost(costManagementInfo.getCost());

                            }
                            stockSaleReceiptReportService.insert(stockSaleReceiptReport);
                        }
                    }
                    //常用库移库出库类型
                    if ("移库出库".equals(warehouseInOutInfo.getInOutType())) {
//                        //更新合同移库库存
//                        ContractInventoryDistribution contractInventoryDistribution1=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
//                                .eq("comp_id",warehouseBaseInfo.getCompId()).eq("inventory_type","1").eq("contract_no",warehouseInOutInfo.getContractNo())
//                                .eq("warehouse",warehouseInOutInfo.getWarehouseName()));
//                        if (contractInventoryDistribution1!=null){
//                            contractInventoryDistribution1.setRemoveStorage(contractInventoryDistribution1.getRemoveStorage()+warehouseInOutInfo.getNetWeight());
//                            contractInventoryDistributionService.updateById(contractInventoryDistribution1);
//                        }
                        InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                .eq("move_task_no", warehouseInOutInfo.getContractNo())
                                .eq("in_out_flag", "1")
                                .eq("delete_flag", "0"));
                        if (inOutWarehouseTask != null) {
//                            //更新所属仓库收购库存
//                            ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
//                                    .eq("comp_id",inOutWarehouseTask.getCompId()).eq("inventory_type","3").eq("warehouse",inOutWarehouseTask.getWarehouseName())
//                                    .eq("locus_warehouse",inOutWarehouseTask.getWarehouseName())
//                                    .eq("goods_name",warehouseInOutInfo.getGoodsName()));
//                            if (contractInventoryDistribution!=null){
//                                contractInventoryDistribution.setInventory(contractInventoryDistribution.getInventory()-warehouseInOutInfo.getNetWeight());
//                                contractInventoryDistributionService.updateById(contractInventoryDistribution);
//                            }
                            //自运出库时手动加的车
                            if ("1".equals(warehouseInOutInfo.getSelfLoading())) {
                                List<TranCarInfo> tranCarInfoList = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                                        .eq("contract_no", warehouseInOutInfo.getContractNo()).eq("tran_type", "1")
                                        .orderBy("create_date", false));
                                TranCarInfo tranCarInfo = new TranCarInfo();
                                TranTaskInfo tranTaskInfo = tranTaskInfoService.selectOne(new EntityWrapper<TranTaskInfo>()
                                        .eq("comp_id", warehouseBaseInfo.getCompId())
                                        .eq("contract_no", warehouseInOutInfo.getContractNo()));
                                if (tranTaskInfo != null) {
                                    TranProcessInfo tranProcessInfo = tranProcessInfoService.selectOne(new EntityWrapper<TranProcessInfo>()
                                            .eq("info_id", tranTaskInfo.getId()));
                                    tranCarInfo.setProcessId(tranProcessInfo.getId());
                                    tranCarInfo.setInfoId(tranTaskInfo.getId());
                                    warehouseInOutInfo.setFreight(tranProcessInfo.getTranPrice());
                                    tranCarInfo.setTranPrice(String.valueOf(tranProcessInfo.getTranPrice() != null ? tranProcessInfo.getTranPrice() : 0f));
                                } else {
                                    throw new YException(YExceptionEnum.TRANTASK_NOT_CREATED_ERROR);
                                }
                                //出库时打入成本
                                CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                                        .eq("goods_name", warehouseInOutInfo.getGoodsName()));
                                if (costManagementInfo != null) {
                                    tranCarInfo.setCost(costManagementInfo.getCost());
                                }
                                tranCarInfo.setCompId(warehouseBaseInfo.getCompId());
                                tranCarInfo.setTranType("1");
                                tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                                String tranCarNo = "";
                                if ((tranCarInfoList.size() + 1) < 10) {
                                    tranCarNo = "C00" + (tranCarInfoList.size() + 1);
                                } else if (tranCarInfoList.size() + 1 < 100) {
                                    tranCarNo = "C0" + (tranCarInfoList.size() + 1);
                                } else {
                                    tranCarNo = "C" + (tranCarInfoList.size() + 1);
                                }
                                tranCarInfo.setTranCarNo(tranCarNo);
                                tranCarInfo.setId(IdGenerator.generateUUID());
                                tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                                tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                                tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                                warehouseInOutInfo.setCarId(tranCarInfo.getId());
                                warehouseInOutInfo.setTranCarNo(tranCarNo);
                                warehouseInOutInfoService.updateById(warehouseInOutInfo);
                                tranCarInfoService.insert(tranCarInfo);
                            }
                            //生成汽运报表
                            TranSettlementReport tranSettlementReport = new TranSettlementReport();
                            tranSettlementReport.setCompId(warehouseBaseInfo.getCompId());
                            tranSettlementReport.setCarId(warehouseInOutInfo.getCarId());
                            tranSettlementReport.setId(IdGenerator.generateUUID());
                            if ("汽运".equals(warehouseInOutInfo.getOutType())) {
                                tranSettlementReport.setTranType("汽运");
                                tranSettlementReport.setTranTypeKey("1");
                            } else if ("火运".equals(warehouseInOutInfo.getOutType())) {
                                tranSettlementReport.setTranType("火运");
                                tranSettlementReport.setTranTypeKey("2");
                            } else {
                                tranSettlementReport.setTranType("船运");
                                tranSettlementReport.setTranTypeKey("3");
                            }
                            tranSettlementReport.setContractNo(warehouseInOutInfo.getContractNo());
                            tranSettlementReport.setCarNo(warehouseInOutInfo.getCarNo());
                            tranSettlementReport.setSettlementWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            //运输单价不为空
                            if (warehouseInOutInfo.getFreight()!=null){
                                //应付
                                tranSettlementReport.setAmountIngPayable(Float.valueOf(warehouseInOutInfo.getFreight()) * tranSettlementReport.getSettlementWeight());
                                //未付
                                tranSettlementReport.setAmountNotPayable(Float.valueOf(warehouseInOutInfo.getFreight()) * tranSettlementReport.getSettlementWeight());
                                tranSettlementReport.setTransportPrice(Float.valueOf(warehouseInOutInfo.getFreight()));
                            }
                            tranSettlementReport.setLoadingImg(warehouseInOutInfo.getAddressUrl());
                            tranSettlementReport.setLoadingWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            tranSettlementReportService.insert(tranSettlementReport);
                            boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(tranSettlementReport.getWorkflowId());
                            // 不是退回的单子
                            if (isStartWorkflow) {
                                Workflow workflow = workflowService
                                        .findLatestWorkflowByBusinessCodeByApp(tranSettlementReport.getCompId(), "TRANSPORTATION-SETTLEMENT-REPORT");
                                // 没配置审核流程，直接结束并处理信息
                                if (workflow == null) {
                                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                }
                                // 开启审核流
                                else {

                                    // 设置状态 已提交审核
                                    tranSettlementReport.setWorkflowId(workflow.getId());
                                    tranSettlementReportService.updateById(tranSettlementReport);
                                    workflowService.startInstance(workflow.getId(), tranSettlementReport.getId());
                                }
                            }
                            // 退回的单子 再启用
                            else {

                                tranSettlementReportService.updateById(tranSettlementReport);
                                workflowService.activateInstance(tranSettlementReport.getWorkflowId(), tranSettlementReport.getId());
                            }
                        }
                    }
                    //运费大于0生成运费结算报表数据
//                    if (warehouseInOutInfo.getFreight() != null && warehouseInOutInfo.getFreight() > 0) {
//                        //生成汽运报表
//                        TranSettlementReport tranSettlementReport = new TranSettlementReport();
//                        tranSettlementReport.setCompId(warehouseBaseInfo.getCompId());
//                        tranSettlementReport.setCarId(warehouseInOutInfo.getCarId());
//                        tranSettlementReport.setId(IdGenerator.generateUUID());
//                        if ("汽运".equals(warehouseInOutInfo.getOutType())) {
//                            tranSettlementReport.setTranType("汽运");
//                            tranSettlementReport.setTranTypeKey("1");
//                        } else if ("火运".equals(warehouseInOutInfo.getOutType())) {
//                            tranSettlementReport.setTranType("火运");
//                            tranSettlementReport.setTranTypeKey("2");
//                        } else {
//                            tranSettlementReport.setTranType("船运");
//                            tranSettlementReport.setTranTypeKey("3");
//                        }
//                        tranSettlementReport.setContractNo(warehouseInOutInfo.getContractNo());
//                        tranSettlementReport.setCarNo(warehouseInOutInfo.getCarNo());
//                        tranSettlementReport.setSettlementWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
//                        //应付
//                        tranSettlementReport.setAmountIngPayable(Float.valueOf(warehouseInOutInfo.getFreight()) * tranSettlementReport.getSettlementWeight());
//                        //未付
//                        tranSettlementReport.setAmountNotPayable(Float.valueOf(warehouseInOutInfo.getFreight()) * tranSettlementReport.getSettlementWeight());
//                        tranSettlementReport.setLoadingWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
//                        tranSettlementReport.setLoadingImg(warehouseInOutInfo.getAddressUrl());
//                        tranSettlementReport.setTransportPrice(Float.valueOf(warehouseInOutInfo.getFreight()));
//                        tranSettlementReportService.insert(tranSettlementReport);
//                        boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(tranSettlementReport.getWorkflowId());
//                        // 不是退回的单子
//                        if (isStartWorkflow) {
//                            Workflow workflow = workflowService
//                                    .findLatestWorkflowByBusinessCodeByApp(tranSettlementReport.getCompId(), "TRANSPORTATION-SETTLEMENT-REPORT");
//                            // 没配置审核流程，直接结束并处理信息
//                            if (workflow == null) {
//                                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
//                            }
//                            // 开启审核流
//                            else {
//
//                                // 设置状态 已提交审核
//                                tranSettlementReport.setWorkflowId(workflow.getId());
//                                tranSettlementReportService.updateById(tranSettlementReport);
//                                workflowService.startInstance(workflow.getId(), tranSettlementReport.getId());
//                            }
//                        }
//                        // 退回的单子 再启用
//                        else {
//
//                            tranSettlementReportService.updateById(tranSettlementReport);
//                            workflowService.activateInstance(tranSettlementReport.getWorkflowId(), tranSettlementReport.getId());
//                        }
//                    }
                    TranCarInfo tranCarInfo = tranCarInfoService.selectById(warehouseInOutInfo.getCarId());
                    if (tranCarInfo != null) {
                        //将发货数据同步到派车表
                        tranCarInfo.setLoadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        if (warehouseInOutInfo.getAddressUrl() != null) {
                            tranCarInfo.setLoadPoundImg(warehouseInOutInfo.getAddressUrl());
                        }
                        if ("移库出库".equals(warehouseInOutInfo.getInOutType())) {
                            //移库出库时打入成本
                            CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName()));
                            if (costManagementInfo != null) {
                                tranCarInfo.setCost(costManagementInfo.getCost());
                            }
                        }
                        tranCarInfo.setLoadingDate(warehouseInOutInfo.getInOutDate());
                        tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                        tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                        tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                        if ("1".equals(tranCarInfo.getSubmit())) {
                            throw new YException(YExceptionEnum.CARNO_SUBMITTED_ERROR);
                        } else {
                            tranCarInfo.setSubmit("1");
                        }
                        tranCarInfoService.updateById(tranCarInfo);
                    }
                    //判断是否有货
                    if (warehouseBaseInfo != null) {
                        //  查询库位
                        WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectById(warehouseInOutInfo.getPositionId());
                        if (warehousePositionInfo != null) {
                            // 查询货物库存量
                            WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                                    .eq("position_id", warehouseInOutInfo.getPositionId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName())
                                    .eq("delete_flag", "0"));
                            // 判断是否有货
                            if (warehousePositionStorageInfo != null) {
                                if (warehouseInOutInfo.getNetWeight() <= warehousePositionStorageInfo.getStorage()) {
                                    // 更新库存量
                                    warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() - Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
                                }
                                //出库量大于库存量
                                else {
                                    throw new YException(YExceptionEnum.INVENTORY_NO_ERROR);
                                }
                            }
                            // 没有储存量
                            else {
                                throw new YException(YExceptionEnum.POSITIONSTORAGE_NO_ERROR);
                            }
                        }
                        //库位不存在
                        else {
                            throw new YException(YExceptionEnum.POSITION_NO_ERROR);
                        }
                        //出库时打入成本
                        CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                                .eq("goods_name", warehouseInOutInfo.getGoodsName()));
                        if (costManagementInfo != null) {
                            warehouseInOutInfo.setWeightedCost(Float.valueOf(String.valueOf(costManagementInfo.getCost())));
                            warehouseInOutInfoService.updateById(warehouseInOutInfo);
                            TranCarInfo tranCarInfo1 = tranCarInfoService.selectById(warehouseInOutInfo.getCarId());
                            if (tranCarInfo1 != null) {
                                //打入出库成本
                                tranCarInfo1.setCost(costManagementInfo.getCost());
                                tranCarInfoService.updateById(tranCarInfo1);
                            }
                        }
                    }
                    //仓库不存在
                    else {
                        throw new YException(YExceptionEnum.WAREHOUSE_NO_ERROR);
                    }
                }
                //临时库出库
                else if ("1".equals(warehouseInOutInfo.getInOutFlag()) && "2".equals(warehouseBaseInfo.getWarehouseType())) {
                    //临时库销售出库类型 且为自动创建的临时库时(采购报表进数据，销售报表也进数据)
                    if ("1".equals(warehouseInOutInfo.getInOutTypeKey()) && "1".equals(warehouseBaseInfo.getCreateType())) {
                        //查出库任务关联的货源
                        InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                .eq("in_out_task_no", warehouseInOutInfo.getInOutTaskNo()));
                        List<SourceRelationInfo> sourceRelationInfoList =sourceRelationInfoService.selectList(new EntityWrapper<SourceRelationInfo>()
                                .eq("task_id", inOutWarehouseTask.getId())
                                .eq("delete_flag", "0"));
                        if (!CollectionUtils.isEmpty(sourceRelationInfoList)){
                            for (SourceRelationInfo sourceRelationInfo:sourceRelationInfoList){
                                //查货源关联的入库单
                                WarehousingOrder warehousingOrder=warehousingOrderService.selectById(sourceRelationInfo.getSourceId());
                                //临时库只有采购入库情况
                                if ("采购入库".equals(warehousingOrder.getInType())){
                                    //更新采购合同库存销售量
                                    ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                                            .eq("comp_id",warehousingOrder.getCompId()).eq("inventory_type","1").eq("contract_no",warehousingOrder.getContractNo())
                                            .eq("warehouse",warehouseInOutInfo.getWarehouseName()));
                                    if (contractInventoryDistribution!=null){
                                        contractInventoryDistribution.setInStorage(contractInventoryDistribution.getInStorage()-warehouseInOutInfo.getNetWeight()*sourceRelationInfo.getProportion());
                                        contractInventoryDistributionService.updateById(contractInventoryDistribution);
                                    }
                                }
                            }
                        }
                        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseBaseInfo.getWarehouseName())
                                .eq("deliver_type", "1")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo != null) {
                            //现货采购入库报表
                            StockPurchaseReceiptReport stockPurchaseReceiptReport = new StockPurchaseReceiptReport();
                            stockPurchaseReceiptReport.setId(IdGenerator.generateUUID());
                            stockPurchaseReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            stockPurchaseReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockPurchaseReceiptReport.setContractNo(contractManagementInfo.getContractNo());
                            stockPurchaseReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockPurchaseReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            stockPurchaseReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockPurchaseReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockPurchaseReceiptReport.setNetWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            stockPurchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                            stockPurchaseReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            stockPurchaseReceiptReport.setSettlementPrice(contractManagementInfo.getUnitContractPrice());
                            if (contractManagementInfo.getUnitContractPrice() != null) {
                                stockPurchaseReceiptReport.setAmountIngPayable(warehouseInOutInfo.getNetWeight() *
                                        (contractManagementInfo.getUnitContractPrice()));
                            }
                            stockPurchaseReceiptReport.setAmountEdPayable(0.0d);
                            stockPurchaseReceiptReport.setAmountNotPayable(stockPurchaseReceiptReport.getAmountIngPayable());
                            stockPurchaseReceiptReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                            stockPurchaseReceiptReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
                            stockPurchaseReceiptReportService.insert(stockPurchaseReceiptReport);
                            boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(stockPurchaseReceiptReport.getWorkflowId());
                            // 不是退回的单子
                            if (isStartWorkflow) {
                                Workflow workflow = workflowService
                                        .findLatestWorkflowByBusinessCodeByApp(stockPurchaseReceiptReport.getCompId(), "STOCK-PROCUREMENT-RECEIPT-REPORT");
                                // 没配置审核流程，直接结束并处理信息
                                if (workflow == null) {
                                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                }
                                // 开启审核流
                                else {
                                    // 设置状态 已提交审核
                                    stockPurchaseReceiptReport.setWorkflowId(workflow.getId());
                                    stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                    workflowService.startInstance(workflow.getId(), stockPurchaseReceiptReport.getId());
                                }
                            }
                            // 退回的单子 再启用
                            else {
                                stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                workflowService.activateInstance(stockPurchaseReceiptReport.getWorkflowId(), stockPurchaseReceiptReport.getId());
                            }
                        }
                        //现货销售出库报表
                        StockSaleReceiptReport stockSaleReceiptReport = new StockSaleReceiptReport();
                        stockSaleReceiptReport.setId(IdGenerator.generateUUID());
                        stockSaleReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                        stockSaleReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                        stockSaleReceiptReport.setContractNo(contractManagementInfo.getContractNo());
                        stockSaleReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                        stockSaleReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                        stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                        stockSaleReceiptReport.setNetWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        stockSaleReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        if (warehouseInOutInfo.getCost() != null) {
                            stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(warehouseInOutInfo.getCost())));
                        } else {
                            stockSaleReceiptReport.setSettlementPrice(0d);
                        }
                        stockSaleReceiptReport.setAmountEdReceivable(0.0d);
                        stockSaleReceiptReport.setDeliveryDate(warehouseInOutInfo.getInOutDate());
                        stockSaleReceiptReport.setAmountIngReceivable(stockSaleReceiptReport.getSettlementPrice() * warehouseInOutInfo.getNetWeight());
                        stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                        stockSaleReceiptReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                        stockSaleReceiptReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
                        stockSaleReceiptReportService.insert(stockSaleReceiptReport);
                        boolean isStartWorkflow1 = org.apache.commons.lang3.StringUtils.isBlank(stockSaleReceiptReport.getWorkflowId());
                        // 不是退回的单子
                        if (isStartWorkflow1) {
                            Workflow workflow = workflowService
                                    .findLatestWorkflowByBusinessCodeByApp(stockSaleReceiptReport.getCompId(), "SALE-RECEIPT-REPORT");
                            // 没配置审核流程，直接结束并处理信息
                            if (workflow == null) {
                                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                            }
                            // 开启审核流
                            else {
                                // 设置状态 已提交审核
                                stockSaleReceiptReport.setWorkflowId(workflow.getId());
                                stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                                workflowService.startInstance(workflow.getId(), stockSaleReceiptReport.getId());
                            }
                        }
                        // 退回的单子 再启用
                        else {
                            stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                            workflowService.activateInstance(stockSaleReceiptReport.getWorkflowId(), stockSaleReceiptReport.getId());
                        }
                        ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", contractManagementInfo.getContractNo()).eq("delete_flag", "0"));
                        if (contractManagementInfo1 == null) {
                            throw new YException(YExceptionEnum.CONTRACT_NO_NOT_EXSITS_ERROR);
                        }
                        Wrapper wrapper = new EntityWrapper<TranCarInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("car_no", warehouseInOutInfo.getCarNo())
                                .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                                .eq("tran_car_no", warehouseInOutInfo.getTranCarNo());
                        TranCarInfo tranCarInfo = tranCarInfoService.selectOne(wrapper);
                        if (tranCarInfo != null) {
                            //将发货数据同步到派车表
                            tranCarInfo.setLoadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            if (warehouseInOutInfo.getAddressUrl() != null) {
                                tranCarInfo.setLoadPoundImg(warehouseInOutInfo.getAddressUrl());
                            }
                            tranCarInfo.setLoadingDate(warehouseInOutInfo.getInOutDate());
                            tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
//                                    tranCarInfo.setDeductionAmount(warehouseInOutInfo.getDeductionAmount());
                            tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                            tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                            if ("1".equals(tranCarInfo.getSubmit())) {
                                throw new YException(YExceptionEnum.CARNO_SUBMITTED_ERROR);
                            } else {
                                tranCarInfo.setSubmit("1");
                            }
                            tranCarInfoService.updateById(tranCarInfo);
                        }
                    }
                    //临时库移库出库类型 且为自动创建的临时库时进采购报表
                    if ("3".equals(warehouseInOutInfo.getInOutTypeKey()) && "1".equals(warehouseBaseInfo.getCreateType())) {
//                        //更新合同移库库存
//                        ContractInventoryDistribution contractInventoryDistribution1=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
//                                .eq("comp_id",warehouseBaseInfo.getCompId()).eq("inventory_type","1").eq("contract_no",warehouseInOutInfo.getContractNo())
//                                .eq("warehouse",warehouseInOutInfo.getWarehouseName()));
//                        if (contractInventoryDistribution1!=null){
//                            contractInventoryDistribution1.setRemoveStorage(contractInventoryDistribution1.getRemoveStorage()+warehouseInOutInfo.getNetWeight());
//                            contractInventoryDistributionService.updateById(contractInventoryDistribution1);
//                        }
                        //按出库重量结算
                        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseBaseInfo.getWarehouseName())
                                .eq("settlement_weight_method", "1")
                                .eq("deliver_type", "1")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo != null) {
                            //现货采购入库报表
                            StockPurchaseReceiptReport stockPurchaseReceiptReport = new StockPurchaseReceiptReport();
                            stockPurchaseReceiptReport.setId(IdGenerator.generateUUID());
                            stockPurchaseReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            stockPurchaseReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockPurchaseReceiptReport.setContractNo(contractManagementInfo.getContractNo());
                            stockPurchaseReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockPurchaseReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            stockPurchaseReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockPurchaseReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockPurchaseReceiptReport.setNetWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            stockPurchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                            stockPurchaseReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            stockPurchaseReceiptReport.setSettlementPrice(contractManagementInfo.getUnitContractPrice());
                            if (contractManagementInfo.getUnitContractPrice() != null) {
                                stockPurchaseReceiptReport.setAmountIngPayable(warehouseInOutInfo.getNetWeight() *
                                        (contractManagementInfo.getUnitContractPrice()));
                            }
                            stockPurchaseReceiptReport.setAmountEdPayable(0.0d);
                            stockPurchaseReceiptReport.setAmountNotPayable(stockPurchaseReceiptReport.getAmountIngPayable());
                            stockPurchaseReceiptReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                            stockPurchaseReceiptReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
                            stockPurchaseReceiptReportService.insert(stockPurchaseReceiptReport);
                            boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(stockPurchaseReceiptReport.getWorkflowId());
                            // 不是退回的单子
                            if (isStartWorkflow) {
                                Workflow workflow = workflowService
                                        .findLatestWorkflowByBusinessCodeByApp(stockPurchaseReceiptReport.getCompId(), "STOCK-PROCUREMENT-RECEIPT-REPORT");
                                // 没配置审核流程，直接结束并处理信息
                                if (workflow == null) {
                                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                }
                                // 开启审核流
                                else {
                                    // 设置状态 已提交审核
                                    stockPurchaseReceiptReport.setWorkflowId(workflow.getId());
                                    stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                    workflowService.startInstance(workflow.getId(), stockPurchaseReceiptReport.getId());
                                }
                            }
                            // 退回的单子 再启用
                            else {
                                stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                workflowService.activateInstance(stockPurchaseReceiptReport.getWorkflowId(), stockPurchaseReceiptReport.getId());
                            }
                        }
                        ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", contractManagementInfo.getContractNo()).eq("delete_flag", "0"));
                        if (contractManagementInfo1 == null) {
                            throw new YException(YExceptionEnum.CONTRACT_NO_NOT_EXSITS_ERROR);
                        }
                        Wrapper wrapper = new EntityWrapper<TranCarInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("car_no", warehouseInOutInfo.getCarNo())
                                .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                                .eq("tran_car_no", warehouseInOutInfo.getTranCarNo());
                        TranCarInfo tranCarInfo = tranCarInfoService.selectOne(wrapper);
                        if (tranCarInfo != null) {
                            //将发货数据同步到派车表
                            tranCarInfo.setLoadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            if (warehouseInOutInfo.getAddressUrl() != null) {
                                tranCarInfo.setLoadPoundImg(warehouseInOutInfo.getAddressUrl());
                            }
                            tranCarInfo.setLoadingDate(warehouseInOutInfo.getInOutDate());
                            tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                            if (contractManagementInfo != null) {
                                tranCarInfo.setCost(contractManagementInfo.getUnitContractPrice());
                            } else {
                                //出库时打入成本
                                CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                                        .eq("goods_name", warehouseInOutInfo.getGoodsName()));
                                if (costManagementInfo != null) {
                                    tranCarInfo.setCost(costManagementInfo.getCost());
                                }
                            }
                            tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                            tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                            if ("1".equals(tranCarInfo.getSubmit())) {
                                throw new YException(YExceptionEnum.CARNO_SUBMITTED_ERROR);
                            } else {
                                tranCarInfo.setSubmit("1");
                            }
                            tranCarInfoService.updateById(tranCarInfo);
                        }
                    }
                    Wrapper<InOutWarehouseTask> inOutWarehouseTaskWrapper = new EntityWrapper<>();
                    inOutWarehouseTaskWrapper.eq("in_out_flag", "1").eq("delete_flag", "0");
                    inOutWarehouseTaskWrapper.andNew().eq("move_task_no", warehouseInOutInfo.getContractNo()).or()
                            .eq("contract_no", warehouseInOutInfo.getContractNo());
                    InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(inOutWarehouseTaskWrapper);
                    if (inOutWarehouseTask != null) {
                        //自运出库时手动加的车
                        if ("1".equals(warehouseInOutInfo.getSelfLoading()) || warehouseInOutInfo.getTranCarNo() == null || warehouseInOutInfo.getCarId() == null) {
                            List<TranCarInfo> tranCarInfoList = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                                    .eq("contract_no", warehouseInOutInfo.getContractNo()).eq("tran_type", "1")
                                    .orderBy("create_date", false));
                            TranCarInfo tranCarInfo = new TranCarInfo();
                            TranTaskInfo tranTaskInfo = tranTaskInfoService.selectOne(new EntityWrapper<TranTaskInfo>()
                                    .eq("comp_id", warehouseBaseInfo.getCompId())
                                    .eq("contract_no", warehouseInOutInfo.getContractNo()));
                            if (tranTaskInfo != null) {
                                TranProcessInfo tranProcessInfo = tranProcessInfoService.selectOne(new EntityWrapper<TranProcessInfo>()
                                        .eq("info_id", tranTaskInfo.getId()));
                                tranCarInfo.setProcessId(tranProcessInfo.getId());
                                tranCarInfo.setTranPrice(String.valueOf(tranProcessInfo.getTranPrice() != null ? tranProcessInfo.getTranPrice() : 0f));
                                warehouseInOutInfo.setFreight(tranProcessInfo.getTranPrice());
                                tranCarInfo.setInfoId(tranTaskInfo.getId());
                            } else {
                                throw new YException(YExceptionEnum.TRANTASK_NOT_CREATED_ERROR);
                            }
                            tranCarInfo.setCompId(warehouseBaseInfo.getCompId());
                            tranCarInfo.setTranType("1");
                            tranCarInfo.setSubmit("1");
                            ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                    .eq("contract_no", warehouseInOutInfo.getContractNo()).eq("delete_flag", "0"));
                            if (contractManagementInfo1 != null) {
                                tranCarInfo.setCost(contractManagementInfo1.getUnitContractPrice());
                            } else {
                                //出库时打入成本
                                CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                                        .eq("goods_name", warehouseInOutInfo.getGoodsName()));
                                if (costManagementInfo != null) {
                                    tranCarInfo.setCost(costManagementInfo.getCost());
                                }
                            }
                            tranCarInfo.setLoadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            tranCarInfo.setLoadingDate(new Date());
                            tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                            String tranCarNo = "";
                            if ((tranCarInfoList.size() + 1) < 10) {
                                tranCarNo = "C00" + (tranCarInfoList.size() + 1);
                            } else if (tranCarInfoList.size() + 1 < 100) {
                                tranCarNo = "C0" + (tranCarInfoList.size() + 1);
                            } else {
                                tranCarNo = "C" + (tranCarInfoList.size() + 1);
                            }
                            tranCarInfo.setTranCarNo(tranCarNo);
                            tranCarInfo.setId(IdGenerator.generateUUID());
                            tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                            tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                            tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                            warehouseInOutInfo.setSelfLoading("1");
                            warehouseInOutInfo.setCarId(tranCarInfo.getId());
                            warehouseInOutInfo.setTranCarNo(tranCarNo);
                            warehouseInOutInfoService.updateById(warehouseInOutInfo);
                            tranCarInfoService.insert(tranCarInfo);
                            //生成汽运报表
                            TranSettlementReport tranSettlementReport = new TranSettlementReport();
                            tranSettlementReport.setCompId(warehouseBaseInfo.getCompId());
                            tranSettlementReport.setCarId(warehouseInOutInfo.getCarId());
                            tranSettlementReport.setId(IdGenerator.generateUUID());
                            if ("汽运".equals(warehouseInOutInfo.getOutType())) {
                                tranSettlementReport.setTranType("汽运");
                                tranSettlementReport.setTranTypeKey("1");
                            } else if ("火运".equals(warehouseInOutInfo.getOutType())) {
                                tranSettlementReport.setTranType("火运");
                                tranSettlementReport.setTranTypeKey("2");
                            } else {
                                tranSettlementReport.setTranType("船运");
                                tranSettlementReport.setTranTypeKey("3");
                            }
                            tranSettlementReport.setContractNo(warehouseInOutInfo.getContractNo());
                            tranSettlementReport.setCarNo(warehouseInOutInfo.getCarNo());
                            tranSettlementReport.setSettlementWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            //运输单价不为空
                            if (warehouseInOutInfo.getFreight()!=null){
                                //应付
                                tranSettlementReport.setAmountIngPayable(Float.valueOf(warehouseInOutInfo.getFreight()) * tranSettlementReport.getSettlementWeight());
                                //未付
                                tranSettlementReport.setAmountNotPayable(Float.valueOf(warehouseInOutInfo.getFreight()) * tranSettlementReport.getSettlementWeight());
                                tranSettlementReport.setTransportPrice(Float.valueOf(warehouseInOutInfo.getFreight()));
                            }
                            tranSettlementReport.setLoadingImg(warehouseInOutInfo.getAddressUrl());
                            tranSettlementReport.setLoadingWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            tranSettlementReportService.insert(tranSettlementReport);
                            boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(tranSettlementReport.getWorkflowId());
                            // 不是退回的单子
                            if (isStartWorkflow) {
                                Workflow workflow = workflowService
                                        .findLatestWorkflowByBusinessCodeByApp(tranSettlementReport.getCompId(), "TRANSPORTATION-SETTLEMENT-REPORT");
                                // 没配置审核流程，直接结束并处理信息
                                if (workflow == null) {
                                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                }
                                // 开启审核流
                                else {

                                    // 设置状态 已提交审核
                                    tranSettlementReport.setWorkflowId(workflow.getId());
                                    tranSettlementReportService.updateById(tranSettlementReport);
                                    workflowService.startInstance(workflow.getId(), tranSettlementReport.getId());
                                }
                            }
                            // 退回的单子 再启用
                            else {

                                tranSettlementReportService.updateById(tranSettlementReport);
                                workflowService.activateInstance(tranSettlementReport.getWorkflowId(), tranSettlementReport.getId());
                            }
                        }
                    }
                    if (warehouseBaseInfo != null) {
                        //出库时打入成本
                        CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                                .eq("goods_name", warehouseInOutInfo.getGoodsNameKey()));
                        if (costManagementInfo != null) {
                            warehouseInOutInfo.setWeightedCost(Float.valueOf(String.valueOf(costManagementInfo.getCost())));
                            warehouseInOutInfoService.updateById(warehouseInOutInfo);
                        }
//                        Float storage =0f;
//                        // 查询应余量
//                        WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
//                                .eq("position_id", warehouseInOutInfo.getPositionId()).eq("goods_name_key", warehouseInOutInfo.getGoodsNameKey()));
//                        if (warehousePositionStorageInfo != null) {
//                            storage = warehousePositionStorageInfo.getStorage();
//                        }
//                        //出库量大于入库量
//                        if ((warehouseInOutInfo.getNetWeight().compareTo(storage)) > 0) {
//                            throw new YException(YExceptionEnum.INNETWEIGHT_NO_ERROR);
//                        }
                    }
                }
            }
        }
        cacheComponent.delPrefixKey(Const.ADMIN_CONTRACTINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        return warehouseInOutInfo.getId();
    }

    @Override
    public String returnWarehouse(WarehouseInOutInfo warehouseInOutInfo) {
        WarehouseInOutInfo warehouseInOutInfo1 = this.selectById(warehouseInOutInfo.getId());
        warehouseInOutInfo.setStatusFlag(StatusEnum.TEMPORARILY_STORED.getFlag());
        warehouseInOutInfo.setStatus(StatusEnum.TEMPORARILY_STORED.getName());
        this.updateById(warehouseInOutInfo);
        if ("销售出库".equals(warehouseInOutInfo1.getInOutType())) {
            StockSaleReceiptReport stockSaleReceiptReport = stockSaleReceiptReportService.selectOne(new EntityWrapper<StockSaleReceiptReport>()
                    .eq("warehouse_record_id", warehouseInOutInfo.getId()));
            if (stockSaleReceiptReport != null) {
                stockSaleReceiptReportService.deleteById(stockSaleReceiptReport.getId());
            }
        } else if ("采购入库".equals(warehouseInOutInfo1.getInOutType())) {
            StockPurchaseReceiptReport stockPurchaseReceiptReport = stockPurchaseReceiptReportService.selectOne(new EntityWrapper<StockPurchaseReceiptReport>()
                    .eq("warehouse_record_id", warehouseInOutInfo.getId()));
            if (stockPurchaseReceiptReport != null) {
                stockPurchaseReceiptReportService.deleteById(stockPurchaseReceiptReport.getId());
            }
        } else if ("移库入库".equals(warehouseInOutInfo1.getInOutType())) {
            StockPurchaseReceiptReport stockPurchaseReceiptReport = stockPurchaseReceiptReportService.selectOne(new EntityWrapper<StockPurchaseReceiptReport>()
                    .eq("warehouse_record_id", warehouseInOutInfo.getId()));
            if (stockPurchaseReceiptReport != null) {
                stockPurchaseReceiptReportService.deleteById(stockPurchaseReceiptReport.getId());
            }
        }
        InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                .eq("in_out_task_no", warehouseInOutInfo1.getInOutTaskNo()));
        if (inOutWarehouseTask != null) {
            inOutWarehouseTask.setCompletedQuantity(inOutWarehouseTask.getCompletedQuantity() - warehouseInOutInfo1.getNetWeight());
        }
        return "OK";

    }

    /**
     * 流转记录查询
     *
     * @param warehouseInOutInfo
     * @return
     */
    @Override
    public Page<WarehouseInOutInfo> selectInfo(WarehouseInOutInfo warehouseInOutInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (warehouseInOutInfo.getCurrentPage() - 1)
                * warehouseInOutInfo.getPageSize());
        //  仓库ID
        pageView.put("baseId", warehouseInOutInfo.getBaseId());
        //  仓位ID
        pageView.put("positionId", warehouseInOutInfo.getPositionId());
        pageView.put("searchKeyWord", warehouseInOutInfo.getSearchKeyWord());
        pageView.put("startDate", warehouseInOutInfo.getStartDate());
        pageView.put("endDate", warehouseInOutInfo.getEndDate());
        pageView.put("pcFlag", warehouseInOutInfo.getPcFlag());
        pageView.put("warehouseName", warehouseInOutInfo.getWarehouseName());
        pageView.put("statusFlag", warehouseInOutInfo.getStatusFlag());
        pageView.put("searchType", warehouseInOutInfo.getSearchType());
        pageView.put("pageSize", warehouseInOutInfo.getPageSize());
        pageView.put("currentPage", warehouseInOutInfo.getCurrentPage());
        pageView.put("phone", warehouseInOutInfo.getPhone());
        // 查询记录总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<WarehouseInOutInfo> dataList = baseMapper.getListByCondition(pageView);
        Page<WarehouseInOutInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(warehouseInOutInfo.getCurrentPage());
        page.setSize(warehouseInOutInfo.getPageSize());
        return page;
    }

    /**
     * 关键字查询
     *
     * @param warehouseInOutInfo
     * @return
     */
    @Override
    public List<WarehouseInOutInfo> selectInfoByKeyWord(WarehouseInOutInfo warehouseInOutInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("keyWord", warehouseInOutInfo.getKeyWord());
        pageView.put("statusFlag", warehouseInOutInfo.getStatusFlag());
        pageView.put("phone", warehouseInOutInfo.getPhone());
        List<WarehouseInOutInfo> dataList = baseMapper.selectInfoByKeyWord(pageView);
        return dataList;
    }

    /**
     * 根据合同号查询公司id
     *
     * @param contractNo
     * @return
     */
    @Override
    public String selectCompId(String contractNo) {
        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                .eq("contract_no", contractNo));
        if (contractManagementInfo != null) {
            return contractManagementInfo.getCompId();
        }
        return "0";
    }


    /**
     * 流转记录查询(临时仓库)
     *
     * @param warehouseInOutInfo
     * @return
     */
    @Override
    public Page<WarehouseInOutInfo> selectInfoTemporary(WarehouseInOutInfo warehouseInOutInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (warehouseInOutInfo.getCurrentPage() - 1)
                * warehouseInOutInfo.getPageSize());
        //  仓库ID
        pageView.put("baseId", warehouseInOutInfo.getBaseId());
        pageView.put("searchType", warehouseInOutInfo.getSearchType());
        pageView.put("searchKeyWord", warehouseInOutInfo.getSearchKeyWord());
        pageView.put("startDate", warehouseInOutInfo.getStartDate());
        pageView.put("endDate", warehouseInOutInfo.getEndDate());
        pageView.put("pageSize", warehouseInOutInfo.getPageSize());
        pageView.put("currentPage", warehouseInOutInfo.getCurrentPage());
        // 查询记录总数
        Integer dataCount = baseMapper.getCountByConditionTemporary(pageView);
        List<WarehouseInOutInfo> dataList = baseMapper.getListByConditionTemporary(pageView);
        Page<WarehouseInOutInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(warehouseInOutInfo.getCurrentPage());
        page.setSize(warehouseInOutInfo.getPageSize());
        return page;
    }

    /**
     * 临时仓库货名下拉列表
     *
     * @param baseId
     * @return
     */
    @Override
    public List<WarehouseInOutInfo> selectTemporaryGoodsNameList(String baseId) {
        List<WarehouseInOutInfo> warehouseInOutInfoList = this.selectList(new EntityWrapper<WarehouseInOutInfo>()
                .eq("base_id", baseId).eq("delete_flag", "0").eq("status_flag", "3").groupBy("goods_name"));
        return warehouseInOutInfoList;
    }


    /******************************************仓库任务使用*****************************************************/

    /**
     * 出入库任务新增 编辑
     *
     * @param warehouseInOutInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertOrUpdateInOutTask(WarehouseInOutInfo warehouseInOutInfo) {
        // 根据传参id判断是否是新增
        //  空是新增
        if (StringUtils.isEmpty(warehouseInOutInfo.getId())) {

            // 主键id
            warehouseInOutInfo.setId(IdGenerator.generateUUID());
            warehouseInOutInfo.setTaskStatusKey(StatusEnum.TASK_REVIEWED.getFlag());
            warehouseInOutInfo.setTaskStatus(StatusEnum.TASK_REVIEWED.getName());
            // 化验数据
            WarehouseInOutDetail warehouseInOutDetail = warehouseInOutInfo.getWarehouseInOutDetail();
            if (warehouseInOutDetail != null) {
                warehouseInOutDetail.setId(IdGenerator.generateUUID());
                warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
                // 操作详情数据库
                List<WarehouseInOutDetail> ll = warehouseInOutDetailService.selectList(new EntityWrapper<WarehouseInOutDetail>().eq("info_id", warehouseInOutInfo.getId()));
                if (ll.size() == 0) {
                    warehouseInOutDetailService.insert(warehouseInOutDetail);
                }
            }

            // 操作主表数据
            this.insert(warehouseInOutInfo);
        }
        //  有id是修改
        else {
            // 化验数据
            WarehouseInOutDetail warehouseInOutDetail = warehouseInOutInfo.getWarehouseInOutDetail();
            if (warehouseInOutDetail != null) {
                // 操作详情数据库
                warehouseInOutDetailService.updateById(warehouseInOutDetail);
            }
            // 操作主表数据
            this.updateById(warehouseInOutInfo);
        }
        return warehouseInOutInfo.getId();
    }

    /**
     * 判断移库编号
     *
     * @param moveTaskNo
     * @return
     */
    @Override
    public boolean selectTaskNo(String moveTaskNo) {
        // 根据出入出入库编号查询数据
        WarehouseInOutInfo warehouseInOutInfo = this.selectOne(new EntityWrapper<WarehouseInOutInfo>().eq(WarehouseInOutInfo.QueryFiles.MOVE_TASK_NO, moveTaskNo)
                .eq(WarehouseInOutInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0));
        //如果没有可以使用
        if (warehouseInOutInfo == null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 查看
     *
     * @param
     */
    @Override
    public WarehouseInOutInfo getInfo(String id) {
        // 主表信息
        WarehouseInOutInfo warehouseInOutInfo = this.selectById(id);
        //详情信息
        WarehouseInOutDetail warehouseInOutDetail = warehouseInOutDetailService.selectOne(new EntityWrapper<WarehouseInOutDetail>().eq(WarehouseInOutDetail.QueryFiles.INFO_ID, id));
        if (warehouseInOutDetail != null) {
            if (warehouseInOutInfo == null) {
                try{
                    WeighingManagement weighingManagement = weighingManagementService.selectOne(new EntityWrapper<WeighingManagement>().eq("warehouse_in_out_id", id));
                    if (weighingManagement != null) {
                        warehouseInOutInfo.setId(id);
                        WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                                .eq("comp_id", weighingManagement.getCompId())
                                .eq("warehouse_name", weighingManagement.getWarehouseName())
                                .eq("warehouse_type", "1")
                                .eq("delete_flag", "0"));
                        if (warehouseBaseInfo != null) {
                            warehouseInOutInfo.setBaseId(warehouseBaseInfo.getId());
                        }
                        warehouseInOutInfo.setWarehouseName(weighingManagement.getWarehouseName());
                        WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectOne(new EntityWrapper<WarehousePositionInfo>()
                                .eq("base_id", warehouseBaseInfo.getId())
                                .eq("bin_number", weighingManagement.getBinNumber())
                                .eq("delete_flag", "0"));
                        if (warehousePositionInfo != null) {
                            warehouseInOutInfo.setPositionId(warehousePositionInfo.getId());
                        }
                        warehouseInOutInfo.setBinNumber(weighingManagement.getBinNumber());
                        warehouseInOutInfo.setOutType(weighingManagement.getOutType());
                        QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                                .eq("relation_id", weighingManagement.getRelationId())
                                .eq("comp_id", weighingManagement.getCompId())
                                .eq("delete_flag", "0"));
                        if(qualityInspectionManagement != null){
                            warehouseInOutInfo.setInOutTaskNo(qualityInspectionManagement.getInOutTaskNo());
                        }
                        if("3".equals(weighingManagement.getManagementType())){
                            warehouseInOutInfo.setInOutFlag("1");
                        }else{
                            warehouseInOutInfo.setInOutFlag("2");
                        }
                        warehouseInOutInfo.setGoodsName(weighingManagement.getGoodsName());
                        warehouseInOutInfo.setGoodsNameKey(weighingManagement.getGoodsNameKey());
                        warehouseInOutInfo.setGrossWeight((weighingManagement.getGrossWeight()==null?0:weighingManagement.getGrossWeight())/1000);
                        warehouseInOutInfo.setTare((weighingManagement.getTare()==null?0:weighingManagement.getTare())/1000);
                        warehouseInOutInfo.setNetWeight((double) (weighingManagement.getNetWeight()==null?0:weighingManagement.getNetWeight())/1000);
                        warehouseInOutInfo.setDeductionWeight( (weighingManagement.getDeductionWeight()==null?0:weighingManagement.getDeductionWeight())/1000);
                        warehouseInOutInfo.setGrade(weighingManagement.getGrade());
                        warehouseInOutInfo.setSecretaryWeigher(weighingManagement.getSecretaryWeigher());
                        warehouseInOutInfo.setInOutDate(weighingManagement.getGrossDate());
                        warehouseInOutInfo.setInOutTypeKey(weighingManagement.getInOutTypeKey());
                        warehouseInOutInfo.setCarNo(weighingManagement.getCarNumber());
                        warehouseInOutInfo.setContractNo(weighingManagement.getContractNo());
                        warehouseInOutInfo.setType(weighingManagement.getType());
                        warehouseInOutInfo.setCost(0f);
                        warehouseInOutInfo.setStatusFlag("1");
                        warehouseInOutInfo.setStatus("已暂存");
                        warehouseInOutInfo.setBackOffice(weighingManagement.getSecretaryWeigher());
                        warehouseInOutInfoService.insert(warehouseInOutInfo);
                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
            warehouseInOutInfo.setWarehouseInOutDetail(warehouseInOutDetail);
        }
        return warehouseInOutInfo;
    }

    /**
     * 查当天出/入库数量
     *
     * @param positionId,type
     * @param inOutFlag
     * @return
     */
    @Override
    public Integer count(String positionId, String inOutFlag) {
        //当天零点
        SimpleDateFormat now = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, 0);
        Date y = c.getTime();
        String year = now.format(y);
        Integer count = this.selectCount(new EntityWrapper<WarehouseInOutInfo>()
                .eq("position_id", positionId)
                .eq("in_out_flag", inOutFlag)
                .ge("create_date", year));
        return count;
    }

    /**
     * 调整
     *
     * @param warehouseInOutInfo
     * @return
     */
    @Override
    public String adjustment(WarehouseInOutInfo warehouseInOutInfo) {
        List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfo.getWarehouseInOutInfoList();
        if (!CollectionUtils.isEmpty(warehouseInOutInfoList)) {
            for (WarehouseInOutInfo warehouseInOutInfo1 : warehouseInOutInfoList) {
                warehouseInOutInfo1.setAdjustment(warehouseInOutInfo.getAdjustment());
                this.updateById(warehouseInOutInfo1);
            }
        }
        return "ok";
    }

    /**
     * 查看已派车辆
     */
    @Override
    public List<WarehouseInOutInfo> selectDistributeCar(String contractNo) {
        List<WarehouseInOutInfo> warehouseInOutInfoList = this.selectList(new EntityWrapper<WarehouseInOutInfo>()
                .eq(WarehouseInOutInfo.QueryFiles.CONTRACT_NO, contractNo)
                .eq(WarehouseInOutInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                .orderBy("update_date", false));
        return warehouseInOutInfoList;
    }

    /**
     * 流转记录查询
     *
     * @param phone
     * @return
     */
    @Override
    public Integer selectCountByPhone(String phone) {
        if (phone == null || phone.isEmpty()) {
            return 0;
        } else {
            Map<String, Object> pageView = new HashMap<>();
            pageView.put("statusFlag", '1');
            pageView.put("phone", phone);
            // 查询记录总数
            Integer dataCount = baseMapper.getCountByCondition(pageView);
            return dataCount;
        }
    }


    /**
     * 任务
     *
     * @param warehouseInOutInfo
     */
    @Override
    public void tesk(WarehouseInOutInfo warehouseInOutInfo, String flag) {
        // 先删除任务
        noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "INOUTTASK-TASK-APPROVE",
                warehouseInOutInfo.getId(), null);
        String staffName = "XXX";
        CommonStaff commitUserInfo = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        if (commitUserInfo != null) {
            staffName = commitUserInfo.getMajorRole() != null
                    ? commitUserInfo.getMajorRole().getRoleName() + " " + commitUserInfo.getStaffName()
                    : commitUserInfo.getStaffName();
        }
        String taskContent = "";
        // 向下一步操作人发送任务通知
        if ("1".equals(flag)) {
            taskContent = "您的合同(" + warehouseInOutInfo.getContractNo() + ")车辆：" + warehouseInOutInfo.getCarNo() + "已发出";
        } else {
            taskContent = "您的合同(" + warehouseInOutInfo.getContractNo() + ")车辆：" + warehouseInOutInfo.getCarNo() + "申请卸货，请及时确认";

        }
        NoticeTaskInfo taskInfo = new NoticeTaskInfo();
        taskInfo.setCompId(commitUserInfo.getCompId());
        taskInfo.setAcceptType(BaseNotice.AcceptStatus.STAFF);
        taskInfo.setBusinessId(warehouseInOutInfo.getId());
        taskInfo.setBusinessType("WAREHOUSE");
        taskInfo.setMessageContent(taskContent);
        taskInfo.setBusinessCode("INOUTTASK-TASK-APPROVE");
//            taskInfo.setNoticeTaskStatus(NoticeTaskInfo.NoticeTaskStatus.RETURN);
        noticeTaskService.createNoticeTask(Lists.newArrayList(warehouseInOutInfo.getCommonId()),
                null, taskInfo);

    }


    @Override
    public Integer selectCountCompany(String compId, String type) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("compId", compId);
        //  仓库ID
        pageView.put("type", type);
        return baseMapper.selectCountCompany(pageView);
    }

    /**
     * 修改入库量
     *
     * @param warehouseInOutInfo
     * @return
     */
    @Override
    public String updateStockQuantity(WarehouseInOutInfo warehouseInOutInfo) {
        WarehouseInOutInfo warehouseInOutInfos = this.selectOne(new EntityWrapper<WarehouseInOutInfo>()
                .eq("base_id", warehouseInOutInfo.getBaseId()).eq("in_out_type", "采购入库"));
        warehouseInOutInfos.setNetWeight(warehouseInOutInfo.getNetWeight());
        this.updateById(warehouseInOutInfos);
        return "ok";

    }


    /**
     * 新出入库
     *
     * @param warehouseInOutInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String newInOutWarehouse(WarehouseInOutInfo warehouseInOutInfo) {
        CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        warehouseInOutInfo.setBackOffice(commonStaff.getStaffName());
        WarehouseInOutDetail warehouseInOutDetail = warehouseInOutInfo.getWarehouseInOutDetail();
        // 查询仓库
        WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectById(warehouseInOutInfo.getBaseId());
        //判断暂存提交(前端传参1暂存3提交)
        if ("1".equals(warehouseInOutInfo.getStatusFlag())) {
            //插入记录
            if (StringUtils.isEmpty(warehouseInOutInfo.getId())) {
                warehouseInOutInfo.setId(IdGenerator.generateUUID());
                warehouseInOutInfo.setStatusFlag(StatusEnum.TEMPORARILY_STORED.getFlag());
                warehouseInOutInfo.setStatus(StatusEnum.TEMPORARILY_STORED.getName());
                this.insert(warehouseInOutInfo);
                // 详情
                warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
                warehouseInOutDetail.setId(IdGenerator.generateUUID());
                List<WarehouseInOutDetail> ll = warehouseInOutDetailService.selectList(new EntityWrapper<WarehouseInOutDetail>().eq("info_id", warehouseInOutInfo.getId()));
                if (ll.size() == 0) {
                    warehouseInOutDetailService.insert(warehouseInOutDetail);
                }
            }
            // 编辑修改记录
            else {
                this.updateById(warehouseInOutInfo);
                //app暂存判断详情表是否存在
                if (StringUtils.isEmpty(warehouseInOutDetail.getId())) {
                    // 详情
                    warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
                    warehouseInOutDetail.setId(IdGenerator.generateUUID());
                    List<WarehouseInOutDetail> ll = warehouseInOutDetailService.selectList(new EntityWrapper<WarehouseInOutDetail>().eq("info_id", warehouseInOutInfo.getId()));
                    if (ll.size() == 0) {
                        warehouseInOutDetailService.insert(warehouseInOutDetail);
                    }
                } else {
                    warehouseInOutDetailService.updateById(warehouseInOutDetail);
                }
            }
            //自运出库时手动加的车
            if ("1".equals(warehouseInOutInfo.getSelfLoading())) {
                TranTaskInfo tranTaskInfo = tranTaskInfoService.selectOne(new EntityWrapper<TranTaskInfo>()
                        .eq("comp_id", warehouseBaseInfo.getCompId())
                        .eq("contract_no", warehouseInOutInfo.getContractNo()));
                if (tranTaskInfo == null) {
                    throw new YException(YExceptionEnum.TRANTASK_NOT_CREATED_ERROR);
                }
            }
            //入库
            if ("2".equals(warehouseInOutInfo.getInOutFlag())) {
                Wrapper wrapper = new EntityWrapper<TranCarInfo>()
                        .eq("contract_no", warehouseInOutInfo.getContractNo())
                        .eq("car_no", warehouseInOutInfo.getCarNo())
                        .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                        .eq("tran_car_no", warehouseInOutInfo.getTranCarNo());
                TranCarInfo tranCarInfo = tranCarInfoService.selectOne(wrapper);
                if (tranCarInfo != null) {
                    //将车改成已被选
                    tranCarInfo.setSubmit("2");
                    tranCarInfo.setStatusFlag(StatusEnum.DELIVERED.getFlag());
                    tranCarInfo.setStatus(StatusEnum.DELIVERED.getName());
                    tranCarInfoService.updateById(tranCarInfo);
                }
                //毛重检斤
                //状态改为已称毛重
                if (warehouseInOutInfo.getWeighingManagement() != null) {
                    WeighingManagement weighingManagement = warehouseInOutInfo.getWeighingManagement();
                    weighingManagement.setStatus(StatusEnum.WEIGHED_GROSS_WEIGHT.getName());
                    weighingManagement.setStatusFlag(StatusEnum.WEIGHED_GROSS_WEIGHT.getFlag());
                    weighingManagement.setGrossDate(new Date());
                    weighingManagement.setSecretaryWeigher(commonStaff.getStaffName());
                    //质检信息
                    QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                            .eq("relation_id", weighingManagement.getRelationId())
                            .eq("comp_id", commonStaff.getCompId()));
                    if (qualityInspectionManagement != null) {
                        //状态改为已称毛重
//                      qualityInspectionManagement.setStatus(StatusEnum.WEIGHED_GROSS_WEIGHT.getName());
//                      qualityInspectionManagement.setStatusFlag(StatusEnum.WEIGHED_GROSS_WEIGHT.getFlag());
                        qualityInspectionManagementService.updateById(qualityInspectionManagement);
                    }
                    if (weighingManagement.getGrossWeight() == null || weighingManagement.getGrossWeight() == 0) {
                        throw new YException(YExceptionEnum.GROSSWEIGHT_NULL);
                    }
                    weighingManagementService.updateById(weighingManagement);
                }
            }
            //出库
            else {
                Wrapper wrapper = new EntityWrapper<TranCarInfo>()
                        .eq("contract_no", warehouseInOutInfo.getContractNo())
                        .eq("car_no", warehouseInOutInfo.getCarNo())
                        .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                        .eq("tran_car_no", warehouseInOutInfo.getTranCarNo());
                TranCarInfo tranCarInfo = tranCarInfoService.selectOne(wrapper);
                if (tranCarInfo != null) {
                    if ("1".equals(tranCarInfo.getSubmit())) {
                        throw new YException(YExceptionEnum.CARNO_SUBMITTED_ERROR);
                    } else {
                        tranCarInfo.setSubmit("1");
                    }
                    tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                    tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                    tranCarInfoService.updateById(tranCarInfo);
                }
                if (warehouseInOutInfo.getWeighingManagement() != null) {
                    if (warehouseInOutInfo.getWeighingManagement().getId() == null) {
                        //皮重检斤
                        WeighingManagement weighingManagement = warehouseInOutInfo.getWeighingManagement();
                        String relationId = IdGenerator.generateUUID();
                        weighingManagement.setId(IdGenerator.generateUUID());
                        if (weighingManagement.getCompId() == null || weighingManagement.getCompId().isEmpty()) {
                            weighingManagement.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
                        }
                        //获取当前年月日
                        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");//设置日期格式
                        String date = f.format(new Date(System.currentTimeMillis()));
                        //查询质检信息数量包括已删除的集合
                        List<WeighingManagement> weighingManagementList1 = weighingManagementService.selectWeighingManagementList(weighingManagement);//调用Service中的方法
                        //生成业务编号
                        if (weighingManagementList1.size() > 0) {
                            //取第一条数据的编号
                            String n = weighingManagementList1.get(0).getNumber();
                            //截取编号后4位
                            int intNumber = Integer.parseInt(n.substring(15));
                            intNumber++;
                            String businessNumber = String.valueOf(intNumber);
                            for (int i = 0; i < 4; i++) {
                                businessNumber = businessNumber.length() < 4 ? "0" + businessNumber : businessNumber;
                            }
                            //编号自增
                            businessNumber = weighingManagement.getNumberLetter() + date + weighingManagement.getWarehouseNo() + businessNumber;
                            weighingManagement.setNumber(businessNumber);
                        } else {
                            //如果当天数据为空，生成第一条数据
                            String businessNumber = weighingManagement.getNumberLetter() + date + weighingManagement.getWarehouseNo() + "0001";
                            weighingManagement.setNumber(businessNumber);
                        }
                        //判断质检编号是否唯一
                        List<WeighingManagement> weighingManagementList = weighingManagementService.selectList(new EntityWrapper<WeighingManagement>()
                                .eq("comp_id", weighingManagement.getCompId())
                                .eq("number", weighingManagement.getNumber()));
                        if (weighingManagementList.size() > 0) {
                            throw new YException(YExceptionEnum.QUALITY_NO_ERROR);
                        }
                        weighingManagement.setWarehouseInOutId(warehouseInOutInfo.getId());
                        weighingManagement.setRelationId(relationId);
                        weighingManagement.setTareDate(new Date());
                        weighingManagement.setManagementType("3");
                        //出库类型
                        weighingManagement.setServiceManagementType("2");
                        //状态改为已称皮重
                        weighingManagement.setStatus(StatusEnum.TARED.getName());
                        weighingManagement.setStatusFlag(StatusEnum.TARED.getFlag());
                        //生成质检信息
                        QualityInspectionManagement qualityInspectionManagement = new QualityInspectionManagement();
                        qualityInspectionManagement.setId(IdGenerator.generateUUID());
                        qualityInspectionManagement.setRelationId(weighingManagement.getRelationId());
                        qualityInspectionManagement.setContractNo(weighingManagement.getContractNo());
                        qualityInspectionManagement.setQualityNo(weighingManagement.getNumber());
                        qualityInspectionManagement.setWarehouseInOutId(weighingManagement.getWarehouseInOutId());
                        qualityInspectionManagement.setCarNumber(weighingManagement.getCarNumber());
                        qualityInspectionManagement.setCompId(weighingManagement.getCompId());
                        qualityInspectionManagement.setGoodsName(weighingManagement.getGoodsName());
                        qualityInspectionManagement.setBinNumber(weighingManagement.getBinNumber());
                        qualityInspectionManagement.setStatus(StatusEnum.TARED.getName());
                        qualityInspectionManagement.setStatusFlag(StatusEnum.TARED.getFlag());
                        qualityInspectionManagement.setManagementType("3");
                        qualityInspectionManagement.setServiceManagementType("2");
                        qualityInspectionManagement.setQualityDate(new Date());
                        qualityInspectionManagement.setWarehouseName(weighingManagement.getWarehouseName());
                        qualityInspectionManagement.setStorageTagNo(weighingManagement.getStorageNumber());
                        qualityInspectionManagementService.insert(qualityInspectionManagement);
                        weighingManagementService.insert(weighingManagement);
                    } else {
                        //编辑皮重检斤
                        WeighingManagement weighingManagement = warehouseInOutInfo.getWeighingManagement();
                        //状态改为已称皮重
                        weighingManagement.setStatus(StatusEnum.TARED.getName());
                        weighingManagement.setStatusFlag(StatusEnum.TARED.getFlag());
                        //更新检斤信息
                        weighingManagementService.updateById(weighingManagement);
                        //更新质检信息
                        qualityInspectionManagementService.updateById(weighingManagement.getQualityInspectionManagement());
                    }
                }
            }

        } else {
            //插入记录
            if (StringUtils.isEmpty(warehouseInOutInfo.getId())) {
                warehouseInOutInfo.setId(IdGenerator.generateUUID());
                warehouseInOutInfo.setStatusFlag(StatusEnum.SUBMITTED.getFlag());
                warehouseInOutInfo.setStatus(StatusEnum.SUBMITTED.getName());
                this.insert(warehouseInOutInfo);
                //更新出入库任务表已完成量
                InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                        .eq("in_out_task_no", warehouseInOutInfo.getInOutTaskNo()));
                if (inOutWarehouseTask != null) {
                    //更新货源实际出库重量
                    List<SourceRelationInfo> sourceRelationInfoList=sourceRelationInfoService.selectList(new EntityWrapper<SourceRelationInfo>()
                            .eq("task_id",inOutWarehouseTask.getId()));
                    if (!CollectionUtils.isEmpty(sourceRelationInfoList)){
                        for (SourceRelationInfo sourceRelationInfo:sourceRelationInfoList){
                            //实际重量
                            sourceRelationInfo.setActualOutWarehouseWeight(sourceRelationInfo.getActualOutWarehouseWeight()+Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()*sourceRelationInfo.getProportion())));
                            //剩余重量
                            sourceRelationInfo.setSurplusWeight(sourceRelationInfo.getSurplusWeight()-Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()*sourceRelationInfo.getProportion())));
                            sourceRelationInfoService.updateById(sourceRelationInfo);
                        }
                    }
                    //可超出重量
                    Float overNeight = 0.0f;
                    ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                            .eq("comp_id", inOutWarehouseTask.getCompId())
                            .eq("contract_no", inOutWarehouseTask.getContractNo()));
                    //出入库有合同
                    if (contractManagementInfo != null) {
                        overNeight = inOutWarehouseTask.getWeight() * (contractManagementInfo.getOverShort() / 100);
                    }
                    //出库无合同情况
                    else if (contractManagementInfo == null &&"1".equals(inOutWarehouseTask.getInOutFlag())) {
                        overNeight = inOutWarehouseTask.getWeight() * 0.05f;
                    } else {
                        contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("comp_id", inOutWarehouseTask.getCompId())
                                .eq("contract_no", inOutWarehouseTask.getWarehouseName()));
                        //移库入库
                        if (contractManagementInfo == null && "2".equals(inOutWarehouseTask.getInOutFlag())) {
                            overNeight = inOutWarehouseTask.getWeight() * 0.08f;
                        }
                    }
                    inOutWarehouseTask.setCompletedQuantity(inOutWarehouseTask.getCompletedQuantity() + warehouseInOutInfo.getNetWeight());
                    if (inOutWarehouseTask.getCompletedQuantity() > inOutWarehouseTask.getWeight() + overNeight) {
                        throw new YException(YExceptionEnum.TASK_WEIGHT_EXCEEDED_ERROR);
                    } else {
                        inOutWarehouseTaskService.updateById(inOutWarehouseTask);
                    }
                }
                // 详情
                warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
                warehouseInOutDetail.setId(IdGenerator.generateUUID());
                List<WarehouseInOutDetail> ll = warehouseInOutDetailService.selectList(new EntityWrapper<WarehouseInOutDetail>().eq("info_id", warehouseInOutInfo.getId()));
                if (ll.size() == 0) {
                    warehouseInOutDetailService.insert(warehouseInOutDetail);
                }

            }
            // 编辑修改记录
            else {
                //更新出入库任务表已完成量
                InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                        .eq("in_out_task_no", warehouseInOutInfo.getInOutTaskNo()));
                if (inOutWarehouseTask != null) {
                    //更新货源实际出库重量
                    List<SourceRelationInfo> sourceRelationInfoList=sourceRelationInfoService.selectList(new EntityWrapper<SourceRelationInfo>()
                            .eq("task_id",inOutWarehouseTask.getId()));
                    if (!CollectionUtils.isEmpty(sourceRelationInfoList)){
                        for (SourceRelationInfo sourceRelationInfo:sourceRelationInfoList){
                            //实际重量
                            sourceRelationInfo.setActualOutWarehouseWeight(sourceRelationInfo.getActualOutWarehouseWeight()+Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()*sourceRelationInfo.getProportion())));
                            //剩余重量
                            sourceRelationInfo.setSurplusWeight(sourceRelationInfo.getSurplusWeight()-Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()*sourceRelationInfo.getProportion())));
                            sourceRelationInfoService.updateById(sourceRelationInfo);
                        }
                    }
                    //可超出重量
                    Float overNeight = 0.0f;
                    ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                            .eq("comp_id", inOutWarehouseTask.getCompId())
                            .eq("contract_no", inOutWarehouseTask.getContractNo()));
                    //出入库有合同
                    if (contractManagementInfo != null) {
                        overNeight = inOutWarehouseTask.getWeight() * (contractManagementInfo.getOverShort() / 100);
                    }
                    //出库无合同情况
                    else if (contractManagementInfo == null &&"1".equals(inOutWarehouseTask.getInOutFlag())) {
                        overNeight = inOutWarehouseTask.getWeight() * 0.05f;
                    } else {
                        contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("comp_id", inOutWarehouseTask.getCompId())
                                .eq("contract_no", inOutWarehouseTask.getWarehouseName()));
                        //移库入库
                        if (contractManagementInfo == null && "2".equals(inOutWarehouseTask.getInOutFlag())) {
                            overNeight = inOutWarehouseTask.getWeight() * 0.08f;
                        }
                    }
                    inOutWarehouseTask.setCompletedQuantity(inOutWarehouseTask.getCompletedQuantity() + warehouseInOutInfo.getNetWeight());
                    if (inOutWarehouseTask.getCompletedQuantity() > inOutWarehouseTask.getWeight() + overNeight) {
                        throw new YException(YExceptionEnum.TASK_WEIGHT_EXCEEDED_ERROR);
                    } else {
                        inOutWarehouseTaskService.updateById(inOutWarehouseTask);
                    }
                }
                warehouseInOutInfo.setInOutDate(new Date());
                warehouseInOutInfo.setStatusFlag(StatusEnum.SUBMITTED.getFlag());
                warehouseInOutInfo.setStatus(StatusEnum.SUBMITTED.getName());
                this.updateById(warehouseInOutInfo);
                warehouseInOutDetailService.updateById(warehouseInOutDetail);
            }
            // 采购订单
            PurchaseOrder purchaseOrder = purchaseOrderService.selectOne(new EntityWrapper<PurchaseOrder>().eq("contract_no", warehouseInOutInfo.getContractNo())
                    .eq("delete_flag", "0"));
            // 销售订单
            SaleOrder saleOrder = saleOrderService.selectOne(new EntityWrapper<SaleOrder>().eq("contract_no", warehouseInOutInfo.getContractNo())
                    .eq("delete_flag", "0"));
            //APP线上订单
            if (purchaseOrder != null || saleOrder != null) {
                // 先删除任务
                noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "INOUTTASK-TASK-APPROVE",
                        warehouseInOutInfo.getId(), null);
                //APP线上订单入库
                if ("2".equals(warehouseInOutInfo.getInOutFlag())) {
                    TranCarInfo tranCarInfo = tranCarInfoService.selectOne(new EntityWrapper<TranCarInfo>()
                            .eq("contract_no", warehouseInOutInfo.getContractNo())
                            .eq("car_no", warehouseInOutInfo.getCarNo())
                            .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0));
                    // 合同表
                    ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>().eq("contract_no", warehouseInOutInfo.getContractNo())
                            .eq("delete_flag", "0"));
                    //更新库存量
                    if (warehouseBaseInfo != null) {
                        float original = 0f;
                        //  查询库位
                        WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectById(warehouseInOutInfo.getPositionId());
                        if (warehousePositionInfo != null) {
                            // 查询货物库存量
                            WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                                    .eq("position_id", warehouseInOutInfo.getPositionId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName())
                                    .eq("delete_flag", "0"));
                            // 判断是否有货
                            if (warehousePositionStorageInfo != null) {
                                original = Float.valueOf(String.valueOf(warehousePositionStorageInfo.getStorage() + warehouseInOutInfo.getNetWeight()));
                                ;
                                // 更新库存量
                                warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
                            }
                            // 没有货
                            else {
                                original = 0f;
                                WarehousePositionStorageInfo warehousePositionStorageInfo1 = new WarehousePositionStorageInfo();
                                warehousePositionStorageInfo1.setId(IdGenerator.generateUUID());
                                warehousePositionStorageInfo1.setPositionId(warehouseInOutInfo.getPositionId());
                                warehousePositionStorageInfo1.setBinNumber(warehouseInOutInfo.getBinNumber());
                                warehousePositionStorageInfo1.setGoodsName(warehouseInOutInfo.getGoodsName());
                                warehousePositionStorageInfo1.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
                                warehousePositionStorageInfo1.setStorage(warehouseInOutInfo.getNetWeight());
                                warehousePositionStorageInfoService.insert(warehousePositionStorageInfo1);
                            }
                        }
//                    // 生成加权成本数据
//                    WeightedDetails weightedDetails = new WeightedDetails();
//                    weightedDetails.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
//                    weightedDetails.setId(IdGenerator.generateUUID());
//                    weightedDetails.setWarehouseId(warehouseInOutInfo.getBaseId());
//                    weightedDetails.setWarehouseName(warehouseInOutInfo.getWarehouseName());
//                    weightedDetails.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
//                    weightedDetails.setGoodsName(warehouseInOutInfo.getGoodsName());
//                    weightedDetails.setGrainType(warehouseInOutInfo.getType());
//                    weightedDetails.setInTypeKey(warehouseInOutInfo.getTaskTypeKey());
//                    weightedDetails.setInType(warehouseInOutInfo.getTaskType());
//                    weightedDetails.setNetWeight(warehouseInOutInfo.getNetWeight());
//                    weightedDetails.setPureWeight(warehouseInOutInfo.getPureWeight());
//                    weightedDetails.setUnitPrice(warehouseInOutInfo.getUnitPrice());
//                    weightedDetails.setDeductionAmount(warehouseInOutInfo.getDeductionAmount());
//                    weightedDetails.setFreight(warehouseInOutInfo.getFreight());
//                    weightedDetails.setOriginalStock(original);
//                    // 查询入库全加权成本
//                    List<WeightedDetails> weightedDetailsList = weightedDetailsService.selectList(new EntityWrapper<WeightedDetails>().eq("warehouse_id", warehouseInOutInfo.getWarehouseName())
//                            .eq("goods_name_key", warehouseInOutInfo.getGoodsNameKey()).orderBy("update_date", false));
//                    if (CollectionUtils.isEmpty(weightedDetailsList)) {
//                        weightedDetails.setCostBefore(0f);
//                    } else {
//                        weightedDetails.setCostBefore(weightedDetailsList.get(0).getCostBefore());
//                    }
//                    // 计算新加权成本
//                    Float newCost = 0f;
//                    if ("干粮".equals(warehouseInOutInfo.getType())) {
//                        newCost = ((warehouseInOutInfo.getCost() + warehouseInOutInfo.getFreight()) * warehouseInOutInfo.getNetWeight() + original * weightedDetails.getCostBefore()) / (warehouseInOutInfo.getNetWeight() + original);
//
//                    } else {
//                        newCost = ((warehouseInOutInfo.getCost() + warehouseInOutInfo.getFreight()) * warehouseInOutInfo.getNetWeight() + original * weightedDetails.getCostBefore()) / (warehouseInOutInfo.getPureWeight() + original);
//
//                    }
//                    weightedDetails.setCostAfter(newCost);
//                    weightedDetailsService.insert(weightedDetails);
//                    // 修改成本信息表
//                    CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", weightedDetails.getWarehouseId())
//                            .eq("goods_name_key", weightedDetails.getGoodsNameKey()));
//                    List<WeightedDetails> weightedDetailsLists = weightedDetailsService.selectList(new EntityWrapper<WeightedDetails>().eq("warehouse_id", warehouseInOutInfo.getWarehouseName())
//                            .eq("goods_name_key", warehouseInOutInfo.getGoodsNameKey()).orderBy("update_date", false));
//                    Float net = 0f;
//                    for(int i=0;i<weightedDetailsLists.size();i++){
//                        net = net +weightedDetailsLists.get(i).getNetWeight();
//                    }
//                    if(costManagementInfo ==null){
//                        CostManagementInfo costManagementInfo1= new CostManagementInfo();
//                        costManagementInfo1.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
//                        costManagementInfo1.setId(IdGenerator.generateUUID());
//                        costManagementInfo1.setWarehouseId(weightedDetails.getWarehouseId());
//                        costManagementInfo1.setWarehouseName(weightedDetails.getWarehouseName());
//                        costManagementInfo1.setGoodsNameKey(weightedDetails.getGoodsNameKey());
//                        costManagementInfo1.setGoodsName(weightedDetails.getGoodsName());
//                        costManagementInfo1.setWarehouseType(warehouseBaseInfo.getWarehouseType());
//
//                        costManagementInfo1.setStorage(net);
//                        costManagementInfo1.setCost(weightedDetails.getCostAfter());
//                        costManagementInfoService.insert(costManagementInfo1);
//                    }
//                    else{
//                        costManagementInfo.setCost(weightedDetails.getCostAfter());
//                        costManagementInfo.setStorage(net);
//                        costManagementInfoService.updateById(costManagementInfo);
//                    }
                    }
                    // 期货采购入库统计
                    if (contractManagementInfo != null && "2".equals(contractManagementInfo.getGoodsType())) {
                        PurchaseReceiptReport purchaseReceiptReport = new PurchaseReceiptReport();
                        purchaseReceiptReport.setId(IdGenerator.generateUUID());
                        purchaseReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                        purchaseReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                        purchaseReceiptReport.setGoodsName(warehouseInOutInfo.getGoodsName());
                        purchaseReceiptReport.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
                        purchaseReceiptReport.setPositionNumber(warehouseInOutInfo.getBinNumber());
                        purchaseReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                        purchaseReceiptReport.setTranCarNo(warehouseInOutInfo.getTranCarNo());
                        purchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                        purchaseReceiptReport.setProtein(warehouseInOutDetail.getProtein());
                        purchaseReceiptReport.setWaterContent(warehouseInOutDetail.getWaterContent());
                        purchaseReceiptReport.setDeductionAmount(warehouseInOutInfo.getDeductionAmount());
                        purchaseReceiptReport.setNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        purchaseReceiptReport.setDeductionItems(warehouseInOutInfo.getDeductionItems());
                        purchaseReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                        purchaseReceiptReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                        purchaseReceiptReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
                        if (purchaseOrder != null) {
                            purchaseReceiptReport.setUnitPrice(purchaseOrder.getUnitPrice());
                            purchaseReceiptReport.setUnloadingCharge(purchaseOrder.getUnloadingCharge());
                            purchaseReceiptReport.setInvoiceFee(purchaseOrder.getInvoiceFee());
                            //期货
                            if (purchaseOrder.getBasis() != null) {
                                purchaseReceiptReport.setBasisPrice(purchaseOrder.getBasis());
                                BigDecimal unitPrice = new BigDecimal(Float.toString(purchaseReceiptReport.getUnitPrice()));
                                BigDecimal basis = new BigDecimal(Float.toString(purchaseReceiptReport.getBasisPrice()));
                                BigDecimal unloadingCharge = new BigDecimal(Float.toString(purchaseReceiptReport.getUnloadingCharge()));
                                BigDecimal invoiceFee = new BigDecimal(Float.toString(purchaseReceiptReport.getInvoiceFee()));
                                BigDecimal deductionAmount = new BigDecimal(purchaseReceiptReport.getDeductionAmount());
                                purchaseReceiptReport.setSettlementPrice(unitPrice.add(basis).add(unloadingCharge).add(invoiceFee).add(deductionAmount).floatValue());
                            }
                            purchaseReceiptReport.setCustomerName(purchaseOrder.getSeller());
                            purchaseReceiptReport.setInvoiceType(purchaseOrder.getType());
                            purchaseReceiptReport.setInvoiceTypeKey(purchaseOrder.getType());
                            purchaseReceiptReport.setAmountIngPayable(CalculationUtil.mulToFloat(purchaseReceiptReport.getSettlementPrice(), purchaseReceiptReport.getNetWeight()));
                            purchaseReceiptReport.setAmountEdPayable(0f);
                            purchaseReceiptReport.setAmountNotPayable(purchaseReceiptReport.getAmountIngPayable());
                            if (tranCarInfo != null) {
                                //将到货数据同步到派车表
                                tranCarInfo.setUnloadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                tranCarInfo.setUnloadPoundImg(warehouseInOutInfo.getAddressUrl());
                                tranCarInfo.setDeductionAmount(warehouseInOutInfo.getDeductionAmount());
                                tranCarInfo.setDeductionItems(warehouseInOutInfo.getDeductionItems());
                                tranCarInfo.setStatus(StatusEnum.DELIVERED.getName());
                                tranCarInfo.setStatusFlag(StatusEnum.DELIVERED.getFlag());
                                if (purchaseOrder != null) {
                                    tranCarInfo.setSettlementPrice(purchaseReceiptReport.getSettlementPrice());
                                }
                                tranCarInfoService.updateById(tranCarInfo);
                            }
                        }
                        // 客户确认
                        TranCarInfo tranCarInfo1 = tranCarInfoService.selectOne(new EntityWrapper<TranCarInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("car_no", warehouseInOutInfo.getCarNo())
                                .eq("delete_flag", "0"));
                        if (tranCarInfo1 != null && "3".equals(tranCarInfo1.getConfirmFlag())) {
                            purchaseReceiptReport.setCustomerConfirmationStatusFlag("1");
                            purchaseReceiptReport.setCustomerConfirmationStatus("是");
                            tesk(warehouseInOutInfo, "2");
                            geTuiUtils.pushByCid("卸货提醒", "您的合同车辆：" + warehouseInOutInfo.getCarNo() + "申请卸货，请及时确认", purchaseOrder.getCommonId());

                            UnimallMessage messageDO = new UnimallMessage();
                            messageDO.setAdminId(purchaseOrder.getCommonId());
                            messageDO.setCustomer(purchaseOrder.getCustomer());
                            messageDO.setOperation("卸货提醒");
                            messageDO.setResult("您的合同车辆：" + warehouseInOutInfo.getCarNo() + "申请卸货，请及时确认");
                            messageDO.setGmtUpdate(new java.util.Date());
                            messageDO.setGmtCreate(new Date());
                            messageDO.setTaskId(IdGenerator.generateUUID());
                            messageDO.setCompanyId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                            messageDO.setPath("XXXXX");
                            webSocket.sendOneMessage(messageDO);
                        } else {
                            purchaseReceiptReport.setCustomerConfirmationStatusFlag("3");
                            purchaseReceiptReport.setCustomerConfirmationStatus("否");
                        }
                        purchaseReceiptReportService.insert(purchaseReceiptReport);
                        boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(purchaseReceiptReport.getWorkflowId());
                        // 不是退回的单子
                        if (isStartWorkflow) {
                            Workflow workflow = workflowService
                                    .findLatestWorkflowByBusinessCodeByApp(purchaseReceiptReport.getCompId(), "PROCUREMENT-RECEIPT-REPORT");
                            // 没配置审核流程，直接结束并处理信息
                            if (workflow == null) {
                                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                            }
                            // 开启审核流
                            else {
                                // 设置状态 已提交审核
                                purchaseReceiptReport.setWorkflowId(workflow.getId());
                                purchaseReceiptReportService.updateById(purchaseReceiptReport);
                                workflowService.startInstance(workflow.getId(), purchaseReceiptReport.getId());
                            }
                        }
                        // 退回的单子 再启用
                        else {
                            purchaseReceiptReportService.updateById(purchaseReceiptReport);
                            workflowService.activateInstance(purchaseReceiptReport.getWorkflowId(), purchaseReceiptReport.getId());
                        }
                    }
                }
                //App线上订单出库
                else if ("1".equals(warehouseInOutInfo.getTaskType())) {
                    //状态改为已发车
                    warehouseInOutInfo.setTranFlag("1");

                    //判断是否第一次提交
                    if (StringUtils.isEmpty(warehouseInOutDetail.getId())) {
                        // 插入详情
                        warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
                        warehouseInOutDetail.setId(IdGenerator.generateUUID());
                        List<WarehouseInOutDetail> ll = warehouseInOutDetailService.selectList(new EntityWrapper<WarehouseInOutDetail>().eq("info_id", warehouseInOutInfo.getId()));
                        if (ll.size() == 0) {
                            warehouseInOutDetailService.insert(warehouseInOutDetail);
                        }
                    }
                    //更新库存量
                    //判断是否有货
                    if (warehouseBaseInfo != null) {
                        //  查询库位
                        WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectById(warehouseInOutInfo.getPositionId());
                        if (warehousePositionInfo != null) {
                            // 查询货物库存量
                            WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                                    .eq("position_id", warehouseInOutInfo.getPositionId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName())
                                    .eq("delete_flag", "0"));
                            // 判断是否有货
                            if (warehousePositionStorageInfo != null) {
                                if (warehouseInOutInfo.getNetWeight() <= warehousePositionStorageInfo.getStorage()) {
                                    // 更新库存量
                                    warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() - Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
                                }
                                //出库量大于库存量
                                else {
                                    throw new YException(YExceptionEnum.INVENTORY_NO_ERROR);
                                }
                            }
                            // 没有储存量
                            else {
                                throw new YException(YExceptionEnum.POSITIONSTORAGE_NO_ERROR);
                            }
                        }
                        //库位不存在
                        else {
                            throw new YException(YExceptionEnum.POSITION_NO_ERROR);
                        }
                    }
                    //仓库不存在
                    else {
                        throw new YException(YExceptionEnum.WAREHOUSE_NO_ERROR);
                    }
                    //查询期货现货合同
                    ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                            .eq("contract_no", warehouseInOutInfo.getContractNo()));
                    if (contractManagementInfo != null && "2".equals(contractManagementInfo.getGoodsType())) {
                        //客户生成收货信息
                        TranCarInfo tranCarInfo = new TranCarInfo();
                        tranCarInfo.setId(IdGenerator.generateUUID());
                        tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                        tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                        tranCarInfo.setTranCarNo(warehouseInOutInfo.getTranCarNo());
                        tranCarInfo.setLoadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        tranCarInfo.setLoadPoundImg(warehouseInOutInfo.getAddressUrl());
                        tranCarInfo.setConfirmFlag(StatusEnum.NOT_CONFIRM.getFlag());
                        // 期货销售出库统计
                        SalesDeliveryReport salesDeliveryReport = new SalesDeliveryReport();
                        salesDeliveryReport.setId(IdGenerator.generateUUID());
                        salesDeliveryReport.setCompId(warehouseBaseInfo.getCompId());
                        salesDeliveryReport.setContractNo(warehouseInOutInfo.getContractNo());
                        salesDeliveryReport.setGoodsName(warehouseInOutInfo.getGoodsName());
                        salesDeliveryReport.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
                        salesDeliveryReport.setPositionNumber(warehouseInOutInfo.getBinNumber());
                        salesDeliveryReport.setCarNo(warehouseInOutInfo.getCarNo());
                        salesDeliveryReport.setTranCarNo(warehouseInOutInfo.getTranCarNo());
                        salesDeliveryReport.setRetrievalDate(warehouseInOutInfo.getInOutDate());
                        salesDeliveryReport.setProtein(warehouseInOutDetail.getProtein());
                        salesDeliveryReport.setWaterContent(warehouseInOutDetail.getWaterContent());
                        salesDeliveryReport.setNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        salesDeliveryReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                        salesDeliveryReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                        salesDeliveryReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
                        if (saleOrder != null) {
                            salesDeliveryReport.setUnitPrice(saleOrder.getUnitPrice());
                            salesDeliveryReport.setInvoiceFee(saleOrder.getInvoiceFee());
                            //期货
                            if (saleOrder.getBasis() != null) {
                                salesDeliveryReport.setBasisPrice(saleOrder.getBasis());
                                BigDecimal unitPrice = new BigDecimal(Float.toString(salesDeliveryReport.getUnitPrice()));
                                BigDecimal basis = new BigDecimal(Float.toString(salesDeliveryReport.getBasisPrice()));
                                BigDecimal invoiceFee = new BigDecimal(Float.toString(salesDeliveryReport.getInvoiceFee()));
                                salesDeliveryReport.setSettlementPrice(unitPrice.add(basis).add(invoiceFee).floatValue());
                                tranCarInfo.setSettlementPrice(saleOrder.getUnitPrice() + saleOrder.getBasis() + saleOrder.getInvoiceFee());
                            }
                            salesDeliveryReport.setCustomerName(saleOrder.getBuyer());
                            salesDeliveryReport.setCollectionIngPayable(CalculationUtil.mulToFloat(salesDeliveryReport.getSettlementPrice(), salesDeliveryReport.getNetWeight()));
                            salesDeliveryReport.setCollectionEdPayable(0f);
                            salesDeliveryReport.setCollectionNotPayable(salesDeliveryReport.getCollectionIngPayable());
                            tranCarInfoService.insert(tranCarInfo);
                        }

                        // 客户确认
                        TranCarInfo tranCarInfo1 = tranCarInfoService.selectOne(new EntityWrapper<TranCarInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("car_no", warehouseInOutInfo.getCarNo())
                                .eq("delete_flag", "0"));
                        if (tranCarInfo1 != null && "3".equals(tranCarInfo1.getConfirmFlag())) {
                            salesDeliveryReport.setCustomerConfirmationStatusFlag("1");
                            salesDeliveryReport.setCustomerConfirmationStatus("是");
                            geTuiUtils.pushByCid("发货通知", "您的合同车辆：" + warehouseInOutInfo.getCarNo() + "已发出", saleOrder.getCommonId());
                            tesk(warehouseInOutInfo, "1");
                            UnimallMessage messageDO = new UnimallMessage();
                            messageDO.setAdminId(saleOrder.getCommonId());
                            messageDO.setCustomer(saleOrder.getCustomer());
                            messageDO.setOperation("发货通知");
                            messageDO.setResult("您的合同车辆：" + warehouseInOutInfo.getCarNo() + "已发出");
                            messageDO.setGmtUpdate(new java.util.Date());
                            messageDO.setGmtCreate(new Date());
                            messageDO.setTaskId(IdGenerator.generateUUID());
                            messageDO.setCompanyId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                            messageDO.setPath("XXXXX");
                            webSocket.sendOneMessage(messageDO);
                        } else {
                            salesDeliveryReport.setCustomerConfirmationStatusFlag("3");
                            salesDeliveryReport.setCustomerConfirmationStatus("否");
                        }
                        salesDeliveryReportService.insert(salesDeliveryReport);

                        boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(salesDeliveryReport.getWorkflowId());
                        // 不是退回的单子
                        if (isStartWorkflow) {
                            Workflow workflow = workflowService
                                    .findLatestWorkflowByBusinessCodeByApp(salesDeliveryReport.getCompId(), "SALE-RECEIPT-REPORT");
                            // 没配置审核流程，直接结束并处理信息
                            if (workflow == null) {
                                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                            }
                            // 开启审核流
                            else {

                                // 设置状态 已提交审核
                                salesDeliveryReport.setWorkflowId(workflow.getId());
                                salesDeliveryReportService.updateById(salesDeliveryReport);
                                workflowService.startInstance(workflow.getId(), salesDeliveryReport.getId());
                            }
                        }
                        // 退回的单子 再启用
                        else {

                            salesDeliveryReportService.updateById(salesDeliveryReport);
                            workflowService.activateInstance(salesDeliveryReport.getWorkflowId(), salesDeliveryReport.getId());
                        }
                    }
                }
            }
            else {
                //常用库入库
                if ("2".equals(warehouseInOutInfo.getInOutFlag()) && "1".equals(warehouseBaseInfo.getWarehouseType())) {
                    //常用库采购入库类型
                    if ("1".equals(warehouseInOutInfo.getInOutTypeKey())) {
                        //他运的采购合同
                        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("deliver_type", "2")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo != null) {
                            //现货采购入库报表
                            StockPurchaseReceiptReport stockPurchaseReceiptReport = new StockPurchaseReceiptReport();
                            stockPurchaseReceiptReport.setId(IdGenerator.generateUUID());
                            stockPurchaseReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            stockPurchaseReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockPurchaseReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                            stockPurchaseReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockPurchaseReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            stockPurchaseReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockPurchaseReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockPurchaseReceiptReport.setNetWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            stockPurchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                            stockPurchaseReceiptReport.setDeductionWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getDeductionWeight())));
                            stockPurchaseReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            stockPurchaseReceiptReport.setDeductionAmount(warehouseInOutInfo.getDeductionAmount());

                            if (contractManagementInfo.getUnitContractPrice() != null) {
                                BigDecimal cost = new BigDecimal(contractManagementInfo.getUnitContractPrice());
                                BigDecimal deductionAmount = new BigDecimal(warehouseInOutInfo.getDeductionAmount() != null ? warehouseInOutInfo.getDeductionAmount() : 0.0);
                                stockPurchaseReceiptReport.setSettlementPrice(cost.subtract(deductionAmount).doubleValue());
                                BigDecimal netWeight = new BigDecimal(warehouseInOutInfo.getNetWeight());
                                stockPurchaseReceiptReport.setAmountIngPayable(cost.subtract(deductionAmount).multiply(netWeight).doubleValue());
                            }
                            //随行就市
                            else {
                                BigDecimal cost = new BigDecimal(Float.toString(warehouseInOutInfo.getCost()));
                                BigDecimal deductionAmount = new BigDecimal(warehouseInOutInfo.getDeductionAmount() != null ? warehouseInOutInfo.getDeductionAmount() : 0.0);
                                stockPurchaseReceiptReport.setSettlementPrice(cost.subtract(deductionAmount).doubleValue());
                                BigDecimal netWeight = new BigDecimal(warehouseInOutInfo.getNetWeight());
                                stockPurchaseReceiptReport.setAmountIngPayable(cost.subtract(deductionAmount).multiply(netWeight).doubleValue());
                            }
                            stockPurchaseReceiptReport.setAmountEdPayable(0.0d);
                            stockPurchaseReceiptReport.setAmountNotPayable(stockPurchaseReceiptReport.getAmountIngPayable());
                            stockPurchaseReceiptReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                            stockPurchaseReceiptReport.setStatus(StatusEnum.FORM_REVIEWED.getName());

                            stockPurchaseReceiptReportService.insert(stockPurchaseReceiptReport);
                            boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(stockPurchaseReceiptReport.getWorkflowId());
                            // 不是退回的单子
                            if (isStartWorkflow) {
                                Workflow workflow = workflowService
                                        .findLatestWorkflowByBusinessCodeByApp(stockPurchaseReceiptReport.getCompId(), "STOCK-PROCUREMENT-RECEIPT-REPORT");
                                // 没配置审核流程，直接结束并处理信息
                                if (workflow == null) {
                                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                }
                                // 开启审核流
                                else {
                                    // 设置状态 已提交审核
                                    stockPurchaseReceiptReport.setWorkflowId(workflow.getId());
                                    stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                    workflowService.startInstance(workflow.getId(), stockPurchaseReceiptReport.getId());
                                }
                            }
                            // 退回的单子 再启用
                            else {
                                stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                workflowService.activateInstance(stockPurchaseReceiptReport.getWorkflowId(), stockPurchaseReceiptReport.getId());
                            }
                        }
                    }
                    //常用库移库入库类型
                    else if ("3".equals(warehouseInOutInfo.getInOutTypeKey())) {
                        InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                .eq("move_task_no", warehouseInOutInfo.getContractNo())
                                .eq("in_out_flag", "1")
                                .eq("delete_flag", "0"));
                        if (inOutWarehouseTask == null) {
                            throw new YException(YExceptionEnum.TASK_NO_NOT_EXSITS_ERROR);
                        } else {
                            //若移库的发货库为自动创建的临时库时
                            WarehouseBaseInfo warehouseBaseInfo1 = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                                    .eq("warehouse_name", inOutWarehouseTask.getWarehouseName())
                                    .eq("create_type", "1")
                                    .eq("warehouse_type", "2")
                                    .eq("delete_flag", "0"));
                            if (warehouseBaseInfo1 != null) {
                                //按入库重量结算
                                ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                        .eq("contract_no", warehouseBaseInfo1.getWarehouseName())
                                        .eq("settlement_weight_method", "2")
                                        .eq("deliver_type", "1")
                                        .eq("delete_flag", "0"));
//                                if (contractManagementInfo == null) {
//                                    throw new YException(YExceptionEnum.CONTRACT_NO_NOT_EXSITS_ERROR);
//                                }
                                if (contractManagementInfo != null) {
                                    //现货采购入库报表
                                    StockPurchaseReceiptReport stockPurchaseReceiptReport = new StockPurchaseReceiptReport();
                                    stockPurchaseReceiptReport.setId(IdGenerator.generateUUID());
                                    stockPurchaseReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                                    stockPurchaseReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                                    stockPurchaseReceiptReport.setContractNo(warehouseBaseInfo1.getWarehouseName());
                                    stockPurchaseReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                                    stockPurchaseReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                    stockPurchaseReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                                    stockPurchaseReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                                    stockPurchaseReceiptReport.setNetWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    stockPurchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                                    stockPurchaseReceiptReport.setDeductionWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getDeductionWeight())));
                                    stockPurchaseReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    if (contractManagementInfo.getUnitContractPrice() != null) {
                                        BigDecimal cost = new BigDecimal(contractManagementInfo.getUnitContractPrice());
                                        BigDecimal deductionAmount = new BigDecimal(warehouseInOutInfo.getDeductionAmount() != null ? warehouseInOutInfo.getDeductionAmount() : 0.0);
                                        stockPurchaseReceiptReport.setSettlementPrice(cost.subtract(deductionAmount).doubleValue());
                                        BigDecimal netWeight = new BigDecimal(warehouseInOutInfo.getNetWeight());
                                        stockPurchaseReceiptReport.setAmountIngPayable(cost.subtract(deductionAmount).multiply(netWeight).doubleValue());
                                    }
                                    //随行就市
                                    else {
                                        BigDecimal cost = new BigDecimal(warehouseInOutInfo.getCost());
                                        BigDecimal deductionAmount = new BigDecimal(warehouseInOutInfo.getDeductionAmount() != null ? warehouseInOutInfo.getDeductionAmount() : 0.0);
                                        stockPurchaseReceiptReport.setSettlementPrice(cost.subtract(deductionAmount).doubleValue());
                                        BigDecimal netWeight = new BigDecimal(warehouseInOutInfo.getNetWeight());
                                        stockPurchaseReceiptReport.setAmountIngPayable(cost.subtract(deductionAmount).multiply(netWeight).doubleValue());
                                    }
                                    stockPurchaseReceiptReport.setAmountEdPayable(0.0d);
                                    stockPurchaseReceiptReport.setAmountNotPayable(stockPurchaseReceiptReport.getAmountIngPayable());
                                    stockPurchaseReceiptReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                                    stockPurchaseReceiptReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
                                    stockPurchaseReceiptReportService.insert(stockPurchaseReceiptReport);
                                    boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(stockPurchaseReceiptReport.getWorkflowId());
                                    // 不是退回的单子
                                    if (isStartWorkflow) {
                                        Workflow workflow = workflowService
                                                .findLatestWorkflowByBusinessCodeByApp(stockPurchaseReceiptReport.getCompId(), "STOCK-PROCUREMENT-RECEIPT-REPORT");
                                        // 没配置审核流程，直接结束并处理信息
                                        if (workflow == null) {
                                            throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                        }
                                        // 开启审核流
                                        else {
                                            // 设置状态 已提交审核
                                            stockPurchaseReceiptReport.setWorkflowId(workflow.getId());
                                            stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                            workflowService.startInstance(workflow.getId(), stockPurchaseReceiptReport.getId());
                                        }
                                    }
                                    // 退回的单子 再启用
                                    else {
                                        stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                        workflowService.activateInstance(stockPurchaseReceiptReport.getWorkflowId(), stockPurchaseReceiptReport.getId());
                                    }
                                }
                            }
                            //常用库之间移库
//                            else{
//                                //查收货库
//                                InOutWarehouseTask inOutWarehouseTask1 = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
//                                        .eq("relevance_id", inOutWarehouseTask.getRelevanceId())
//                                        .eq("in_out_flag", "2")
//                                        .eq("delete_flag", "0"));
//                                //更新所在仓库收购库存
//                                ContractInventoryDistribution contractInventoryDistribution1=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
//                                        .eq("comp_id",inOutWarehouseTask1.getCompId()).eq("inventory_type","3").eq("warehouse",inOutWarehouseTask.getWarehouseName())
//                                        .eq("locus_warehouse",inOutWarehouseTask1.getWarehouseName())
//                                        .eq("goods_name",warehouseInOutInfo.getGoodsName()));
//                                if (contractInventoryDistribution1!=null){
//                                    contractInventoryDistribution1.setInventory(contractInventoryDistribution1.getInventory()+warehouseInOutInfo.getNetWeight());
//                                    contractInventoryDistributionService.updateById(contractInventoryDistribution1);
//                                }
//                                else {
//                                    ContractInventoryDistribution contractInventoryDistribution2=new ContractInventoryDistribution();
//                                    contractInventoryDistribution2.setId(IdGenerator.generateUUID());
//                                    contractInventoryDistribution2.setCompId(inOutWarehouseTask.getCompId());
//                                    //所属仓库  发货库
//                                    contractInventoryDistribution2.setWarehouse(inOutWarehouseTask.getWarehouseName());
//                                    contractInventoryDistribution2.setInventory(warehouseInOutInfo.getNetWeight());
//                                    //所在仓库  收货
//                                    contractInventoryDistribution2.setLocusWarehouse(inOutWarehouseTask1.getWarehouseName());
//                                    contractInventoryDistribution2.setGoodsName(warehouseInOutInfo.getGoodsName());
//                                    contractInventoryDistribution2.setInventoryType("3");
//                                    contractInventoryDistributionService.insert(contractInventoryDistribution2);
//
//                                }
//                            }
                        }
                        //入库时更新汽运报表卸车数据
                        TranSettlementReport tranSettlementReport = tranSettlementReportService.selectOne(new EntityWrapper<TranSettlementReport>()
                                .eq("car_id", warehouseInOutInfo.getCarId()));
                        if (tranSettlementReport!=null) {
                            tranSettlementReport.setUnloadingWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            tranSettlementReport.setUnloadingImg(warehouseInOutInfo.getAddressUrl());
                                //损耗
                            tranSettlementReport.setLossWeight(tranSettlementReport.getLoadingWeight() - tranSettlementReport.getUnloadingWeight());
                                //汽运类型
                                if (tranSettlementReport.getTranTypeKey().equals(NumberConstant.CONSTANT1)) {
                                    //结算重量
                                    if ("0".equals(tranSettlementReport.getManualFlag())) {
                                        //卸车不为空时，结算重量=装卸取小
                                        tranSettlementReport.setSettlementWeight(tranSettlementReport.getLoadingWeight() > tranSettlementReport.getUnloadingWeight() ? tranSettlementReport.getUnloadingWeight() : tranSettlementReport.getLoadingWeight());
                                    }
                                    if (tranSettlementReport.getTransportPrice()!=null) {
                                        //扣款
                                        if (tranSettlementReport.getLossWeight() <= (tranSettlementReport.getLoadingWeight() / 1000)) {
                                            tranSettlementReport.setDeductionAmount("0");
                                            //应付=单价x结算重量-扣款
                                            tranSettlementReport.setAmountIngPayable(tranSettlementReport.getTransportPrice() * tranSettlementReport.getSettlementWeight());
                                        } else {
                                            tranSettlementReport.setDeductionAmount(String.format("%.2f", (Float.valueOf(tranSettlementReport.getLoadingWeight() - tranSettlementReport.getUnloadingWeight()) - (tranSettlementReport.getLoadingWeight() / 1000)) * Float.valueOf(tranSettlementReport.getTransportPrice())));
                                            //应付=单价x结算重量-扣款
                                            tranSettlementReport.setAmountIngPayable(tranSettlementReport.getTransportPrice() * tranSettlementReport.getSettlementWeight() - Float.valueOf(tranSettlementReport.getDeductionAmount()));
                                        }
                                    }
                                }
                                tranSettlementReportService.updateById(tranSettlementReport);
                        }
                    }

                    //常用库退库入库类型
                    else if ("退库".equals(warehouseInOutInfo.getInOutType())) {
                        warehouseInOutInfo.setReturnTickFlag("2");
                        //检斤表
                        WeighingManagement weighingManagement = weighingManagementService.selectOne(new EntityWrapper<WeighingManagement>()
                                .eq("warehouse_in_out_id", warehouseInOutInfo.getId())
                                .eq("delete_flag", "0"));
                        //他运的销售合同
                        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("deliver_type", "2")
                                .eq("contract_type", "1")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo != null) {
                            //现货销售出库报表
                            StockSaleReceiptReport stockSaleReceiptReport = new StockSaleReceiptReport();
                            stockSaleReceiptReport.setId(IdGenerator.generateUUID());
                            stockSaleReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            stockSaleReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockSaleReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                            stockSaleReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            stockSaleReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockSaleReceiptReport.setNetWeight(-warehouseInOutInfo.getNetWeight());
                            stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(weighingManagement.getContractPrice())));
                            stockSaleReceiptReport.setReturnDate(warehouseInOutInfo.getInOutDate());
                            stockSaleReceiptReport.setAmountIngReceivable(-warehouseInOutInfo.getNetWeight() * (Double.valueOf(String.valueOf(weighingManagement.getContractPrice()))));
                            stockSaleReceiptReport.setSettlementWeight(-warehouseInOutInfo.getNetWeight());
                            stockSaleReceiptReport.setReturnFlag("1");
                            stockSaleReceiptReport.setStatusFlag(StatusEnum.TO_BE_RECEIVED.getFlag());
                            stockSaleReceiptReport.setStatus(StatusEnum.TO_BE_RECEIVED.getName());
                            stockSaleReceiptReport.setSettlementWeight(stockSaleReceiptReport.getNetWeight());
                            CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId()));
                            if (costManagementInfo != null) {
                                stockSaleReceiptReport.setCost(costManagementInfo.getCost());

                            }
                            stockSaleReceiptReportService.insert(stockSaleReceiptReport);
                        }
                        //自运的销售合同
                        ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("contract_type", "1")
                                .eq("deliver_type", "1")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo1 != null) {
                            //现货销售出库报表
                            StockSaleReceiptReport stockSaleReceiptReport = new StockSaleReceiptReport();
                            stockSaleReceiptReport.setId(IdGenerator.generateUUID());
                            stockSaleReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockSaleReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            stockSaleReceiptReport.setProcessNo("退库");
                            stockSaleReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                            stockSaleReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            stockSaleReceiptReport.setTranCarNo(warehouseInOutInfo.getTranCarNo());
                            stockSaleReceiptReport.setCaseNo(warehouseInOutInfo.getBoxNo() + "," + warehouseInOutInfo.getBoxNoOther());
                            stockSaleReceiptReport.setTitleNo(warehouseInOutInfo.getTitleNo());
                            stockSaleReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockSaleReceiptReport.setNetWeight(-warehouseInOutInfo.getNetWeight());
                            stockSaleReceiptReport.setReturnDate(warehouseInOutInfo.getInOutDate());
                            stockSaleReceiptReport.setAmountIngReceivable(-warehouseInOutInfo.getNetWeight() * (Double.valueOf(String.valueOf(weighingManagement.getContractPrice()==null?0:weighingManagement.getContractPrice()))));
                            stockSaleReceiptReport.setSettlementWeight(-warehouseInOutInfo.getNetWeight());
                            stockSaleReceiptReport.setReturnFlag("1");
                            stockSaleReceiptReport.setStatusFlag(StatusEnum.TO_BE_RECEIVED.getFlag());
                            stockSaleReceiptReport.setStatus(StatusEnum.TO_BE_RECEIVED.getName());
                            stockSaleReceiptReport.setSettlementWeight(stockSaleReceiptReport.getNetWeight());
                            CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId()));
                            if (costManagementInfo != null) {
                                stockSaleReceiptReport.setCost(costManagementInfo.getCost());

                            }
                            stockSaleReceiptReportService.insert(stockSaleReceiptReport);
                        }
                    }
                    if (warehouseInOutInfo.getWeighingManagement() != null) {
                        //皮重检斤
                        WeighingManagement weighingManagement = warehouseInOutInfo.getWeighingManagement();
                        WeighingManagement weighingManagement1 = weighingManagementService.selectById(weighingManagement.getId());
                        //状态改为已称皮重
                        weighingManagement.setStatus(StatusEnum.TARED.getName());
                        weighingManagement.setStatusFlag(StatusEnum.TARED.getFlag());
                        weighingManagement.setTareDate(new Date());
                        weighingManagement.setSkinInspector(commonStaff.getStaffName());
                        //质检信息
                        QualityInspectionManagement qualityInspectionManagement1 = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                                .eq("relation_id", weighingManagement1.getRelationId())
                                .eq("comp_id", weighingManagement1.getCompId()));
                        if (qualityInspectionManagement1 != null) {
                            //状态改为已称皮重
//                      qualityInspectionManagement1.setStatus(StatusEnum.TARED.getName());
//                      qualityInspectionManagement1.setStatusFlag(StatusEnum.TARED.getFlag());
                            qualityInspectionManagementService.updateById(qualityInspectionManagement1);
                        }
                        //收购业务
                        if ("1".equals(weighingManagement1.getManagementType()) && "3".equals(weighingManagement1.getServiceManagementType())) {
                            //查关联的付款信息
                            PaymentManagement paymentManagement = paymentManagementService.selectOne(new EntityWrapper<PaymentManagement>()
                                    .eq("relation_id", weighingManagement1.getRelationId())
                                    .eq("comp_id", weighingManagement1.getCompId()));
                            if (paymentManagement != null) {
                                paymentManagement.setNetWeight(weighingManagement.getNetWeight());
                                paymentManagement.setGrossWeight(weighingManagement1.getGrossWeight());
                                paymentManagement.setTare(weighingManagement.getTare());
                                paymentManagementService.updateById(paymentManagement);
                            } else {
                                //生成付款信息
                                PaymentManagement paymentManagement1 = new PaymentManagement();
                                paymentManagement1.setId(IdGenerator.generateUUID());
                                paymentManagement1.setRelationId(weighingManagement1.getRelationId());
                                paymentManagement1.setCompId(weighingManagement1.getCompId());
                                paymentManagement1.setCustomerNumberCard(weighingManagement1.getCustomerNumberCard());
                                paymentManagement1.setPaymentNo(weighingManagement1.getNumber());
                                paymentManagement1.setContractNo(weighingManagement1.getContractNo());
                                paymentManagement1.setCustomerName(weighingManagement1.getCustomer());
                                paymentManagement1.setCustomerPhone(weighingManagement1.getCustomerPhone());
                                paymentManagement1.setCarNo(weighingManagement1.getCarNumber());
                                paymentManagement1.setType(weighingManagement1.getType());
                                paymentManagement1.setGoodsName(weighingManagement1.getGoodsName());
                                paymentManagement1.setStatus(StatusEnum.TO_BE_SETTLED.getName());
                                paymentManagement1.setStatusFlag(StatusEnum.TO_BE_SETTLED.getFlag());
                                paymentManagement1.setNetWeight(weighingManagement.getNetWeight());
                                paymentManagement1.setManagementType("1");
                                paymentManagement1.setGrossWeight(weighingManagement1.getGrossWeight());
                                paymentManagement1.setTare(weighingManagement.getTare());
                                paymentManagement1.setWarehouseName(weighingManagement1.getWarehouseName());
                                //获取银行卡等相关信息
                                IdentityAuthenticationInfo identityAuthenticationInfo = identityAuthenticationInfoService.selectOne(new EntityWrapper<IdentityAuthenticationInfo>()
                                        .eq("comp_id", weighingManagement1.getCompId())
                                        .eq("customer_name",weighingManagement1.getCustomer())
                                        .eq("customer_phone",weighingManagement1.getCustomerPhone())
                                        .eq("delete_flag","0"));
                                if(identityAuthenticationInfo != null){
                                    paymentManagement1.setBankCard(identityAuthenticationInfo.getBankCard());
                                    paymentManagement1.setBankDeposit(identityAuthenticationInfo.getBankDeposit());
                                    paymentManagement1.setBankDepositBranch(identityAuthenticationInfo.getBankDepositBranch());
                                    paymentManagement1.setPayeeAddressUrl(identityAuthenticationInfo.getPayeeAddressUrl());
                                    paymentManagement1.setIdentityId(identityAuthenticationInfo.getId());
                                }
                                //质检信息
                                QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                                        .eq("relation_id", weighingManagement1.getRelationId())
                                        .eq("comp_id", weighingManagement1.getCompId()));
                                if (qualityInspectionManagement != null) {
                                    if ("潮粮".equals(weighingManagement1.getType())) {
                                        paymentManagement1.setTidalGrainPrice(qualityInspectionManagement.getTidalGrainPrice());
                                    } else {
                                        paymentManagement1.setTidalGrainPrice(qualityInspectionManagement.getDryGrainPrice());
                                    }
                                }
                                paymentManagementService.insert(paymentManagement1);
                            }
                        }
                        if (weighingManagement.getTare() == null || weighingManagement.getTare() == 0) {
                            throw new YException(YExceptionEnum.TARE_NULL);
                        }
                        weighingManagementService.updateById(weighingManagement);
                    }
                    Wrapper wrapper = new EntityWrapper<TranCarInfo>()
                            .eq("contract_no", warehouseInOutInfo.getContractNo())
                            .eq("car_no", warehouseInOutInfo.getCarNo())
                            .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                            .eq("tran_car_no", warehouseInOutInfo.getTranCarNo());
                    TranCarInfo tranCarInfo = tranCarInfoService.selectOne(wrapper);
                    if (tranCarInfo != null) {
                        //将到货数据同步到派车表
                        tranCarInfo.setUnloadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        if (warehouseInOutInfo.getAddressUrl() != null) {
                            tranCarInfo.setUnloadPoundImg(warehouseInOutInfo.getAddressUrl());
                        }
                        tranCarInfo.setUnloadingDate(warehouseInOutInfo.getInOutDate());
//                        if ("2".equals(tranCarInfo.getSubmit())) {
//                            throw new YException(YExceptionEnum.CARNO_SUBMITTED_ERROR);
//                        } else {
                        tranCarInfo.setSubmit("2");
                        tranCarInfo.setStatusFlag(StatusEnum.DELIVERED.getFlag());
                        tranCarInfo.setStatus(StatusEnum.DELIVERED.getName());
//                        }
                        tranCarInfoService.updateById(tranCarInfo);
                    }
                    //更新库存量
                    float original = 0f;
                    //判断是否有库
                    if (warehouseBaseInfo != null) {
                        //  查询库位
                        WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectById(warehouseInOutInfo.getPositionId());
                        if (warehousePositionInfo != null) {
                            // 查询货物库存量
                            WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                                    .eq("position_id", warehouseInOutInfo.getPositionId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName())
                                    .eq("delete_flag", "0"));
                            // 判断是否有货
                            if (warehousePositionStorageInfo != null) {
                                original = Float.valueOf(String.valueOf(warehousePositionStorageInfo.getStorage()));
                                // 更新库存量
                                warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
                            }
                            // 没有货
                            else {
                                WarehousePositionStorageInfo warehousePositionStorageInfo1 = new WarehousePositionStorageInfo();
                                warehousePositionStorageInfo1.setId(IdGenerator.generateUUID());
                                warehousePositionStorageInfo1.setPositionId(warehouseInOutInfo.getPositionId());
                                warehousePositionStorageInfo1.setBinNumber(warehouseInOutInfo.getBinNumber());
                                warehousePositionStorageInfo1.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
                                warehousePositionStorageInfo1.setGoodsName(warehouseInOutInfo.getGoodsName());
                                warehousePositionStorageInfo1.setStorage(warehouseInOutInfo.getNetWeight());
                                warehousePositionStorageInfoService.insert(warehousePositionStorageInfo1);
                            }
                        }
                    }

                    // 生成加权成本数据
                    WeightedDetails weightedDetails = new WeightedDetails();
                    weightedDetails.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                    weightedDetails.setId(IdGenerator.generateUUID());
                    weightedDetails.setWarehouseId(warehouseInOutInfo.getBaseId());
                    weightedDetails.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                    weightedDetails.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
                    weightedDetails.setGoodsName(warehouseInOutInfo.getGoodsName());
                    weightedDetails.setGrainType(warehouseInOutInfo.getType());
                    weightedDetails.setInTypeKey(warehouseInOutInfo.getInOutTypeKey());
                    weightedDetails.setInType(warehouseInOutInfo.getInOutType());
                    weightedDetails.setNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                    weightedDetails.setPureWeight(warehouseInOutInfo.getPureWeight());
                    weightedDetails.setUnitPrice(warehouseInOutInfo.getCost());
                    weightedDetails.setDeductionAmount(warehouseInOutInfo.getDeductionAmount());
                    weightedDetails.setFreight(warehouseInOutInfo.getFreight());
                    weightedDetails.setOriginalStock(original);
                    // 查询入库全加权成本
                    List<WeightedDetails> weightedDetailsList = weightedDetailsService.selectList(new EntityWrapper<WeightedDetails>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                            .eq("goods_name", warehouseInOutInfo.getGoodsName()).orderBy("update_date", false));

                    // 计算新加权成本
                    Double newCost = 0d;
                    if (CollectionUtils.isEmpty(weightedDetailsList)) {
                        if ("干粮".equals(warehouseInOutInfo.getType())) {
                            newCost = ((warehouseInOutInfo.getCost() / 1.09 + warehouseInOutInfo.getFreight()) * Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()))) / (Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())) + original);

                        } else {
                            newCost = ((warehouseInOutInfo.getCost() / 1.09 + warehouseInOutInfo.getFreight()) * Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()))) / (warehouseInOutInfo.getPureWeight() + original);

                        }
                        weightedDetails.setCostBefore(Float.valueOf(String.valueOf(newCost)));
                        weightedDetails.setCostAfter(newCost);
                    } else {
                        weightedDetails.setCostBefore(weightedDetailsList.get(0).getCostBefore());
                        if ("干粮".equals(warehouseInOutInfo.getType())) {
                            newCost = ((warehouseInOutInfo.getCost() / 1.09 + warehouseInOutInfo.getFreight()) * Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())) + original * weightedDetails.getCostBefore()) / (Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())) + original);

                        } else {
                            newCost = ((warehouseInOutInfo.getCost() / 1.09 + warehouseInOutInfo.getFreight()) * Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())) + original * weightedDetails.getCostBefore()) / (warehouseInOutInfo.getPureWeight() + original);

                        }
                        weightedDetails.setCostAfter(newCost);
                    }

                    weightedDetails.setCostAfter(newCost);
                    if (CollectionUtils.isEmpty(weightedDetailsList)) {
                        weightedDetails.setCostBefore(Float.valueOf(String.valueOf(newCost)));
                    } else {
                        weightedDetails.setCostBefore(weightedDetailsList.get(0).getCostBefore());
                    }
                    weightedDetailsService.insert(weightedDetails);
                    // 修改成本信息表
                    CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", weightedDetails.getWarehouseId())
                            .eq("comp_id", weightedDetails.getCompId())
                            .eq("goods_name", weightedDetails.getGoodsName()));
//                    List<WeightedDetails> weightedDetailsLists = weightedDetailsService.selectList(new EntityWrapper<WeightedDetails>().eq("warehouse_id", warehouseInOutInfo.getWarehouseName())
//                            .eq("goods_name_key", warehouseInOutInfo.getGoodsNameKey()).orderBy("update_date", false));
                    Double net = 0d;
//                    for (int i = 0; i < weightedDetailsLists.size(); i++) {
//                        net = net + weightedDetailsLists.get(i).getNetWeight();
//                    }
                    List<WarehousePositionInfo> warehousePositionInfos = warehousePositionInfoService.selectList(new EntityWrapper<WarehousePositionInfo>()
                            .eq("base_id", warehouseInOutInfo.getBaseId()));
                    if (!CollectionUtils.isEmpty(warehousePositionInfos)) {
                        for (int i = 0; i < warehousePositionInfos.size(); i++) {
                            List<WarehousePositionStorageInfo> warehousePositionStorageInfos = warehousePositionStorageInfoService.selectList(new EntityWrapper<WarehousePositionStorageInfo>()
                                    .eq("position_id", warehousePositionInfos.get(i).getId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName()));
                            for (int j = 0; j < warehousePositionStorageInfos.size(); j++) {
                                net = net + warehousePositionStorageInfos.get(j).getStorage();
                            }
                        }
                    }
                    if (costManagementInfo == null) {
                        CostManagementInfo costManagementInfo1 = new CostManagementInfo();
                        costManagementInfo1.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                        costManagementInfo1.setId(IdGenerator.generateUUID());
                        costManagementInfo1.setWarehouseId(weightedDetails.getWarehouseId());
                        costManagementInfo1.setWarehouseName(weightedDetails.getWarehouseName());
                        costManagementInfo1.setGoodsNameKey(weightedDetails.getGoodsNameKey());
                        costManagementInfo1.setGoodsName(weightedDetails.getGoodsName());
                        costManagementInfo1.setWarehouseType(warehouseBaseInfo.getWarehouseType());

                        costManagementInfo1.setStorage(net);
                        costManagementInfo1.setCost(weightedDetails.getCostAfter());
                        costManagementInfoService.insert(costManagementInfo1);
                    } else {
                        costManagementInfo.setCost(weightedDetails.getCostAfter());
                        costManagementInfo.setStorage(net);
                        costManagementInfoService.updateById(costManagementInfo);
                    }
                }
                //临时库入库
                else if ("2".equals(warehouseInOutInfo.getInOutFlag()) && "2".equals(warehouseBaseInfo.getWarehouseType())) {
                    //更新库存量
                    float original = 0f;
                    //判断是否有库
                    if (warehouseBaseInfo != null) {
                        //  查询库位
                        WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectById(warehouseInOutInfo.getPositionId());
                        if (warehousePositionInfo != null) {
                            // 查询货物库存量
                            WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                                    .eq("position_id", warehouseInOutInfo.getPositionId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName())
                                    .eq("delete_flag", "0"));
                            // 判断是否有货
                            if (warehousePositionStorageInfo != null) {
                                original = Float.valueOf(String.valueOf(warehousePositionStorageInfo.getStorage()));
                                // 更新库存量
                                warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
                            }
                            // 没有货
                            else {
                                WarehousePositionStorageInfo warehousePositionStorageInfo1 = new WarehousePositionStorageInfo();
                                warehousePositionStorageInfo1.setId(IdGenerator.generateUUID());
                                warehousePositionStorageInfo1.setPositionId(warehouseInOutInfo.getPositionId());
                                warehousePositionStorageInfo1.setBinNumber(warehouseInOutInfo.getBinNumber());
                                warehousePositionStorageInfo1.setGoodsNameKey(warehouseInOutInfo.getGoodsNameKey());
                                warehousePositionStorageInfo1.setGoodsName(warehouseInOutInfo.getGoodsName());
                                warehousePositionStorageInfo1.setStorage(warehouseInOutInfo.getNetWeight());
                                warehousePositionStorageInfoService.insert(warehousePositionStorageInfo1);
                            }
                        }
                    }
                }
                //常用库出库
                else if ("1".equals(warehouseInOutInfo.getInOutFlag()) && "1".equals(warehouseBaseInfo.getWarehouseType())) {
                    //常用库销售出库类型
                    if ("1".equals(warehouseInOutInfo.getInOutTypeKey())) {
                        //查出库任务关联的货源
                        InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                .eq("in_out_task_no", warehouseInOutInfo.getInOutTaskNo()));
                        List<SourceRelationInfo> sourceRelationInfoList =sourceRelationInfoService.selectList(new EntityWrapper<SourceRelationInfo>()
                                .eq("task_id", inOutWarehouseTask.getId())
                                .eq("delete_flag", "0"));
                        if (!CollectionUtils.isEmpty(sourceRelationInfoList)){
                            for (SourceRelationInfo sourceRelationInfo:sourceRelationInfoList){
                                //查货源关联的入库单
                                WarehousingOrder warehousingOrder=warehousingOrderService.selectById(sourceRelationInfo.getSourceId());
                                if ("采购入库".equals(warehousingOrder.getInType())){
                                    //更新采购合同库存销售量
                                    ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                                            .eq("comp_id",warehousingOrder.getCompId()).eq("inventory_type","1").eq("contract_no",warehousingOrder.getContractNo())
                                            .eq("warehouse",warehouseInOutInfo.getWarehouseName()));
                                    if (contractInventoryDistribution!=null){
                                        contractInventoryDistribution.setInStorage(contractInventoryDistribution.getInStorage()-warehouseInOutInfo.getNetWeight()*sourceRelationInfo.getProportion());
                                        contractInventoryDistributionService.updateById(contractInventoryDistribution);
                                    }
                                }
                                else if ("收购入库".equals(warehousingOrder.getInType())){
                                    //查收购合同原始货源仓库
                                    InOutWarehouseTask inOutWarehouseTask1=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                            .eq("comp_id", warehousingOrder.getCompId())
                                            .eq("contract_no", warehousingOrder.getContractNo())
                                            .eq("delete_flag", "0"));
                                    //更新收货库库点库存剩余量 (所在仓库为出货库、所属仓库为原始货源仓库、货名一致)
                                    ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                                            .eq("comp_id",warehousingOrder.getCompId()).eq("inventory_type","3").eq("locus_warehouse",warehouseInOutInfo.getWarehouseName())
                                            .eq("warehouse",inOutWarehouseTask1.getWarehouseName())
                                            .eq("goods_name",warehouseInOutInfo.getGoodsName()));
                                    if (contractInventoryDistribution!=null){
                                        contractInventoryDistribution.setInventory(contractInventoryDistribution.getInventory()-warehouseInOutInfo.getNetWeight()*sourceRelationInfo.getProportion());
                                        contractInventoryDistributionService.updateById(contractInventoryDistribution);
                                    }
                                }
                            }
                        }
                        //检斤表
                        WeighingManagement weighingManagement = weighingManagementService.selectOne(new EntityWrapper<WeighingManagement>()
                                .eq("warehouse_in_out_id", warehouseInOutInfo.getId())
                                .eq("delete_flag", "0"));
                        //他运的销售合同
                        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("deliver_type", "2")
                                .eq("contract_type", "1")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo != null) {
                            if (contractManagementInfo.getUnitContractPrice() == null) {
                                contractManagementInfo.setUnitContractPrice(0d);
                            }
                            //现货销售出库报表
                            StockSaleReceiptReport stockSaleReceiptReport = new StockSaleReceiptReport();
                            stockSaleReceiptReport.setId(IdGenerator.generateUUID());
                            stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            stockSaleReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockSaleReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            TranTaskInfo tranTaskInfo = tranTaskInfoService.selectOne(new EntityWrapper<TranTaskInfo>()
                                    .eq("contract_no", contractManagementInfo.getContractNo())
                                    .eq("comp_id", contractManagementInfo.getCompId()));
                            if (tranTaskInfo != null) {
                                TranProcessInfo tranProcessInfo = tranProcessInfoService.selectOne(new EntityWrapper<TranProcessInfo>()
                                        .eq("info_id", tranTaskInfo.getId()));
                                if (tranProcessInfo != null) {
                                    if (tranProcessInfo.getThreeTranType() == null) {
                                        tranProcessInfo.setThreeTranType(warehouseInOutInfo.getOutType());

                                    } else if (!tranProcessInfo.getThreeTranType().contains(warehouseInOutInfo.getOutType())) {
                                        tranProcessInfo.setThreeTranType(tranProcessInfo.getThreeTranType() + "," + warehouseInOutInfo.getOutType());
                                    }
                                    tranProcessInfoService.updateById(tranProcessInfo);
                                    stockSaleReceiptReport.setProcessId(tranProcessInfo.getId());
                                    TranCarInfo tranCarInfo = new TranCarInfo();
                                    tranCarInfo.setId(IdGenerator.generateUUID());
                                    tranCarInfo.setProcessId(tranProcessInfo.getId());
                                    tranCarInfo.setCompId(tranTaskInfo.getCompId());
                                    tranCarInfo.setInfoId(tranProcessInfo.getInfoId());
                                    tranCarInfo.setTranType("4");
                                    tranCarInfo.setSubmit("1");
                                    tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                                    tranCarInfo.setLoadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                                    tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                                    if ("汽运".equals(warehouseInOutInfo.getOutType())) {
                                        tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                                        tranCarInfo.setCaseNo(warehouseInOutInfo.getBoxNo());
                                        tranCarInfo.setThreeTranType("汽运");
                                        tranCarInfo.setTitleNo(warehouseInOutInfo.getTitleNo());
                                        tranCarInfo.setCaseNoOther(warehouseInOutInfo.getBoxNoOther());
                                        tranCarInfo.setTitleNoOther(warehouseInOutInfo.getTitleNoOther());
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setCaseNo(warehouseInOutInfo.getBoxNo());
                                        stockSaleReceiptReport.setTitleNo(warehouseInOutInfo.getTitleNo());
                                        stockSaleReceiptReport.setCaseNoOther(warehouseInOutInfo.getBoxNoOther());
                                        stockSaleReceiptReport.setTitleNoOther(warehouseInOutInfo.getTitleNoOther());
                                    } else if ("火运".equals(warehouseInOutInfo.getOutType())) {
                                        tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                                        tranCarInfo.setBoxNo(warehouseInOutInfo.getWingNumber());
                                        tranCarInfo.setThreeTranType("火运");
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setBoxNo(warehouseInOutInfo.getWingNumber());
                                    } else if ("散船".equals(warehouseInOutInfo.getOutType())) {
                                        tranCarInfo.setShipName(warehouseInOutInfo.getShipName());
                                        tranCarInfo.setShipNo(warehouseInOutInfo.getShipNumber());
                                        tranCarInfo.setThreeTranType("散船");
                                        tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setShipName(warehouseInOutInfo.getShipName());
                                        stockSaleReceiptReport.setShipNo(warehouseInOutInfo.getShipNumber());
                                    } else if ("集装箱船".equals(warehouseInOutInfo.getOutType())) {
                                        tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                                        tranCarInfo.setCaseNo(warehouseInOutInfo.getBoxNo());
                                        tranCarInfo.setTitleNo(warehouseInOutInfo.getTitleNo());
                                        tranCarInfo.setThreeTranType("集装箱船");
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setCaseNoOther(warehouseInOutInfo.getBoxNoOther());
                                        stockSaleReceiptReport.setTitleNoOther(warehouseInOutInfo.getTitleNoOther());
                                        stockSaleReceiptReport.setCaseNo(warehouseInOutInfo.getBoxNo());
                                        stockSaleReceiptReport.setTitleNo(warehouseInOutInfo.getTitleNo());
                                    }
                                    tranCarInfoService.insert(tranCarInfo);
                                }
                            }
                            stockSaleReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                            stockSaleReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockSaleReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockSaleReceiptReport.setNetWeight(warehouseInOutInfo.getNetWeight());
                            stockSaleReceiptReport.setDeliveryDate(warehouseInOutInfo.getInOutDate());
                            //按出库重量结算时
                            if ("1".equals(contractManagementInfo.getSettlementWeightMethod())) {
                                stockSaleReceiptReport.setSettlementWeight(warehouseInOutInfo.getNetWeight());
                            }
//                            //定价销售
                            if (weighingManagement.getContractPrice() != null) {
                                stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(weighingManagement.getContractPrice())));
                                stockSaleReceiptReport.setAmountIngReceivable(warehouseInOutInfo.getNetWeight() *
                                        (Double.valueOf(String.valueOf(weighingManagement.getContractPrice()))));
                                stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                            }
                            stockSaleReceiptReport.setStatusFlag(StatusEnum.TO_BE_RECEIVED.getFlag());
                            stockSaleReceiptReport.setStatus(StatusEnum.TO_BE_RECEIVED.getName());
                            stockSaleReceiptReport.setSettlementWeight(stockSaleReceiptReport.getNetWeight());
                            CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId()));
                            if (costManagementInfo != null) {
                                stockSaleReceiptReport.setCost(costManagementInfo.getCost());

                            }
                            stockSaleReceiptReportService.insert(stockSaleReceiptReport);
                        }
                        //自运的销售合同
                        ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("deliver_type", "1")
                                .eq("contract_type", "1")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo1 != null) {
                            //现货销售出库报表
                            StockSaleReceiptReport stockSaleReceiptReport = new StockSaleReceiptReport();
                            stockSaleReceiptReport.setId(IdGenerator.generateUUID());
                            stockSaleReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockSaleReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            TranTaskInfo tranTaskInfo = tranTaskInfoService.selectOne(new EntityWrapper<TranTaskInfo>()
                                    .eq("contract_no", contractManagementInfo1.getContractNo())
                                    .eq("comp_id", contractManagementInfo1.getCompId()));
                            if (tranTaskInfo != null) {
                                TranProcessInfo tranProcessInfo = tranProcessInfoService.selectOne(new EntityWrapper<TranProcessInfo>()
                                        .eq("info_id", tranTaskInfo.getId()));
                                if (tranProcessInfo != null) {
                                    stockSaleReceiptReport.setProcessId(tranProcessInfo.getId());
                                    stockSaleReceiptReport.setProcessNo(tranProcessInfo.getProcessNo());
                                    if ("汽运".equals(warehouseInOutInfo.getOutType())) {
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setTranCarNo(warehouseInOutInfo.getTranCarNo());
                                        stockSaleReceiptReport.setCaseNo(warehouseInOutInfo.getBoxNo());
                                        stockSaleReceiptReport.setTitleNo(warehouseInOutInfo.getTitleNo());
                                        stockSaleReceiptReport.setCaseNoOther(warehouseInOutInfo.getBoxNoOther());
                                        stockSaleReceiptReport.setTitleNoOther(warehouseInOutInfo.getTitleNoOther());
                                    } else if ("火运".equals(warehouseInOutInfo.getOutType())) {
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setBoxNo(warehouseInOutInfo.getWingNumber());
                                    } else if ("散船".equals(warehouseInOutInfo.getOutType())) {
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setShipName(warehouseInOutInfo.getShipName());
                                        stockSaleReceiptReport.setShipNo(warehouseInOutInfo.getShipNumber());
                                    } else if ("集装箱船".equals(warehouseInOutInfo.getOutType())) {
                                        stockSaleReceiptReport.setCaseNo(warehouseInOutInfo.getBoxNo());
                                        stockSaleReceiptReport.setCaseNoOther(warehouseInOutInfo.getBoxNoOther());
                                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                                        stockSaleReceiptReport.setTitleNoOther(warehouseInOutInfo.getTitleNoOther());
                                        stockSaleReceiptReport.setTitleNo(warehouseInOutInfo.getTitleNo());
                                    }
                                    //自运出库时手动加的车
                                    if ("1".equals(warehouseInOutInfo.getSelfLoading())) {
                                        List<TranCarInfo> tranCarInfoList = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                                                .eq("contract_no", contractManagementInfo1.getContractNo()).eq("tran_type", "1"));
                                        TranCarInfo tranCarInfo = new TranCarInfo();
                                        tranCarInfo.setProcessId(tranProcessInfo.getId());
                                        tranCarInfo.setTranPrice(String.valueOf(tranProcessInfo.getTranPrice() != null ? tranProcessInfo.getTranPrice() : 0f));
                                        tranCarInfo.setInfoId(tranTaskInfo.getId());
                                        tranCarInfo.setCompId(warehouseBaseInfo.getCompId());
                                        tranCarInfo.setTranType("1");
                                        tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                                        String tranCarNo = "";
                                        if ((tranCarInfoList.size() + 1) < 10) {
                                            tranCarNo = "C00" + (tranCarInfoList.size() + 1);
                                        } else if (tranCarInfoList.size() + 1 < 100) {
                                            tranCarNo = "C0" + (tranCarInfoList.size() + 1);
                                        } else {
                                            tranCarNo = "C" + (tranCarInfoList.size() + 1);
                                        }
                                        tranCarInfo.setTranCarNo(tranCarNo);
                                        tranCarInfo.setId(IdGenerator.generateUUID());
                                        tranCarInfo.setContractNo(contractManagementInfo1.getContractNo());
                                        tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                                        tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                                        warehouseInOutInfo.setCarId(tranCarInfo.getId());
                                        warehouseInOutInfo.setTranCarNo(tranCarNo);
                                        stockSaleReceiptReport.setTranCarNo(tranCarNo);
                                        warehouseInOutInfoService.updateById(warehouseInOutInfo);
                                        tranCarInfoService.insert(tranCarInfo);
                                    }
                                    //生成汽运报表
                                    TranSettlementReport tranSettlementReport = new TranSettlementReport();
                                    tranSettlementReport.setCompId(warehouseBaseInfo.getCompId());
                                    tranSettlementReport.setCarId(warehouseInOutInfo.getCarId());
                                    tranSettlementReport.setId(IdGenerator.generateUUID());
                                    if ("汽运".equals(warehouseInOutInfo.getOutType())) {
                                        tranSettlementReport.setTranType("汽运");
                                        tranSettlementReport.setTranTypeKey("1");
                                    } else if ("火运".equals(warehouseInOutInfo.getOutType())) {
                                        tranSettlementReport.setTranType("火运");
                                        tranSettlementReport.setTranTypeKey("2");
                                    } else {
                                        tranSettlementReport.setTranType("船运");
                                        tranSettlementReport.setTranTypeKey("3");
                                    }
                                    tranSettlementReport.setContractNo(warehouseInOutInfo.getContractNo());
                                    tranSettlementReport.setCarNo(warehouseInOutInfo.getCarNo());
                                    tranSettlementReport.setStartAddress(warehouseInOutInfo.getWarehouseName());
                                    tranSettlementReport.setSettlementWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    //运输单价不为空
                                    if (tranProcessInfo.getTranPrice()!=null){
                                        //应付
                                        tranSettlementReport.setAmountIngPayable(Float.valueOf(tranProcessInfo.getTranPrice()) * tranSettlementReport.getSettlementWeight());
                                        //未付
                                        tranSettlementReport.setAmountNotPayable(Float.valueOf(tranProcessInfo.getTranPrice()) * tranSettlementReport.getSettlementWeight());
                                        tranSettlementReport.setTransportPrice(Float.valueOf(tranProcessInfo.getTranPrice()));
                                    }
                                    tranSettlementReport.setLoadingImg(warehouseInOutInfo.getAddressUrl());
                                    tranSettlementReport.setLoadingWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    tranSettlementReportService.insert(tranSettlementReport);
                                    boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(tranSettlementReport.getWorkflowId());
                                    // 不是退回的单子
                                    if (isStartWorkflow) {
                                        Workflow workflow = workflowService
                                                .findLatestWorkflowByBusinessCodeByApp(tranSettlementReport.getCompId(), "TRANSPORTATION-SETTLEMENT-REPORT");
                                        // 没配置审核流程，直接结束并处理信息
                                        if (workflow == null) {
                                            throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                        }
                                        // 开启审核流
                                        else {

                                            // 设置状态 已提交审核
                                            tranSettlementReport.setWorkflowId(workflow.getId());
                                            tranSettlementReportService.updateById(tranSettlementReport);
                                            workflowService.startInstance(workflow.getId(), tranSettlementReport.getId());
                                        }
                                    }
                                    // 退回的单子 再启用
                                    else {

                                        tranSettlementReportService.updateById(tranSettlementReport);
                                        workflowService.activateInstance(tranSettlementReport.getWorkflowId(), tranSettlementReport.getId());
                                    }
                                }
                            } else {
                                throw new YException(YExceptionEnum.TRANTASK_NOT_CREATED_ERROR);
                            }
                            stockSaleReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                            stockSaleReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockSaleReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockSaleReceiptReport.setNetWeight(warehouseInOutInfo.getNetWeight());
                            stockSaleReceiptReport.setDeliveryDate(warehouseInOutInfo.getInOutDate());
                            stockSaleReceiptReport.setSettlementWeight(warehouseInOutInfo.getNetWeight());
                            //按出库重量结算时
                            if ("1".equals(contractManagementInfo1.getSettlementWeightMethod())) {
                                stockSaleReceiptReport.setSettlementWeight(warehouseInOutInfo.getNetWeight());
//                                //定价销售
                                if (weighingManagement.getContractPrice() != null) {
                                    stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(weighingManagement.getContractPrice())));
                                    stockSaleReceiptReport.setAmountIngReceivable(warehouseInOutInfo.getNetWeight() *
                                            (Double.valueOf(String.valueOf(weighingManagement.getContractPrice()))));
                                    stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                    stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                }
                            }
                            stockSaleReceiptReport.setStatusFlag(StatusEnum.TO_BE_RECEIVED.getFlag());
                            stockSaleReceiptReport.setStatus(StatusEnum.TO_BE_RECEIVED.getName());
                            stockSaleReceiptReport.setSettlementWeight(stockSaleReceiptReport.getNetWeight());
                            CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId()));
                            if (costManagementInfo != null) {
                                stockSaleReceiptReport.setCost(costManagementInfo.getCost());

                            }
                            stockSaleReceiptReportService.insert(stockSaleReceiptReport);
                        }
                    }
                    //常用库移库出库类型
                    if ("移库出库".equals(warehouseInOutInfo.getInOutType())) {
                        //更新合同移库库存
//                        ContractInventoryDistribution contractInventoryDistribution1=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
//                                .eq("comp_id",warehouseBaseInfo.getCompId()).eq("inventory_type","1").eq("contract_no",warehouseInOutInfo.getContractNo())
//                                .eq("warehouse",warehouseInOutInfo.getWarehouseName()));
//                        if (contractInventoryDistribution1!=null){
//                            contractInventoryDistribution1.setRemoveStorage(contractInventoryDistribution1.getRemoveStorage()+warehouseInOutInfo.getNetWeight());
//                            contractInventoryDistributionService.updateById(contractInventoryDistribution1);
//                        }
                        InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                .eq("move_task_no", warehouseInOutInfo.getContractNo())
                                .eq("in_out_flag", "1")
                                .eq("delete_flag", "0"));
                        if (inOutWarehouseTask != null) {
                            //更新所属仓库收购库存
//                            ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
//                                    .eq("comp_id",inOutWarehouseTask.getCompId()).eq("inventory_type","3").eq("warehouse",inOutWarehouseTask.getWarehouseName())
//                                    .eq("locus_warehouse",inOutWarehouseTask.getWarehouseName())
//                                    .eq("goods_name",warehouseInOutInfo.getGoodsName()));
//                            if (contractInventoryDistribution!=null){
//                                contractInventoryDistribution.setInventory(contractInventoryDistribution.getInventory()-warehouseInOutInfo.getNetWeight());
//                                contractInventoryDistributionService.updateById(contractInventoryDistribution);
//                            }
                            //自运出库时手动加的车
                            if ("1".equals(warehouseInOutInfo.getSelfLoading())) {
                                List<TranCarInfo> tranCarInfoList = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                                        .eq("contract_no", warehouseInOutInfo.getContractNo()).eq("tran_type", "1")
                                        .orderBy("create_date", false));
                                TranCarInfo tranCarInfo = new TranCarInfo();
                                TranTaskInfo tranTaskInfo = tranTaskInfoService.selectOne(new EntityWrapper<TranTaskInfo>()
                                        .eq("comp_id", warehouseBaseInfo.getCompId())
                                        .eq("contract_no", warehouseInOutInfo.getContractNo()));
                                if (tranTaskInfo != null) {
                                    TranProcessInfo tranProcessInfo = tranProcessInfoService.selectOne(new EntityWrapper<TranProcessInfo>()
                                            .eq("info_id", tranTaskInfo.getId()));
                                    tranCarInfo.setProcessId(tranProcessInfo.getId());
                                    tranCarInfo.setInfoId(tranTaskInfo.getId());
                                    tranCarInfo.setTranPrice(String.valueOf(tranProcessInfo.getTranPrice() != null ? tranProcessInfo.getTranPrice() : 0f));
                                    warehouseInOutInfo.setFreight(tranProcessInfo.getTranPrice());
                                } else {
                                    throw new YException(YExceptionEnum.TRANTASK_NOT_CREATED_ERROR);
                                }
                                //出库时打入成本
                                CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                                        .eq("goods_name", warehouseInOutInfo.getGoodsName()));
                                if (costManagementInfo != null) {
                                    tranCarInfo.setCost(costManagementInfo.getCost());
                                }
                                tranCarInfo.setCompId(warehouseBaseInfo.getCompId());
                                tranCarInfo.setTranType("1");
                                tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                                String tranCarNo = "";
                                if ((tranCarInfoList.size() + 1) < 10) {
                                    tranCarNo = "C00" + (tranCarInfoList.size() + 1);
                                } else if (tranCarInfoList.size() + 1 < 100) {
                                    tranCarNo = "C0" + (tranCarInfoList.size() + 1);
                                } else {
                                    tranCarNo = "C" + (tranCarInfoList.size() + 1);
                                }
                                tranCarInfo.setTranCarNo(tranCarNo);
                                tranCarInfo.setId(IdGenerator.generateUUID());
                                tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                                tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                                tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                                warehouseInOutInfo.setCarId(tranCarInfo.getId());
                                warehouseInOutInfo.setTranCarNo(tranCarNo);
                                warehouseInOutInfoService.updateById(warehouseInOutInfo);
                                tranCarInfoService.insert(tranCarInfo);
                                //生成汽运报表
                                TranSettlementReport tranSettlementReport = new TranSettlementReport();
                                tranSettlementReport.setCompId(warehouseBaseInfo.getCompId());
                                tranSettlementReport.setCarId(warehouseInOutInfo.getCarId());
                                tranSettlementReport.setId(IdGenerator.generateUUID());
                                if ("汽运".equals(warehouseInOutInfo.getOutType())) {
                                    tranSettlementReport.setTranType("汽运");
                                    tranSettlementReport.setTranTypeKey("1");
                                } else if ("火运".equals(warehouseInOutInfo.getOutType())) {
                                    tranSettlementReport.setTranType("火运");
                                    tranSettlementReport.setTranTypeKey("2");
                                } else {
                                    tranSettlementReport.setTranType("船运");
                                    tranSettlementReport.setTranTypeKey("3");
                                }
                                tranSettlementReport.setContractNo(warehouseInOutInfo.getContractNo());
                                tranSettlementReport.setCarNo(warehouseInOutInfo.getCarNo());
                                tranSettlementReport.setStartAddress(warehouseInOutInfo.getWarehouseName());
                                tranSettlementReport.setSettlementWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                //运输单价不为空
                                if (warehouseInOutInfo.getFreight()!=null){
                                    //应付
                                    tranSettlementReport.setAmountIngPayable(Float.valueOf(warehouseInOutInfo.getFreight()) * tranSettlementReport.getSettlementWeight());
                                    //未付
                                    tranSettlementReport.setAmountNotPayable(Float.valueOf(warehouseInOutInfo.getFreight()) * tranSettlementReport.getSettlementWeight());
                                    tranSettlementReport.setTransportPrice(Float.valueOf(warehouseInOutInfo.getFreight()));
                                }
                                tranSettlementReport.setLoadingImg(warehouseInOutInfo.getAddressUrl());
                                tranSettlementReport.setLoadingWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                tranSettlementReportService.insert(tranSettlementReport);
                                boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(tranSettlementReport.getWorkflowId());
                                // 不是退回的单子
                                if (isStartWorkflow) {
                                    Workflow workflow = workflowService
                                            .findLatestWorkflowByBusinessCodeByApp(tranSettlementReport.getCompId(), "TRANSPORTATION-SETTLEMENT-REPORT");
                                    // 没配置审核流程，直接结束并处理信息
                                    if (workflow == null) {
                                        throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                    }
                                    // 开启审核流
                                    else {

                                        // 设置状态 已提交审核
                                        tranSettlementReport.setWorkflowId(workflow.getId());
                                        tranSettlementReportService.updateById(tranSettlementReport);
                                        workflowService.startInstance(workflow.getId(), tranSettlementReport.getId());
                                    }
                                }
                                // 退回的单子 再启用
                                else {

                                    tranSettlementReportService.updateById(tranSettlementReport);
                                    workflowService.activateInstance(tranSettlementReport.getWorkflowId(), tranSettlementReport.getId());
                                }
                            }
                        }
                    }
                    if (warehouseInOutInfo.getWeighingManagement() != null) {
                        //毛重检斤
                        //状态改为已称毛重
                        WeighingManagement weighingManagement = warehouseInOutInfo.getWeighingManagement();
                        weighingManagement.setStatus(StatusEnum.WEIGHED_GROSS_WEIGHT.getName());
                        weighingManagement.setStatusFlag(StatusEnum.WEIGHED_GROSS_WEIGHT.getFlag());
                        weighingManagement.setGrossDate(new Date());
                        weighingManagement.setSecretaryWeigher(commonStaff.getStaffName());
                        //质检信息
                        QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                                .eq("relation_id", weighingManagement.getRelationId())
                                .eq("comp_id", commonStaff.getCompId()));
                        if (qualityInspectionManagement != null) {
                            qualityInspectionManagement.setCarNumber(warehouseInOutInfo.getCarNo());
                            //状态改为已称毛重
//                      qualityInspectionManagement.setStatus(StatusEnum.WEIGHED_GROSS_WEIGHT.getName());
//                      qualityInspectionManagement.setStatusFlag(StatusEnum.WEIGHED_GROSS_WEIGHT.getFlag());
                            qualityInspectionManagementService.updateById(qualityInspectionManagement);
                        }
                        if (weighingManagement.getGrossWeight() == null || weighingManagement.getGrossWeight() == 0) {
                            throw new YException(YExceptionEnum.GROSSWEIGHT_NULL);
                        }
                        weighingManagementService.updateById(weighingManagement);
                    }
                    //运费大于0生成运费结算报表数据
//                    if (warehouseInOutInfo.getFreight() != null && warehouseInOutInfo.getFreight() > 0) {
//                        //生成汽运报表
//                        TranSettlementReport tranSettlementReport = new TranSettlementReport();
//                        tranSettlementReport.setCompId(warehouseBaseInfo.getCompId());
//                        tranSettlementReport.setCarId(warehouseInOutInfo.getCarId());
//                        tranSettlementReport.setId(IdGenerator.generateUUID());
//                        if ("汽运".equals(warehouseInOutInfo.getOutType())) {
//                            tranSettlementReport.setTranType("汽运");
//                            tranSettlementReport.setTranTypeKey("1");
//                        } else if ("火运".equals(warehouseInOutInfo.getOutType())) {
//                            tranSettlementReport.setTranType("火运");
//                            tranSettlementReport.setTranTypeKey("2");
//                        } else {
//                            tranSettlementReport.setTranType("船运");
//                            tranSettlementReport.setTranTypeKey("3");
//                        }
//                        tranSettlementReport.setContractNo(warehouseInOutInfo.getContractNo());
//                        tranSettlementReport.setCarNo(warehouseInOutInfo.getCarNo());
//                        tranSettlementReport.setSettlementWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
//                        //应付
//                        tranSettlementReport.setAmountIngPayable(Float.valueOf(warehouseInOutInfo.getFreight()) * tranSettlementReport.getSettlementWeight());
//                        //未付
//                        tranSettlementReport.setAmountNotPayable(Float.valueOf(warehouseInOutInfo.getFreight()) * tranSettlementReport.getSettlementWeight());
//                        tranSettlementReport.setLoadingWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
//                        tranSettlementReport.setLoadingImg(warehouseInOutInfo.getAddressUrl());
//                        tranSettlementReport.setTransportPrice(Float.valueOf(warehouseInOutInfo.getFreight()));
//                        tranSettlementReportService.insert(tranSettlementReport);
//                        boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(tranSettlementReport.getWorkflowId());
//                        // 不是退回的单子
//                        if (isStartWorkflow) {
//                            Workflow workflow = workflowService
//                                    .findLatestWorkflowByBusinessCodeByApp(tranSettlementReport.getCompId(), "TRANSPORTATION-SETTLEMENT-REPORT");
//                            // 没配置审核流程，直接结束并处理信息
//                            if (workflow == null) {
//                                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
//                            }
//                            // 开启审核流
//                            else {
//
//                                // 设置状态 已提交审核
//                                tranSettlementReport.setWorkflowId(workflow.getId());
//                                tranSettlementReportService.updateById(tranSettlementReport);
//                                workflowService.startInstance(workflow.getId(), tranSettlementReport.getId());
//                            }
//                        }
//                        // 退回的单子 再启用
//                        else {
//
//                            tranSettlementReportService.updateById(tranSettlementReport);
//                            workflowService.activateInstance(tranSettlementReport.getWorkflowId(), tranSettlementReport.getId());
//                        }
//                    }
                    TranCarInfo tranCarInfo = tranCarInfoService.selectById(warehouseInOutInfo.getCarId());
                    if (tranCarInfo != null) {
                        //将发货数据同步到派车表
                        tranCarInfo.setLoadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        if (warehouseInOutInfo.getAddressUrl() != null) {
                            tranCarInfo.setLoadPoundImg(warehouseInOutInfo.getAddressUrl());
                        }
                        if ("移库出库".equals(warehouseInOutInfo.getInOutType())) {
                            //移库出库时打入成本
                            CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName()));
                            if (costManagementInfo != null) {
                                tranCarInfo.setCost(costManagementInfo.getCost());
                            }
                        }
                        tranCarInfo.setLoadingDate(warehouseInOutInfo.getInOutDate());
                        tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                        tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                        tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                        if ("1".equals(tranCarInfo.getSubmit())) {
                            throw new YException(YExceptionEnum.CARNO_SUBMITTED_ERROR);
                        } else {
                            tranCarInfo.setSubmit("1");
                        }
                        tranCarInfoService.updateById(tranCarInfo);
                    }
                    //判断是否有货
                    if (warehouseBaseInfo != null) {
                        //  查询库位
                        WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectById(warehouseInOutInfo.getPositionId());
                        if (warehousePositionInfo != null) {
                            // 查询货物库存量
                            WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                                    .eq("position_id", warehouseInOutInfo.getPositionId())
                                    .eq("goods_name", warehouseInOutInfo.getGoodsName())
                                    .eq("delete_flag", "0"));
                            // 判断是否有货
                            if (warehousePositionStorageInfo != null) {
                                if (warehouseInOutInfo.getNetWeight() <= warehousePositionStorageInfo.getStorage()) {
                                    // 更新库存量
                                    warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() - Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                                    warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
                                }
                                //出库量大于库存量
                                else {
                                    throw new YException(YExceptionEnum.INVENTORY_NO_ERROR);
                                }
                            }
                            // 没有储存量
                            else {
                                throw new YException(YExceptionEnum.POSITIONSTORAGE_NO_ERROR);
                            }
                        }
                        //库位不存在
                        else {
                            throw new YException(YExceptionEnum.POSITION_NO_ERROR);
                        }
                        //出库时打入成本
                        CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                                .eq("goods_name", warehouseInOutInfo.getGoodsName()));
                        if (costManagementInfo != null) {
                            warehouseInOutInfo.setWeightedCost(Float.valueOf(String.valueOf(costManagementInfo.getCost())));
                            warehouseInOutInfoService.updateById(warehouseInOutInfo);
                            TranCarInfo tranCarInfo1 = tranCarInfoService.selectById(warehouseInOutInfo.getCarId());
                            if (tranCarInfo1 != null) {
                                //打入出库成本
                                tranCarInfo1.setCost(costManagementInfo.getCost());
                                tranCarInfoService.updateById(tranCarInfo1);
                            }
                        }
                    }
                    //仓库不存在
                    else {
                        throw new YException(YExceptionEnum.WAREHOUSE_NO_ERROR);
                    }
                }
                //临时库出库
                else if ("1".equals(warehouseInOutInfo.getInOutFlag()) && "2".equals(warehouseBaseInfo.getWarehouseType())) {
                    //检斤表
                    WeighingManagement weighingManagement = weighingManagementService.selectOne(new EntityWrapper<WeighingManagement>()
                            .eq("warehouse_in_out_id", warehouseInOutInfo.getId())
                            .eq("delete_flag", "0"));
                    //临时库销售出库类型 且为自动创建的临时库时(采购报表进数据，销售报表也进数据)
                    if ("1".equals(warehouseInOutInfo.getInOutTypeKey()) && "1".equals(warehouseBaseInfo.getCreateType())) {
                        //查出库任务关联的货源
                        InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                .eq("in_out_task_no", warehouseInOutInfo.getInOutTaskNo()));
                        List<SourceRelationInfo> sourceRelationInfoList =sourceRelationInfoService.selectList(new EntityWrapper<SourceRelationInfo>()
                                .eq("task_id", inOutWarehouseTask.getId())
                                .eq("delete_flag", "0"));
                        if (!CollectionUtils.isEmpty(sourceRelationInfoList)){
                            for (SourceRelationInfo sourceRelationInfo:sourceRelationInfoList){
                                //查货源关联的入库单
                                WarehousingOrder warehousingOrder=warehousingOrderService.selectById(sourceRelationInfo.getSourceId());
                                //临时库只有采购入库情况
                                if ("采购入库".equals(warehousingOrder.getInType())){
                                    //更新采购合同库存销售量
                                    ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                                            .eq("comp_id",warehousingOrder.getCompId()).eq("inventory_type","1").eq("contract_no",warehousingOrder.getContractNo())
                                            .eq("warehouse",warehouseInOutInfo.getWarehouseName()));
                                    if (contractInventoryDistribution!=null){
                                        contractInventoryDistribution.setInStorage(contractInventoryDistribution.getInStorage()-warehouseInOutInfo.getNetWeight()*sourceRelationInfo.getProportion());
                                        contractInventoryDistributionService.updateById(contractInventoryDistribution);
                                    }
                                }
                            }
                        }
                        //自运销售合同
                        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseBaseInfo.getWarehouseName())
                                .eq("deliver_type", "1")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo != null) {
                            //现货采购入库报表
                            StockPurchaseReceiptReport stockPurchaseReceiptReport = new StockPurchaseReceiptReport();
                            stockPurchaseReceiptReport.setId(IdGenerator.generateUUID());
                            stockPurchaseReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            stockPurchaseReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockPurchaseReceiptReport.setContractNo(contractManagementInfo.getContractNo());
                            stockPurchaseReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockPurchaseReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            stockPurchaseReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockPurchaseReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockPurchaseReceiptReport.setNetWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            stockPurchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                            stockPurchaseReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            stockPurchaseReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(weighingManagement.getContractPrice())));
//                            if (contractManagementInfo.getUnitContractPrice() != null) {
                            stockPurchaseReceiptReport.setAmountIngPayable(warehouseInOutInfo.getNetWeight() *
                                    (Double.valueOf(String.valueOf(weighingManagement.getContractPrice()))));
//                            }
                            stockPurchaseReceiptReport.setAmountEdPayable(0.0d);
                            stockPurchaseReceiptReport.setAmountNotPayable(stockPurchaseReceiptReport.getAmountIngPayable());
                            stockPurchaseReceiptReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                            stockPurchaseReceiptReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
                            stockPurchaseReceiptReportService.insert(stockPurchaseReceiptReport);
                            boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(stockPurchaseReceiptReport.getWorkflowId());
                            // 不是退回的单子
                            if (isStartWorkflow) {
                                Workflow workflow = workflowService
                                        .findLatestWorkflowByBusinessCodeByApp(stockPurchaseReceiptReport.getCompId(), "STOCK-PROCUREMENT-RECEIPT-REPORT");
                                // 没配置审核流程，直接结束并处理信息
                                if (workflow == null) {
                                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                }
                                // 开启审核流
                                else {
                                    // 设置状态 已提交审核
                                    stockPurchaseReceiptReport.setWorkflowId(workflow.getId());
                                    stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                    workflowService.startInstance(workflow.getId(), stockPurchaseReceiptReport.getId());
                                }
                            }
                            // 退回的单子 再启用
                            else {
                                stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                workflowService.activateInstance(stockPurchaseReceiptReport.getWorkflowId(), stockPurchaseReceiptReport.getId());
                            }
                        }
                        //他运销售合同
                        ContractManagementInfo contractManagementInfoSale = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("deliver_type", "2")
                                .eq("contract_type", "1")
                                .eq("delete_flag", "0"));
                        //现货销售出库报表
                        StockSaleReceiptReport stockSaleReceiptReport = new StockSaleReceiptReport();
                        stockSaleReceiptReport.setId(IdGenerator.generateUUID());
                        stockSaleReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                        stockSaleReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                        stockSaleReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                        stockSaleReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                        stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                        stockSaleReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                        stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                        stockSaleReceiptReport.setNetWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        stockSaleReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                        stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(warehouseInOutInfo.getCost()==null?(contractManagementInfoSale.getUnitContractPrice()==null?0:contractManagementInfoSale.getUnitContractPrice()):warehouseInOutInfo.getCost())));
                        stockSaleReceiptReport.setAmountEdReceivable(0.0d);
                        stockSaleReceiptReport.setDeliveryDate(warehouseInOutInfo.getInOutDate());
                        stockSaleReceiptReport.setAmountIngReceivable(stockSaleReceiptReport.getSettlementPrice() * warehouseInOutInfo.getNetWeight());
                        stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                        stockSaleReceiptReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                        stockSaleReceiptReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
                        stockSaleReceiptReportService.insert(stockSaleReceiptReport);
                        boolean isStartWorkflow1 = org.apache.commons.lang3.StringUtils.isBlank(stockSaleReceiptReport.getWorkflowId());
                        // 不是退回的单子
                        if (isStartWorkflow1) {
                            Workflow workflow = workflowService
                                    .findLatestWorkflowByBusinessCodeByApp(stockSaleReceiptReport.getCompId(), "SALE-RECEIPT-REPORT");
                            // 没配置审核流程，直接结束并处理信息
                            if (workflow == null) {
                                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                            }
                            // 开启审核流
                            else {
                                // 设置状态 已提交审核
                                stockSaleReceiptReport.setWorkflowId(workflow.getId());
                                stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                                workflowService.startInstance(workflow.getId(), stockSaleReceiptReport.getId());
                            }
                        }
                        // 退回的单子 再启用
                        else {
                            stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                            workflowService.activateInstance(stockSaleReceiptReport.getWorkflowId(), stockSaleReceiptReport.getId());
                        }
                        ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", contractManagementInfo.getContractNo()).eq("delete_flag", "0"));
                        if (contractManagementInfo1 == null) {
                            throw new YException(YExceptionEnum.CONTRACT_NO_NOT_EXSITS_ERROR);
                        }

                        Wrapper wrapper = new EntityWrapper<TranCarInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("car_no", warehouseInOutInfo.getCarNo())
                                .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                                .eq("tran_car_no", warehouseInOutInfo.getTranCarNo());
                        TranCarInfo tranCarInfo = tranCarInfoService.selectOne(wrapper);
                        if (tranCarInfo != null) {
                            //将发货数据同步到派车表
                            tranCarInfo.setLoadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            if (warehouseInOutInfo.getAddressUrl() != null) {
                                tranCarInfo.setLoadPoundImg(warehouseInOutInfo.getAddressUrl());
                            }
                            tranCarInfo.setLoadingDate(warehouseInOutInfo.getInOutDate());
                            tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                            tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                            tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                            if ("1".equals(tranCarInfo.getSubmit())) {
                                throw new YException(YExceptionEnum.CARNO_SUBMITTED_ERROR);
                            } else {
                                tranCarInfo.setSubmit("1");
                            }
                            tranCarInfoService.updateById(tranCarInfo);
                        }
                    }
                    //临时库移库出库类型 且为自动创建的临时库时进采购报表
                    if ("3".equals(warehouseInOutInfo.getInOutTypeKey()) && "1".equals(warehouseBaseInfo.getCreateType())) {
                        //更新合同移库库存
//                        ContractInventoryDistribution contractInventoryDistribution1=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
//                                .eq("comp_id",warehouseBaseInfo.getCompId()).eq("inventory_type","1").eq("contract_no",warehouseInOutInfo.getContractNo())
//                                .eq("warehouse",warehouseInOutInfo.getWarehouseName()));
//                        if (contractInventoryDistribution1!=null){
//                            contractInventoryDistribution1.setRemoveStorage(contractInventoryDistribution1.getRemoveStorage()+warehouseInOutInfo.getNetWeight());
//                            contractInventoryDistributionService.updateById(contractInventoryDistribution1);
//                        }
                        //按出库重量结算
                        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", warehouseBaseInfo.getWarehouseName())
                                .eq("settlement_weight_method", "1")
                                .eq("deliver_type", "1")
                                .eq("delete_flag", "0"));
                        if (contractManagementInfo != null) {
                            //现货采购入库报表
                            StockPurchaseReceiptReport stockPurchaseReceiptReport = new StockPurchaseReceiptReport();
                            stockPurchaseReceiptReport.setId(IdGenerator.generateUUID());
                            stockPurchaseReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                            stockPurchaseReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                            stockPurchaseReceiptReport.setContractNo(contractManagementInfo.getContractNo());
                            stockPurchaseReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                            stockPurchaseReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            stockPurchaseReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                            stockPurchaseReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                            stockPurchaseReceiptReport.setNetWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            stockPurchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                            stockPurchaseReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            stockPurchaseReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(weighingManagement.getContractPrice())));
                            if (contractManagementInfo.getUnitContractPrice() != null) {
                                stockPurchaseReceiptReport.setAmountIngPayable(warehouseInOutInfo.getNetWeight() *
                                        (Double.valueOf(String.valueOf(weighingManagement.getContractPrice()))));
                            }
                            stockPurchaseReceiptReport.setAmountEdPayable(0.0d);
                            stockPurchaseReceiptReport.setAmountNotPayable(stockPurchaseReceiptReport.getAmountIngPayable());
                            stockPurchaseReceiptReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
                            stockPurchaseReceiptReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
                            stockPurchaseReceiptReportService.insert(stockPurchaseReceiptReport);
                            boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(stockPurchaseReceiptReport.getWorkflowId());
                            // 不是退回的单子
                            if (isStartWorkflow) {
                                Workflow workflow = workflowService
                                        .findLatestWorkflowByBusinessCodeByApp(stockPurchaseReceiptReport.getCompId(), "STOCK-PROCUREMENT-RECEIPT-REPORT");
                                // 没配置审核流程，直接结束并处理信息
                                if (workflow == null) {
                                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                }
                                // 开启审核流
                                else {
                                    // 设置状态 已提交审核
                                    stockPurchaseReceiptReport.setWorkflowId(workflow.getId());
                                    stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                    workflowService.startInstance(workflow.getId(), stockPurchaseReceiptReport.getId());
                                }
                            }
                            // 退回的单子 再启用
                            else {
                                stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                                workflowService.activateInstance(stockPurchaseReceiptReport.getWorkflowId(), stockPurchaseReceiptReport.getId());
                            }
                        }
                        ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                .eq("contract_no", contractManagementInfo.getContractNo()).eq("delete_flag", "0"));
                        if (contractManagementInfo1 == null) {
                            throw new YException(YExceptionEnum.CONTRACT_NO_NOT_EXSITS_ERROR);
                        }
                        Wrapper wrapper = new EntityWrapper<TranCarInfo>()
                                .eq("contract_no", warehouseInOutInfo.getContractNo())
                                .eq("car_no", warehouseInOutInfo.getCarNo())
                                .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                                .eq("tran_car_no", warehouseInOutInfo.getTranCarNo());
                        TranCarInfo tranCarInfo = tranCarInfoService.selectOne(wrapper);
                        if (tranCarInfo != null) {
                            //将发货数据同步到派车表
                            tranCarInfo.setLoadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            if (warehouseInOutInfo.getAddressUrl() != null) {
                                tranCarInfo.setLoadPoundImg(warehouseInOutInfo.getAddressUrl());
                            }
                            tranCarInfo.setLoadingDate(warehouseInOutInfo.getInOutDate());
                            tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                            if (contractManagementInfo != null) {
                                tranCarInfo.setCost(contractManagementInfo.getUnitContractPrice());
                            } else {
                                //出库时打入成本
                                CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                                        .eq("goods_name", warehouseInOutInfo.getGoodsName()));
                                if (costManagementInfo != null) {
                                    tranCarInfo.setCost(costManagementInfo.getCost());
                                }
                            }
                            tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                            tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                            if ("1".equals(tranCarInfo.getSubmit())) {
                                throw new YException(YExceptionEnum.CARNO_SUBMITTED_ERROR);
                            } else {
                                tranCarInfo.setSubmit("1");
                            }
                            tranCarInfoService.updateById(tranCarInfo);
                        }
                    }
                    if (warehouseInOutInfo.getWeighingManagement() != null) {
                        //毛重检斤
                        //状态改为已称毛重
                        WeighingManagement weighingManagement1 = warehouseInOutInfo.getWeighingManagement();
                        weighingManagement1.setStatus(StatusEnum.WEIGHED_GROSS_WEIGHT.getName());
                        weighingManagement1.setStatusFlag(StatusEnum.WEIGHED_GROSS_WEIGHT.getFlag());
                        weighingManagement1.setGrossDate(new Date());
                        weighingManagement1.setSecretaryWeigher(commonStaff.getStaffName());
                        //质检信息
                        QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                                .eq("relation_id", weighingManagement1.getRelationId())
                                .eq("comp_id", commonStaff.getCompId()));
                        if (qualityInspectionManagement != null) {
                            qualityInspectionManagement.setCarNumber(warehouseInOutInfo.getCarNo());
                            //状态改为已称毛重
                            qualityInspectionManagementService.updateById(qualityInspectionManagement);
                        }
                        if (weighingManagement1.getGrossWeight() == null || weighingManagement1.getGrossWeight() == 0) {
                            throw new YException(YExceptionEnum.GROSSWEIGHT_NULL);
                        }
                        weighingManagementService.updateById(weighingManagement1);
                    }
                    Wrapper<InOutWarehouseTask> inOutWarehouseTaskWrapper = new EntityWrapper<>();
                    inOutWarehouseTaskWrapper.eq("in_out_flag", "1").eq("delete_flag", "0");
                    inOutWarehouseTaskWrapper.andNew().eq("move_task_no", warehouseInOutInfo.getContractNo()).or()
                            .eq("contract_no", warehouseInOutInfo.getContractNo());
                    InOutWarehouseTask inOutWarehouseTask = inOutWarehouseTaskService.selectOne(inOutWarehouseTaskWrapper);
                    if (inOutWarehouseTask != null) {
                        //自运出库时手动加的车
                        if ("1".equals(warehouseInOutInfo.getSelfLoading()) || warehouseInOutInfo.getTranCarNo() == null || warehouseInOutInfo.getCarId() == null) {
                            List<TranCarInfo> tranCarInfoList = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                                    .eq("contract_no", warehouseInOutInfo.getContractNo()).eq("tran_type", "1")
                                    .orderBy("create_date", false));
                            TranCarInfo tranCarInfo = new TranCarInfo();
                            TranTaskInfo tranTaskInfo = tranTaskInfoService.selectOne(new EntityWrapper<TranTaskInfo>()
                                    .eq("comp_id", warehouseBaseInfo.getCompId())
                                    .eq("contract_no", warehouseInOutInfo.getContractNo()));
                            if (tranTaskInfo != null) {
                                TranProcessInfo tranProcessInfo = tranProcessInfoService.selectOne(new EntityWrapper<TranProcessInfo>()
                                        .eq("info_id", tranTaskInfo.getId()));
                                tranCarInfo.setProcessId(tranProcessInfo.getId());
                                tranCarInfo.setTranPrice(String.valueOf(tranProcessInfo.getTranPrice() != null ? tranProcessInfo.getTranPrice() : 0f));
                                warehouseInOutInfo.setFreight(tranProcessInfo.getTranPrice());
                                tranCarInfo.setInfoId(tranTaskInfo.getId());
                            } else {
                                throw new YException(YExceptionEnum.TRANTASK_NOT_CREATED_ERROR);
                            }
                            tranCarInfo.setCompId(warehouseBaseInfo.getCompId());
                            tranCarInfo.setTranType("1");
                            tranCarInfo.setSubmit("1");
                            ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                                    .eq("contract_no", warehouseInOutInfo.getContractNo()).eq("delete_flag", "0"));
                            if (contractManagementInfo1 != null) {
                                tranCarInfo.setCost(contractManagementInfo1.getUnitContractPrice());
                            } else {
                                //出库时打入成本
                                CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                                        .eq("goods_name", warehouseInOutInfo.getGoodsName()));
                                if (costManagementInfo != null) {
                                    tranCarInfo.setCost(costManagementInfo.getCost());
                                }
                            }
                            tranCarInfo.setLoadNetWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            tranCarInfo.setLoadingDate(new Date());
                            tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                            String tranCarNo = "";
                            if ((tranCarInfoList.size() + 1) < 10) {
                                tranCarNo = "C00" + (tranCarInfoList.size() + 1);
                            } else if (tranCarInfoList.size() + 1 < 100) {
                                tranCarNo = "C0" + (tranCarInfoList.size() + 1);
                            } else {
                                tranCarNo = "C" + (tranCarInfoList.size() + 1);
                            }
                            tranCarInfo.setTranCarNo(tranCarNo);
                            tranCarInfo.setId(IdGenerator.generateUUID());
                            tranCarInfo.setContractNo(warehouseInOutInfo.getContractNo());
                            tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                            tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                            warehouseInOutInfo.setSelfLoading("1");
                            warehouseInOutInfo.setCarId(tranCarInfo.getId());
                            warehouseInOutInfo.setTranCarNo(tranCarNo);
                            warehouseInOutInfoService.updateById(warehouseInOutInfo);
                            tranCarInfoService.insert(tranCarInfo);
                            //生成汽运报表
                            TranSettlementReport tranSettlementReport = new TranSettlementReport();
                            tranSettlementReport.setCompId(warehouseBaseInfo.getCompId());
                            tranSettlementReport.setCarId(warehouseInOutInfo.getCarId());
                            tranSettlementReport.setId(IdGenerator.generateUUID());
                            if ("汽运".equals(warehouseInOutInfo.getOutType())) {
                                tranSettlementReport.setTranType("汽运");
                                tranSettlementReport.setTranTypeKey("1");
                            } else if ("火运".equals(warehouseInOutInfo.getOutType())) {
                                tranSettlementReport.setTranType("火运");
                                tranSettlementReport.setTranTypeKey("2");
                            } else {
                                tranSettlementReport.setTranType("船运");
                                tranSettlementReport.setTranTypeKey("3");
                            }
                            tranSettlementReport.setContractNo(warehouseInOutInfo.getContractNo());
                            tranSettlementReport.setCarNo(warehouseInOutInfo.getCarNo());
                            tranSettlementReport.setStartAddress(warehouseInOutInfo.getWarehouseName());
                            tranSettlementReport.setSettlementWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            //运输单价不为空
                            if (warehouseInOutInfo.getFreight()!=null){
                                //应付
                                tranSettlementReport.setAmountIngPayable(Float.valueOf(warehouseInOutInfo.getFreight()) * tranSettlementReport.getSettlementWeight());
                                //未付
                                tranSettlementReport.setAmountNotPayable(Float.valueOf(warehouseInOutInfo.getFreight()) * tranSettlementReport.getSettlementWeight());
                                tranSettlementReport.setTransportPrice(Float.valueOf(warehouseInOutInfo.getFreight()));
                            }
                            tranSettlementReport.setLoadingImg(warehouseInOutInfo.getAddressUrl());
                            tranSettlementReport.setLoadingWeight(Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight())));
                            tranSettlementReportService.insert(tranSettlementReport);
                            boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(tranSettlementReport.getWorkflowId());
                            // 不是退回的单子
                            if (isStartWorkflow) {
                                Workflow workflow = workflowService
                                        .findLatestWorkflowByBusinessCodeByApp(tranSettlementReport.getCompId(), "TRANSPORTATION-SETTLEMENT-REPORT");
                                // 没配置审核流程，直接结束并处理信息
                                if (workflow == null) {
                                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                                }
                                // 开启审核流
                                else {

                                    // 设置状态 已提交审核
                                    tranSettlementReport.setWorkflowId(workflow.getId());
                                    tranSettlementReportService.updateById(tranSettlementReport);
                                    workflowService.startInstance(workflow.getId(), tranSettlementReport.getId());
                                }
                            }
                            // 退回的单子 再启用
                            else {

                                tranSettlementReportService.updateById(tranSettlementReport);
                                workflowService.activateInstance(tranSettlementReport.getWorkflowId(), tranSettlementReport.getId());
                            }
                        }
                    }
                    if (warehouseBaseInfo != null) {
                        //出库时打入成本
                        CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId())
                                .eq("goods_name", warehouseInOutInfo.getGoodsNameKey()));
                        if (costManagementInfo != null) {
                            warehouseInOutInfo.setWeightedCost(Float.valueOf(String.valueOf(costManagementInfo.getCost())));
                            warehouseInOutInfoService.updateById(warehouseInOutInfo);
                        }
                    }
                }
            }
        }
        cacheComponent.delPrefixKey(Const.ADMIN_CONTRACTINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        return warehouseInOutInfo.getWeighingManagement().getId();
    }

}
