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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
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.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.StringUtils;
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.WeighingManagementMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.util.Const;
import com.yh.saas.plugin.yiliangyiyun.util.QRCodeUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 检斤管理 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2021-09-06
 */
@Service
public class WeighingManagementServiceImpl extends ServiceImpl<WeighingManagementMapper, WeighingManagement> implements IWeighingManagementService {

    @Autowired
    private IPaymentManagementService paymentManagementService;
    @Autowired
    private IQualityInspectionManagementService qualityInspectionManagementService;
    @Autowired
    private  IIdentityAuthenticationInfoService identityAuthenticationInfoService;
    @Autowired
    private ICommonCompanyService commonCompanyService;
    @Autowired
    private IWarehouseBaseInfoService warehouseBaseInfoService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    private IWarehouseInOutDetailService warehouseInOutDetailService;
    @Autowired
    private IWarehousePositionStorageInfoService warehousePositionStorageInfoService;
    @Autowired
    private IStockPurchaseReceiptReportService stockPurchaseReceiptReportService;
    @Autowired
    private ITranCarInfoService tranCarInfoService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private ICommonStaffService staffService;
    @Autowired
    private QRCodeUtil qrCodeUtil;
    @Autowired
    private IStockSaleReceiptReportService stockSaleReceiptReportService;
    @Autowired
    private IInOutWarehouseTaskService inOutWarehouseTaskService;
    @Autowired
    private IContractInventoryDistributionService contractInventoryDistributionService;
    @Autowired
    private IWarehousePositionInfoService warehousePositionInfoService;
    @Autowired
    private ITranTaskInfoService tranTaskInfoService;
    @Autowired
    private ITranProcessInfoService tranProcessInfoService;
    @Autowired
    private ICostManagementInfoService costManagementInfoService;
    @Autowired
    private INewWorkflowService workflowService;

    @Autowired
    private CacheComponent cacheComponent;

    /**
     * 检斤管理列表
     * @param weighingManagement
     * @return
     */
    @Override
    public Page<WeighingManagement> selectWeighingManagement(WeighingManagement weighingManagement) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (weighingManagement.getCurrentPage() - 1)
                * weighingManagement.getPageSize());
        //公司id
        if (weighingManagement.getCompId() == null || weighingManagement.getCompId().isEmpty()) {
            weighingManagement.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
        }
        pageView.put("compId", weighingManagement.getCompId());
        pageView.put("number", weighingManagement.getNumber());
        pageView.put("searchKeyWord", weighingManagement.getSearchKeyWord());
        pageView.put("serviceManagementType",weighingManagement.getServiceManagementType());
        pageView.put("startDate", weighingManagement.getStartDate());
        pageView.put("endDate", weighingManagement.getEndDate());
        pageView.put("statusType",weighingManagement.getStatusType());
        if(StringUtils.isEmpty(weighingManagement.getViewFlag())){
            pageView.put("pageSize", weighingManagement.getPageSize());
            pageView.put("currentPage", weighingManagement.getCurrentPage());
        }
        pageView.put("managementType", weighingManagement.getManagementType());
        pageView.put("warehouseName", weighingManagement.getWarehouseName());
        List<WeighingManagement> listRedis = cacheComponent.getObjList(Const.ADMIN_WEIGHINGINFO+JSONObject.toJSONString(pageView),WeighingManagement.class);
        if(listRedis != null && listRedis.size() > 0 ){
            Long countRedis = Long.parseLong(cacheComponent.getRaw(Const.ADMIN_WEIGHINGINFO_NUM+JSONObject.toJSONString(pageView)));
            Page<WeighingManagement> page = new Page<>();
            page.setRecords(listRedis == null ? Lists.newArrayList() : listRedis);
            page.setTotal(countRedis == null ? 0 : countRedis);
            page.setCurrent(weighingManagement.getCurrentPage());
            page.setSize(weighingManagement.getPageSize());
            return page;
        }
        // 查询销售订单总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<WeighingManagement> dataList = baseMapper.getListByCondition(pageView);

        if(StringUtils.isEmpty(weighingManagement.getViewFlag())){
            if (CollectionUtils.isNotEmpty(dataList)) {
                for (WeighingManagement weighingManagement1 : dataList) {
                    CommonCompany commonCompany = commonCompanyService.selectOne(new EntityWrapper<CommonCompany>()
                            .eq("comp_id", weighingManagement1.getCompId()));
                    //公司名
                    if (commonCompany != null) {
                        weighingManagement1.setCompName(commonCompany.getCompName());
                    }
                    PaymentManagement paymentManagement = paymentManagementService.selectOne(new EntityWrapper<PaymentManagement>()
                            .eq("relation_id", weighingManagement1.getRelationId())
                            .eq("comp_id", weighingManagement1.getCompId()));
                    if (paymentManagement != null) {
                        weighingManagement1.setPaymentManagement(paymentManagement);
                    }
                    ContractManagementInfo contractManagementInfo=contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                            .eq("comp_id",weighingManagement1.getCompId())
                            .eq("contract_no",weighingManagement1.getContractNo()));
                    if (contractManagementInfo!=null){
                        weighingManagement1.setContractManagement(contractManagementInfo);
                    }
                    QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                            .eq("relation_id", weighingManagement1.getRelationId())
                            .eq("comp_id", weighingManagement1.getCompId()));
                    if (qualityInspectionManagement != null) {
                        weighingManagement1.setQualityInspectionManagement(qualityInspectionManagement);
                    }
                    WarehouseInOutInfo warehouseInOutInfo=warehouseInOutInfoService.selectById(weighingManagement1.getWarehouseInOutId());
                    if (warehouseInOutInfo!=null){
                        InOutWarehouseTask inOutWarehouseTask=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                .eq("in_out_task_no",warehouseInOutInfo.getInOutTaskNo())
                                .eq("comp_id",weighingManagement1.getCompId()));
                        if (inOutWarehouseTask!=null){
                            weighingManagement1.setCompletedQuantity(inOutWarehouseTask.getCompletedQuantity());
                            weighingManagement1.setWeight(inOutWarehouseTask.getWeight());
                        }
                        weighingManagement1.setTranCarNo(warehouseInOutInfo.getTranCarNo());
                        WarehouseInOutDetail warehouseInOutDetail=warehouseInOutDetailService.selectOne(new EntityWrapper<WarehouseInOutDetail>()
                                .eq("info_id", warehouseInOutInfo.getId()));
                        if (warehouseInOutDetail!=null){
                            weighingManagement1.setInOutDetailId(warehouseInOutDetail.getId());
                        }
                    }
                    WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                            .eq("comp_id", weighingManagement1.getCompId())
                            .eq("warehouse_name", weighingManagement1.getWarehouseName()));
                    if (warehouseBaseInfo != null) {
                        //仓库负责人,电话
                        weighingManagement1.setPerson(warehouseBaseInfo.getPersonCharge());
                        weighingManagement1.setPersonPhone(warehouseBaseInfo.getPersonPhone());
                        weighingManagement1.setAutomaticWeightAcquisition(warehouseBaseInfo.getAutomaticWeightAcquisition());
                    }
                }
            }
        }

        cacheComponent.putRaw(Const.ADMIN_WEIGHINGINFO+JSONObject.toJSONString(pageView), JSONObject.toJSONString(dataList),60*60*24);
        cacheComponent.putRaw(Const.ADMIN_WEIGHINGINFO_NUM+JSONObject.toJSONString(pageView), dataList.size()+"",60*60*24);

        Page<WeighingManagement> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(weighingManagement.getCurrentPage());
        page.setSize(weighingManagement.getPageSize());
        return page;
    }

    /**
     * 毛重检斤
     * @param weighingManagement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editGrossWeight(WeighingManagement weighingManagement) {
        //状态改为已称毛重
        weighingManagement.setStatus(StatusEnum.WEIGHED_GROSS_WEIGHT.getName());
        weighingManagement.setStatusFlag(StatusEnum.WEIGHED_GROSS_WEIGHT.getFlag());
        weighingManagement.setGrossDate(new Date());
        CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        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 ("3".equals(weighingManagement.getManagementType())){
//
//
//
//            WeighingManagement weighingManagement1=this.selectById(weighingManagement.getId());
//            //查关联的收款信息
//            PaymentManagement paymentManagement=paymentManagementService.selectOne(new EntityWrapper<PaymentManagement>()
//                    .eq("relation_id",weighingManagement1.getRelationId()));
//            if (paymentManagement!=null){
//                paymentManagement.setNetWeight(weighingManagement.getGrossWeight());
//                paymentManagementService.updateById(paymentManagement);
//            }
//            else {
//                //生成收款信息
//                PaymentManagement paymentManagement1=new PaymentManagement();
//                paymentManagement1.setId(IdGenerator.generateUUID());
//                paymentManagement1.setRelationId(weighingManagement1.getRelationId());
//                paymentManagement1.setCompId(weighingManagement1.getCompId());
//                paymentManagement1.setCarNo(weighingManagement1.getCarNumber());
//                paymentManagement1.setGoodsName(weighingManagement1.getGoodsName());
//                paymentManagement1.setContractNo(weighingManagement1.getContractNo());
//                paymentManagement1.setGrossWeight(weighingManagement.getGrossWeight());
//                paymentManagement1.setTare(weighingManagement1.getTare());
//                paymentManagement1.setNetWeight(weighingManagement.getNetWeight());
//                //计算应收
//                paymentManagement1.setCalculationCollectable(weighingManagement1.getContractPrice()*weighingManagement.getNetWeight());
//                //实际应收
//                paymentManagement1.setActualCollectionment(paymentManagement1.getCalculationCollectable());
//                //未收
//                paymentManagement1.setAmountNotCollectable(paymentManagement1.getCalculationCollectable());
//                //已收
//                paymentManagement1.setAmountEdCollectionable(0.0f);
//                paymentManagement1.setManagementType("3");
//                paymentManagement1.setWarehouseName(weighingManagement1.getWarehouseName());
//                paymentManagementService.insert(paymentManagement1);
//            }
//        }

        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        if( weighingManagement.getGrossWeight() == null || weighingManagement.getGrossWeight() == 0){
            throw new YException(YExceptionEnum.GROSSWEIGHT_NULL);
        }
        boolean one = this.updateById(weighingManagement);
        if (one) {
            return weighingManagement.getId();
        } else {
            return "NG";
        }
    }

    /**
     * 皮重检斤
     * @param weighingManagement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editTare(WeighingManagement weighingManagement) {
        WeighingManagement weighingManagement1=this.selectById(weighingManagement.getId());
        //状态改为已称皮重
        weighingManagement.setStatus(StatusEnum.TARED.getName());
        weighingManagement.setStatusFlag(StatusEnum.TARED.getFlag());
        weighingManagement.setTareDate(new Date());
        CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        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())){
            //更新任务已完成量
            InOutWarehouseTask inOutWarehouseTask=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                    .eq("comp_id", weighingManagement1.getCompId())
                    .eq("contract_no", weighingManagement1.getContractNo())
                    .eq("delete_flag", "0")
                    .orderBy("update_date", false));
            if (inOutWarehouseTask!=null){
                //可超出重量
                Float overNeight = 0.0f;
                ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                        .eq("comp_id", weighingManagement1.getCompId())
                        .eq("contract_no", weighingManagement1.getContractNo()));
                //合同溢短装
                if (contractManagementInfo != null) {
                    overNeight = inOutWarehouseTask.getWeight() * (contractManagementInfo.getOverShort() / 100);
                }
                inOutWarehouseTask.setCompletedQuantity(inOutWarehouseTask.getCompletedQuantity() + weighingManagement.getNetWeight()/1000);
                if (inOutWarehouseTask.getCompletedQuantity() > inOutWarehouseTask.getWeight() + overNeight) {
                    throw new YException(YExceptionEnum.TASK_WEIGHT_EXCEEDED_ERROR);
                } else {
                    inOutWarehouseTaskService.updateById(inOutWarehouseTask);
                }
            }
            //查关联的付款信息
            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());
//                if ("潮粮".equals(weighingManagement1.getType())){
//                    //查收购设置数据
//                    PurchasePrice purchasePrice=purchasePriceService.selectOne(new EntityWrapper<PurchasePrice>()
//                            .eq("warehouse_id",weighingManagement.getWarehouseId())
//                            .eq("goods_name",weighingManagement.getGoodsName()));
//                    Float pureWeight=weighingManagement.getNetWeight()* (100-(Float.valueOf(qualityInspectionManagement1.getWaterContent())-purchasePrice.getWaterMin())*purchasePrice.getDeductWeight())/100;
//                    paymentManagement1.setPureWeight(pureWeight);
//                }
                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);
        }

        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        boolean one = this.updateById(weighingManagement);
        if (one) {
            return weighingManagement.getId();
        } else {
            return "NG";
        }
    }

    /**
     * 删除检斤管理信息
     *  @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWeightcheck(String id) {
        //查询检斤管理信息
        WeighingManagement weighingManagement = this.selectById(id);
        if(weighingManagement != null){
            WarehouseInOutInfo warehouseInOutInfo = warehouseInOutInfoService.selectById(weighingManagement.getWarehouseInOutId());
            if(warehouseInOutInfo != null && warehouseInOutInfo.getInOutFlag()!=null){
                if("1".equals(warehouseInOutInfo.getInOutFlag())){
                    if ("3".equals(weighingManagement.getStatusFlag())){
                        throw new YException(YExceptionEnum.OUT_WEIGHT_STATUS_ERROR);
                    }
                }
                else{
                    if ("5".equals(weighingManagement.getStatusFlag())){
                        throw new YException(YExceptionEnum.IN_WEIGHT_STATUS_ERROR);
                    }
                }
            }
            //无关联的付款信息时可删除
            PaymentManagement paymentManagement = paymentManagementService.selectOne(new EntityWrapper<PaymentManagement>()
                    .eq("relation_id", weighingManagement.getRelationId())
                    .eq("comp_id", weighingManagement.getCompId())
                    .eq("delete_flag","0"));
            if (paymentManagement==null){
                //删除关联的质检信息
                QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                        .eq("relation_id", weighingManagement.getRelationId())
                        .eq("comp_id", weighingManagement.getCompId()));
                //删除检斤管理信息,质检管理信息
                this.deleteById(weighingManagement.getId());
                qualityInspectionManagementService.deleteById(qualityInspectionManagement.getId());
                if(warehouseInOutInfo != null){
                    if ("3".equals(warehouseInOutInfo.getStatusFlag())){
                        throw new YException(YExceptionEnum.IN_OUT_STATUS_ERROR);
                    }
                    warehouseInOutInfoService.deleteById(weighingManagement.getWarehouseInOutId());
                }
            }
            else{
                throw new YException(YExceptionEnum.PAYMENT_NOT_DELETED_ERROR);
            }
        }
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
    }

    /**
     * 查看检斤信息
     * @param id
     * @return
     */
    @Override
    public WeighingManagement getWeighingManagement(String id) {
        WeighingManagement weighingManagement = this.selectById(id);
        if (weighingManagement!=null){
            if(weighingManagement.getWarehouseInOutId()!=null){
                WarehouseInOutInfo warehouseInOutInfo =
                        warehouseInOutInfoService.selectById(weighingManagement.getWarehouseInOutId());
                if(warehouseInOutInfo!= null){
                    weighingManagement.setPositionId(warehouseInOutInfo.getPositionId());
                    weighingManagement.setSelfLoading(warehouseInOutInfo.getSelfLoading());
                }
            }
            CommonCompany commonCompany=commonCompanyService.selectOne(new EntityWrapper<CommonCompany>()
                    .eq("comp_id",weighingManagement.getCompId()));
            //公司名
            if (commonCompany!=null){
                weighingManagement.setCompName(commonCompany.getCompName());
            }
            ContractManagementInfo contractManagementInfo=contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                    .eq("comp_id",weighingManagement.getCompId())
                    .eq("contract_no",weighingManagement.getContractNo()));
            if (contractManagementInfo!=null){
                weighingManagement.setContractManagement(contractManagementInfo);
            }
            WarehouseBaseInfo warehouseBaseInfo=warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                    .eq("comp_id",weighingManagement.getCompId())
                    .eq("warehouse_name",weighingManagement.getWarehouseName()));
            if (warehouseBaseInfo!=null){
                //仓库负责人,电话
                weighingManagement.setPerson(warehouseBaseInfo.getPersonCharge());
                weighingManagement.setPersonPhone(warehouseBaseInfo.getPersonPhone());
            }
            //质检信息
            QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                    .eq("relation_id", weighingManagement.getRelationId())
                    .eq("comp_id", weighingManagement.getCompId()));
            if (qualityInspectionManagement!=null) {
                weighingManagement.setQualityInspectionManagement(qualityInspectionManagement);
            }
            WarehouseInOutDetail warehouseInOutDetail=warehouseInOutDetailService.selectOne(new EntityWrapper<WarehouseInOutDetail>()
                    .eq("info_id", weighingManagement.getWarehouseInOutId()));
            if (warehouseInOutDetail!=null){
                weighingManagement.setInOutDetailId(warehouseInOutDetail.getId());
            }
            weighingManagement.setCodeUrl(qrCodeUtil.generateQRCodeImage(qualityInspectionManagement.getCompId()+"&"+qualityInspectionManagement.getQualityNo()+"&"+warehouseBaseInfo.getId(),800,800,"",qualityInspectionManagement.getId()));

        }
        return weighingManagement;
    }

    /**
     * 查询业务编号
     * @param
     * @return
     */
    @Override
    public List<WeighingManagement> selectWeighingManagementList(WeighingManagement weighingManagement) {
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String date = f.format(new Date(System.currentTimeMillis()));
        Map<String, Object> pageView = new HashMap<>(7);
        pageView.put("date", date);
        pageView.put("warehouseNo", weighingManagement.getWarehouseNo());
        pageView.put("numberLetter", weighingManagement.getNumberLetter());
        pageView.put("compId", weighingManagement.getCompId());
        List<WeighingManagement> dataList = baseMapper.getListByConditions(pageView);
        return dataList;
    }


    /**
     * 出库管理添加皮重检斤管理信息
     * @param weighingManagement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addTare(WeighingManagement weighingManagement) {
        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 = this.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 =
                this.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.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());

        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        boolean two=qualityInspectionManagementService.insert(qualityInspectionManagement);
        boolean one=this.insert(weighingManagement);
        //成功返回ok
        if (one &&two ) {
            return weighingManagement.getId();
        } else {
            return "NG";
        }
    }

    /**
     * 出库管理编辑皮重检斤管理信息
     * @param weighingManagement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editTareOut(WeighingManagement weighingManagement) {
        //状态改为已称皮重
        weighingManagement.setStatus(StatusEnum.TARED.getName());
        weighingManagement.setStatusFlag(StatusEnum.TARED.getFlag());

        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        //更新检斤信息
        boolean one = this.updateById(weighingManagement);
        //更新质检信息
        boolean two = qualityInspectionManagementService.updateById(weighingManagement.getQualityInspectionManagement());
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        //成功返回ok
        if (one &&two ) {
            return weighingManagement.getId();
        } else {
            return "NG";
        }

    }

    /**
     * 扫描二维码
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public WeighingManagement getQRcode(WeighingManagement weighingManagement) {
        //查询检斤信息
        WeighingManagement weighingManagement1 = this.selectOne(new EntityWrapper<WeighingManagement>()
            .eq("comp_id",weighingManagement.getCompId())
            .eq("number",weighingManagement.getNumber())
            .eq("delete_flag","0"));
        //查询质检信息
        QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                .eq("comp_id",weighingManagement.getCompId())
                .eq("quality_no",weighingManagement.getNumber())
                .eq("delete_flag","0"));
        weighingManagement1.setQualityInspectionManagement(qualityInspectionManagement);
        //查询付款信息
        PaymentManagement paymentManagement = paymentManagementService.selectOne(new EntityWrapper<PaymentManagement>()
                .eq("comp_id",weighingManagement.getCompId())
                .eq("payment_no",weighingManagement.getNumber())
                .eq("delete_flag","0"));
        weighingManagement1.setPaymentManagement(paymentManagement);
        //查询仓库信息
        WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                .eq("id",weighingManagement.getWarehouseId())
                .eq("delete_flag","0"));
        weighingManagement1.setWarehouseBaseInfo(warehouseBaseInfo);
        return weighingManagement1;
    }

    /**
     * 退回
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String weightReturn(WeighingManagement weighingManagement) {
        //查询检斤信息表
        WeighingManagement weighingManagement1 = this.selectById(weighingManagement.getId());
        //查询出入库表
        WarehouseInOutInfo warehouseInOutInfo = warehouseInOutInfoService.selectById(weighingManagement1.getWarehouseInOutId());
        if(weighingManagement1.getWarehouseInOutId() != null){
            if(warehouseInOutInfo!= null && "3".equals(warehouseInOutInfo.getStatusFlag())){
                //状态改为已暂存
                warehouseInOutInfo.setStatusFlag(StatusEnum.TEMPORARILY_STORED.getFlag());
                warehouseInOutInfo.setStatus(StatusEnum.TEMPORARILY_STORED.getName());
                //更新出入库表信息
                warehouseInOutInfoService.updateById(warehouseInOutInfo);
                //查询仓位库存信息
                WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                        .eq("position_id",warehouseInOutInfo.getPositionId())
                        .eq("goods_name",warehouseInOutInfo.getGoodsName())
                        .eq("delete_flag","0"));
                if(warehousePositionStorageInfo != null){
                    //更新仓位库存信息
                    warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() - weighingManagement1.getNetWeight()/1000);
                    warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
                }
                //减去任务已完成量
                InOutWarehouseTask inOutWarehouseTask=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                        .eq("in_out_task_no",warehouseInOutInfo.getInOutTaskNo()));
                if (inOutWarehouseTask!=null){
                    inOutWarehouseTask.setCompletedQuantity(inOutWarehouseTask.getCompletedQuantity()-warehouseInOutInfo.getNetWeight());
                    inOutWarehouseTaskService.updateById(inOutWarehouseTask);
                }
            }
        }
        //收购入库
        if(weighingManagement1 != null && "3".equals(weighingManagement1.getServiceManagementType())){
            //状态改为已称毛重
            weighingManagement1.setStatus(StatusEnum.WEIGHED_GROSS_WEIGHT.getName());
            weighingManagement1.setStatusFlag(StatusEnum.WEIGHED_GROSS_WEIGHT.getFlag());
            //更新检斤信息
            this.updateById(weighingManagement1);

            //查询付款信息表
            PaymentManagement paymentManagement = paymentManagementService.selectOne(new EntityWrapper<PaymentManagement>()
                        .eq("payment_no",weighingManagement1.getNumber())
                        .eq("delete_flag","0"));
            //删除付款表数据,delete_flag改为1
            paymentManagement.setDeleteFlag("1");
            paymentManagementService.updateById(paymentManagement);
        }
        //采购入库
        else if(weighingManagement1 != null && "1".equals(weighingManagement1.getServiceManagementType())){
            //状态改为已称毛重
            weighingManagement1.setStatus(StatusEnum.WEIGHED_GROSS_WEIGHT.getName());
            weighingManagement1.setStatusFlag(StatusEnum.WEIGHED_GROSS_WEIGHT.getFlag());
            //更新检斤信息
            this.updateById(weighingManagement1);
            if(weighingManagement1.getWarehouseInOutId() != null){
                if(warehouseInOutInfo != null){
                    if(warehouseInOutInfo.getCarId() != null ){
                        //查询派车信息表
                        TranCarInfo tranCarInfo = tranCarInfoService.selectOne(new EntityWrapper<TranCarInfo>()
                                .eq("car_no",warehouseInOutInfo.getCarNo())
                                .eq("delete_flag","0"));
                        if(tranCarInfo != null){
                            tranCarInfo.setSubmit("2");
                            //汽运状态改为已装车
                            tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                            tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                            //更新派车信息表
                            tranCarInfoService.updateById(tranCarInfo);
                        }
                    }
                    //查询采购入库报表
                    StockPurchaseReceiptReport stockPurchaseReceiptReport = stockPurchaseReceiptReportService.selectOne(new EntityWrapper<StockPurchaseReceiptReport>()
                            .eq("warehouse_record_id",warehouseInOutInfo.getId())
                            .eq("delete_flag","0"));
                    if(stockPurchaseReceiptReport != null){
                        stockPurchaseReceiptReport.setDeleteFlag("1");
                        stockPurchaseReceiptReportService.updateById(stockPurchaseReceiptReport);
                    }
                }
            }
        }

        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        return "OK";
    }


    /**
     * 出库管理检斤退回
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String outWeightReturn(WeighingManagement weighingManagement) {
        //查询检斤信息表
        WeighingManagement weighingManagement1 = this.selectById(weighingManagement.getId());
        //状态改为已称皮重
        weighingManagement1.setStatus(StatusEnum.TARED.getName());
        weighingManagement1.setStatusFlag(StatusEnum.TARED.getFlag());
        //更新检斤信息
        this.updateById(weighingManagement1);
        //查询出入库表
        WarehouseInOutInfo warehouseInOutInfo = warehouseInOutInfoService.selectById(weighingManagement1.getWarehouseInOutId());
        if(weighingManagement1.getWarehouseInOutId() != null){
            if(warehouseInOutInfo!= null && "3".equals(warehouseInOutInfo.getStatusFlag())){
                //状态改为已暂存
                warehouseInOutInfo.setStatusFlag(StatusEnum.TEMPORARILY_STORED.getFlag());
                warehouseInOutInfo.setStatus(StatusEnum.TEMPORARILY_STORED.getName());
                //更新出入库表信息
                warehouseInOutInfoService.updateById(warehouseInOutInfo);
                //查询仓位库存信息
                WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                        .eq("position_id",warehouseInOutInfo.getPositionId())
                        .eq("goods_name",warehouseInOutInfo.getGoodsName())
                        .eq("delete_flag","0"));
                if(warehousePositionStorageInfo != null){
                    //更新仓位库存信息
                    warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() + weighingManagement1.getNetWeight()/1000);
                    warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
                }
                //减去任务已完成量
                InOutWarehouseTask inOutWarehouseTask=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                        .eq("in_out_task_no",warehouseInOutInfo.getInOutTaskNo()));
                if (inOutWarehouseTask!=null){
                    inOutWarehouseTask.setCompletedQuantity(inOutWarehouseTask.getCompletedQuantity()-warehouseInOutInfo.getNetWeight());
                    inOutWarehouseTaskService.updateById(inOutWarehouseTask);
                }
            }
        }
        //移库出库
        if(weighingManagement1 != null && "2".equals(weighingManagement1.getServiceManagementType()) && "移库出库".equals(weighingManagement1.getInOutType())){

            if(warehouseInOutInfo.getCarId() != null ){
                //查询派车信息表
                TranCarInfo tranCarInfo = tranCarInfoService.selectOne(new EntityWrapper<TranCarInfo>()
                        .eq("car_no",warehouseInOutInfo.getCarNo())
                        .eq("delete_flag","0"));
                if(tranCarInfo != null){
                    tranCarInfo.setSubmit("1");
                    //汽运状态改为已装车
                    tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                    tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                    //更新派车信息表
                    tranCarInfoService.updateById(tranCarInfo);
                }
            }
        }
        //销售出库
        else if(weighingManagement1 != null && "2".equals(weighingManagement1.getServiceManagementType()) && "销售出库".equals(weighingManagement1.getInOutType())){

            if(weighingManagement1.getWarehouseInOutId() != null){
                if(warehouseInOutInfo != null){
                    if(warehouseInOutInfo.getCarId() != null ){
                        //查询派车信息表
                        TranCarInfo tranCarInfo = tranCarInfoService.selectOne(new EntityWrapper<TranCarInfo>()
                                .eq("car_no",warehouseInOutInfo.getCarNo())
                                .eq("delete_flag","0"));
                        if(tranCarInfo != null){
                            tranCarInfo.setSubmit("1");
                            //汽运状态改为已装车
                            tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                            tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                            //更新派车信息表
                            tranCarInfoService.updateById(tranCarInfo);
                        }
                    }
                    //查询销售出库报表
                    StockSaleReceiptReport stockSaleReceiptReport = stockSaleReceiptReportService.selectOne(new EntityWrapper<StockSaleReceiptReport>()
                            .eq("warehouse_record_id",warehouseInOutInfo.getId())
                            .eq("delete_flag","0"));
                    if(stockSaleReceiptReport != null){
                        stockSaleReceiptReport.setDeleteFlag("1");
                        stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                    }
                }
            }
        }

        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        return "OK";
    }

    /**
     * 换仓
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String changeWarehouse(WeighingManagement weighingManagement) {
        //查询检斤信息
        WeighingManagement weighingManagement1 = this.selectById(weighingManagement.getId());
        if (weighingManagement1 != null){
            weighingManagement1.setBinNumber(weighingManagement.getChangeBinNumer());
            weighingManagement1.setPositionId(weighingManagement.getChangePositionId());
            this.updateById(weighingManagement1);
        }
        //查询质检信息
        QualityInspectionManagement qualityInspectionManagement = qualityInspectionManagementService.selectOne(new EntityWrapper<QualityInspectionManagement>()
                .eq("relation_id",weighingManagement1.getRelationId())
                .eq("delete_flag","0"));
        if (qualityInspectionManagement != null){
            qualityInspectionManagement.setBinNumber(weighingManagement.getChangeBinNumer());
            qualityInspectionManagementService.updateById(qualityInspectionManagement);
        }
        //查询出入库信息
        WarehouseInOutInfo warehouseInOutInfo = warehouseInOutInfoService.selectOne(new EntityWrapper<WarehouseInOutInfo>()
                .eq("id",weighingManagement1.getWarehouseInOutId())
                .eq("delete_flag","0"));
        if (warehouseInOutInfo != null){
            warehouseInOutInfo.setBinNumber(weighingManagement.getChangeBinNumer());
            warehouseInOutInfo.setPositionId(weighingManagement.getChangePositionId());
            warehouseInOutInfoService.updateById(warehouseInOutInfo);
        }
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        return "ok";
    }

    /**
     * 移库导入
     * @param weighingManagement
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importWeighing(WeighingManagement weighingManagement) {
        List<WeighingManagement> weighingManagementList=weighingManagement.getWeighingManagementList();
        InOutWarehouseTask inOutWarehouseTask=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
        .eq("in_out_task_no",weighingManagementList.get(0).getInOutTaskNo()));
        //合计净重
        double weight = weighingManagementList.stream().mapToDouble(WeighingManagement::getNetWeight).sum();
        //更新任务完成量
        inOutWarehouseTask.setCompletedQuantity(inOutWarehouseTask.getCompletedQuantity() + weight);
        if (inOutWarehouseTask.getCompletedQuantity() > inOutWarehouseTask.getWeight() + inOutWarehouseTask.getWeight() * 0.08f) {
            throw new YException(YExceptionEnum.TASK_WEIGHT_EXCEEDED_ERROR);
        } else {
            inOutWarehouseTaskService.updateById(inOutWarehouseTask);
        }
        //更新库存量
        WarehouseBaseInfo warehouseBaseInfo=warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                .eq("warehouse_name",weighingManagement.getWarehouseName())
                .eq("comp_id",inOutWarehouseTask.getCompId()));
        //  查询库位
        WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectOne(new EntityWrapper<WarehousePositionInfo>()
                .eq("base_id", warehouseBaseInfo.getId())
                .eq("delete_flag", "0"));
        if (warehousePositionInfo != null) {
            // 查询货物库存量
            WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                    .eq("position_id", warehousePositionInfo.getId())
                    .eq("goods_name", "玉米")
                    .eq("delete_flag", "0"));
            // 判断是否有货
            if (warehousePositionStorageInfo != null) {
                warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() + weight);
                warehousePositionStorageInfoService.updateById(warehousePositionStorageInfo);
            }
            // 没有货
            else {
                WarehousePositionStorageInfo warehousePositionStorageInfo1 = new WarehousePositionStorageInfo();
                warehousePositionStorageInfo1.setId(IdGenerator.generateUUID());
                warehousePositionStorageInfo1.setPositionId(warehousePositionInfo.getId());
                warehousePositionStorageInfo1.setBinNumber("1");
                warehousePositionStorageInfo1.setGoodsNameKey("1");
                warehousePositionStorageInfo1.setGoodsName("玉米");
                warehousePositionStorageInfo1.setStorage(weight);
                warehousePositionStorageInfoService.insert(warehousePositionStorageInfo1);
            }
        }
        for (WeighingManagement weighingManagement1:weighingManagementList) {
            //生成入库记录
            WarehouseInOutInfo warehouseInOutInfo = new WarehouseInOutInfo();
            warehouseInOutInfo.setId(IdGenerator.generateUUID());
            warehouseInOutInfo.setBaseId(warehouseBaseInfo.getId());
            warehouseInOutInfo.setInOutTaskNo(weighingManagement1.getInOutTaskNo());
            warehouseInOutInfo.setContractNo(inOutWarehouseTask.getMoveTaskNo());
            warehouseInOutInfo.setWarehouseName(weighingManagement.getWarehouseName());
            warehouseInOutInfo.setOutType(weighingManagement1.getOutType());
            warehouseInOutInfo.setInOutFlag("2");
            if(warehousePositionInfo!=null) {
                warehouseInOutInfo.setBinNumber("1");
                warehouseInOutInfo.setPositionId(warehousePositionInfo.getId());
            }
            warehouseInOutInfo.setGoodsNameKey("1");
            warehouseInOutInfo.setGoodsName("玉米");
            warehouseInOutInfo.setGrossWeight(weighingManagement1.getGrossWeight());
            warehouseInOutInfo.setTare(weighingManagement1.getTare());
            warehouseInOutInfo.setNetWeight(Double.valueOf(String.valueOf(weighingManagement1.getNetWeight())));
            warehouseInOutInfo.setInOutDate(weighingManagement1.getGrossDate());
            warehouseInOutInfo.setInOutTypeKey("3");
            warehouseInOutInfo.setInOutType("移库入库");
            warehouseInOutInfo.setCarNo(weighingManagement1.getCarNumber());
            warehouseInOutInfo.setStatusFlag(StatusEnum.SUBMITTED.getFlag());
            warehouseInOutInfo.setStatus(StatusEnum.SUBMITTED.getName());
            //生成入库详情
            WarehouseInOutDetail warehouseInOutDetail = new WarehouseInOutDetail();
            warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
            warehouseInOutDetail.setId(IdGenerator.generateUUID());
            String relationId = IdGenerator.generateUUID();
            QualityInspectionManagement qualityInspectionManagement = new QualityInspectionManagement();
            qualityInspectionManagement.setId(IdGenerator.generateUUID());
            qualityInspectionManagement.setWarehouseInOutId(warehouseInOutInfo.getId());
            qualityInspectionManagement.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
            qualityInspectionManagement.setRelationId(relationId);
            qualityInspectionManagement.setGoodsName("玉米");
            qualityInspectionManagement.setNatureOfGrainPurchase("贸易粮");
            qualityInspectionManagement.setBinNumber("1");
            qualityInspectionManagement.setServiceManagementType("1");
            qualityInspectionManagement.setQualityNo(weighingManagement1.getNumber());
            qualityInspectionManagement.setContractNo(inOutWarehouseTask.getMoveTaskNo());
            qualityInspectionManagement.setCarNumber(weighingManagement1.getCarNumber());
            qualityInspectionManagement.setWarehouseName(weighingManagement.getWarehouseName());
            qualityInspectionManagement.setInOutTaskNo(weighingManagement1.getInOutTaskNo());
            qualityInspectionManagement.setTips("出货库" + inOutWarehouseTask.getSendWarehouse());
            qualityInspectionManagement.setInOutTypeKey("3");
            qualityInspectionManagement.setInOutType("移库入库");
            qualityInspectionManagement.setQualityDate(weighingManagement1.getGrossDate());
            qualityInspectionManagement.setManagementType("1");
            qualityInspectionManagement.setType("干粮");
            qualityInspectionManagement.setConfirm("1");
            CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
            qualityInspectionManagement.setQualityInspector(commonStaff.getStaffName());
            qualityInspectionManagement.setReInspector(commonStaff.getStaffName());
            //状态为已复检
            qualityInspectionManagement.setStatus(StatusEnum.COMPLEX_INSPECTED.getName());
            qualityInspectionManagement.setStatusFlag(StatusEnum.COMPLEX_INSPECTED.getFlag());
            qualityInspectionManagement.setAgentKey(AuthSecurityUtils.getCurrentUserId());
            qualityInspectionManagement.setAgent(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getStaffName());
            //生成检斤信息
            weighingManagement1.setId(IdGenerator.generateUUID());
            weighingManagement1.setRelationId(relationId);
            weighingManagement1.setNumber(weighingManagement1.getNumber());
            weighingManagement1.setCarNumber(weighingManagement1.getCarNumber());
            weighingManagement1.setWarehouseInOutId(warehouseInOutInfo.getId());
            weighingManagement1.setContractNo(inOutWarehouseTask.getMoveTaskNo());
            weighingManagement1.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
            weighingManagement1.setServiceManagementType("1");
            weighingManagement1.setInOutTaskNo(weighingManagement1.getInOutTaskNo());
            weighingManagement1.setGoodsName("玉米");
            weighingManagement1.setType("干粮");
            weighingManagement1.setBinNumber("1");
            weighingManagement1.setOutType(weighingManagement1.getOutType());
            weighingManagement1.setSecretaryWeigher(commonStaff.getStaffName());
            weighingManagement1.setSkinInspector(commonStaff.getStaffName());
            weighingManagement1.setGrossWeight(weighingManagement1.getGrossWeight());
            weighingManagement1.setTare(weighingManagement1.getTare());
            weighingManagement1.setNetWeight(weighingManagement1.getNetWeight() * 1000);
            weighingManagement1.setManagementType("1");
            weighingManagement1.setWarehouseName(weighingManagement.getWarehouseName());
            weighingManagement1.setGrossDate(weighingManagement1.getGrossDate());
            weighingManagement1.setTareDate(weighingManagement1.getGrossDate());
            //状态为已称皮重
            weighingManagement1.setStatus(StatusEnum.TARED.getName());
            weighingManagement1.setStatusFlag(StatusEnum.TARED.getFlag());
            warehouseInOutInfoService.insert(warehouseInOutInfo);
            warehouseInOutDetailService.insert(warehouseInOutDetail);
            qualityInspectionManagementService.insert(qualityInspectionManagement);
            this.insert(weighingManagement1);
            InOutWarehouseTask inOutWarehouseTask1 = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                    .eq("move_task_no", inOutWarehouseTask.getMoveTaskNo())
                    .eq("in_out_flag", "1")
                    .eq("delete_flag", "0"));
            if (inOutWarehouseTask1 == null) {
                throw new YException(YExceptionEnum.TASK_NO_NOT_EXSITS_ERROR);
            } else {
                //若移库的发货库为自动创建的临时库时
                WarehouseBaseInfo warehouseBaseInfo1 = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                        .eq("warehouse_name", inOutWarehouseTask1.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) {
                        //现货采购入库报表
                        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(warehouseInOutInfo.getNetWeight());
                        stockPurchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                        stockPurchaseReceiptReport.setSettlementWeight(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 inOutWarehouseTask2 = 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", inOutWarehouseTask2.getCompId()).eq("inventory_type", "3").eq("warehouse", inOutWarehouseTask.getWarehouseName())
                            .eq("locus_warehouse", inOutWarehouseTask2.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(inOutWarehouseTask2.getWarehouseName());
                        contractInventoryDistribution2.setGoodsName(warehouseInOutInfo.getGoodsName());
                        contractInventoryDistribution2.setInventoryType("3");
                        contractInventoryDistributionService.insert(contractInventoryDistribution2);
                    }
                }
            }
        }
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        return "ok";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importWeighingOut(WeighingManagement weighingManagement) {
        List<WeighingManagement> weighingManagementList=weighingManagement.getWeighingManagementList();
        InOutWarehouseTask inOutWarehouseTask=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                .eq("in_out_task_no",weighingManagementList.get(0).getInOutTaskNo()));
        //合计净重
        double weight = weighingManagementList.stream().mapToDouble(WeighingManagement::getNetWeight).sum();
        //可超出重量
        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 {
            overNeight = inOutWarehouseTask.getWeight() * 0.05f;
        }
        inOutWarehouseTask.setCompletedQuantity(inOutWarehouseTask.getCompletedQuantity() + weight);
        if (inOutWarehouseTask.getCompletedQuantity() > inOutWarehouseTask.getWeight() + overNeight) {
            throw new YException(YExceptionEnum.TASK_WEIGHT_EXCEEDED_ERROR);
        } else {
            inOutWarehouseTaskService.updateById(inOutWarehouseTask);
        }
        //更新库存量
        WarehouseBaseInfo warehouseBaseInfo=warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                .eq("warehouse_name",weighingManagement.getWarehouseName())
                .eq("comp_id",inOutWarehouseTask.getCompId()));
        String positionId="";
        if ("1".equals(warehouseBaseInfo.getWarehouseType())) {
            //  查询库位
            WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectOne(new EntityWrapper<WarehousePositionInfo>()
                    .eq("base_id", warehouseBaseInfo.getId())
                    .eq("delete_flag", "0"));
            if (warehousePositionInfo != null) {
                positionId=warehousePositionInfo.getId();
                // 查询货物库存量
                WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                        .eq("position_id", warehousePositionInfo.getId())
                        .eq("goods_name", "玉米")
                        .eq("delete_flag", "0"));
                // 判断是否有货
                if (warehousePositionStorageInfo != null) {
                    if (weight <= warehousePositionStorageInfo.getStorage()) {
                        // 更新库存量
                        warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() - weight);
                        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);
            }
        }
        for (WeighingManagement weighingManagement1:weighingManagementList) {
            //生成出库记录
            WarehouseInOutInfo warehouseInOutInfo = new WarehouseInOutInfo();
            warehouseInOutInfo.setId(IdGenerator.generateUUID());
            warehouseInOutInfo.setBaseId(warehouseBaseInfo.getId());
            warehouseInOutInfo.setInOutTaskNo(weighingManagement1.getInOutTaskNo());
            warehouseInOutInfo.setContractNo(weighingManagement1.getContractNo());
            warehouseInOutInfo.setWarehouseName(weighingManagement.getWarehouseName());
            warehouseInOutInfo.setOutType(weighingManagement1.getOutType());
            warehouseInOutInfo.setInOutFlag("1");
            warehouseInOutInfo.setBinNumber("1");
            warehouseInOutInfo.setPositionId(positionId);
            warehouseInOutInfo.setGoodsNameKey("1");
            warehouseInOutInfo.setGoodsName("玉米");
            warehouseInOutInfo.setGrossWeight(weighingManagement1.getGrossWeight());
            warehouseInOutInfo.setTare(weighingManagement1.getTare());
            warehouseInOutInfo.setNetWeight(Double.valueOf(String.valueOf(weighingManagement1.getNetWeight())));
            warehouseInOutInfo.setInOutDate(weighingManagement1.getGrossDate());
            warehouseInOutInfo.setInOutTypeKey("3");
            warehouseInOutInfo.setInOutType("销售出库");
            warehouseInOutInfo.setCarNo(weighingManagement1.getCarNumber());
            warehouseInOutInfo.setStatusFlag(StatusEnum.SUBMITTED.getFlag());
            warehouseInOutInfo.setStatus(StatusEnum.SUBMITTED.getName());
            //生成入库详情
            WarehouseInOutDetail warehouseInOutDetail = new WarehouseInOutDetail();
            warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
            warehouseInOutDetail.setId(IdGenerator.generateUUID());
            warehouseInOutInfoService.insert(warehouseInOutInfo);
            warehouseInOutDetailService.insert(warehouseInOutDetail);
            //更新合同销售库存
            ContractInventoryDistribution contractInventoryDistribution = contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                    .eq("comp_id", warehouseBaseInfo.getCompId()).eq("inventory_type", "1").eq("contract_no", warehouseInOutInfo.getContractNo())
                    .eq("warehouse", warehouseInOutInfo.getWarehouseName()));
            if (contractInventoryDistribution != null) {
                contractInventoryDistribution.setSaleStorage(contractInventoryDistribution.getSaleStorage() + warehouseInOutInfo.getNetWeight());
                contractInventoryDistributionService.updateById(contractInventoryDistribution);
            }
            //常用库出库
            if ("1".equals(warehouseBaseInfo.getWarehouseType())) {
                String relationId = IdGenerator.generateUUID();
                QualityInspectionManagement qualityInspectionManagement = new QualityInspectionManagement();
                qualityInspectionManagement.setId(IdGenerator.generateUUID());
                qualityInspectionManagement.setWarehouseInOutId(warehouseInOutInfo.getId());
                qualityInspectionManagement.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
                qualityInspectionManagement.setRelationId(relationId);
                qualityInspectionManagement.setGoodsName("玉米");
                qualityInspectionManagement.setNatureOfGrainPurchase("贸易粮");
                qualityInspectionManagement.setBinNumber("1");
                qualityInspectionManagement.setServiceManagementType("2");
                qualityInspectionManagement.setQualityNo(weighingManagement1.getNumber());
                qualityInspectionManagement.setContractNo(weighingManagement1.getContractNo());
                qualityInspectionManagement.setCarNumber(weighingManagement1.getCarNumber());
                qualityInspectionManagement.setWarehouseName(weighingManagement.getWarehouseName());
                qualityInspectionManagement.setInOutTaskNo(weighingManagement1.getInOutTaskNo());
                qualityInspectionManagement.setInOutTypeKey("3");
                qualityInspectionManagement.setInOutType("销售出库");
                qualityInspectionManagement.setQualityDate(weighingManagement1.getGrossDate());
                qualityInspectionManagement.setManagementType("3");
                qualityInspectionManagement.setType("干粮");
                CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
                qualityInspectionManagement.setQualityInspector(commonStaff.getStaffName());
                qualityInspectionManagement.setReInspector(commonStaff.getStaffName());
                //状态为已称皮重
                qualityInspectionManagement.setStatus(StatusEnum.TARED.getName());
                qualityInspectionManagement.setStatusFlag(StatusEnum.TARED.getFlag());
                qualityInspectionManagement.setAgentKey(AuthSecurityUtils.getCurrentUserId());
                qualityInspectionManagement.setAgent(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getStaffName());
                //生成检斤信息
                weighingManagement1.setId(IdGenerator.generateUUID());
                weighingManagement1.setRelationId(relationId);
                weighingManagement1.setNumber(weighingManagement1.getNumber());
                weighingManagement1.setCarNumber(weighingManagement1.getCarNumber());
                weighingManagement1.setWarehouseInOutId(warehouseInOutInfo.getId());
                weighingManagement1.setContractNo(weighingManagement1.getContractNo());
                weighingManagement1.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
                weighingManagement1.setServiceManagementType("2");
                weighingManagement1.setInOutTaskNo(weighingManagement1.getInOutTaskNo());
                weighingManagement1.setGoodsName("玉米");
                weighingManagement1.setType("干粮");
                weighingManagement1.setBinNumber("1");
                weighingManagement1.setPositionId(positionId);
                weighingManagement1.setOutType(weighingManagement1.getOutType());
                weighingManagement1.setSecretaryWeigher(commonStaff.getStaffName());
                weighingManagement1.setSkinInspector(commonStaff.getStaffName());
                weighingManagement1.setContractPrice(weighingManagement1.getContractPrice());
                if (weighingManagement1.getGrossWeight()!=null) {
                    weighingManagement1.setGrossWeight(weighingManagement1.getGrossWeight() * 1000);
                    weighingManagement1.setTare(weighingManagement1.getTare() * 1000);
                }
                weighingManagement1.setNetWeight(weighingManagement1.getNetWeight() * 1000);
                weighingManagement1.setManagementType("3");
                weighingManagement1.setWarehouseName(weighingManagement.getWarehouseName());
                weighingManagement1.setGrossDate(weighingManagement1.getGrossDate());
                weighingManagement1.setTareDate(weighingManagement1.getGrossDate());
                //状态为已称皮重
                weighingManagement1.setStatus(StatusEnum.TARED.getName());
                weighingManagement1.setStatusFlag(StatusEnum.TARED.getFlag());
                qualityInspectionManagementService.insert(qualityInspectionManagement);
                this.insert(weighingManagement1);
                //他运的销售合同
                ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                        .eq("contract_no", warehouseInOutInfo.getContractNo())
                        .eq("deliver_type", "2")
                        .eq("contract_type", "1")
                        .eq("delete_flag", "0"));
                if (contractManagementInfo1 != null) {
                    if (contractManagementInfo1.getUnitContractPrice() == null) {
                        contractManagementInfo1.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());
                            tranCarInfo.setCarNo(warehouseInOutInfo.getCarNo());
                            tranCarInfo.setThreeTranType("汽运");
                            stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            tranCarInfoService.insert(tranCarInfo);
                        }
                    }
                    stockSaleReceiptReport.setContractNo(warehouseInOutInfo.getContractNo());
                    stockSaleReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                    stockSaleReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight()!=null?warehouseInOutInfo.getGrossWeight():0f)));
                    stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare()!=null?warehouseInOutInfo.getTare():0f)));
                    stockSaleReceiptReport.setNetWeight(warehouseInOutInfo.getNetWeight());
                    stockSaleReceiptReport.setDeliveryDate(warehouseInOutInfo.getInOutDate());
                    //按出库重量结算时
                    if ("1".equals(contractManagementInfo.getSettlementWeightMethod())) {
                        stockSaleReceiptReport.setSettlementWeight(weighingManagement1.getSettleWeight());
                    }
                    stockSaleReceiptReport.setSettlementPrice(weighingManagement1.getSettlePrice());
                    stockSaleReceiptReport.setAmountIngReceivable(weighingManagement1.getSettleMoney());
                    stockSaleReceiptReport.setAmountEdReceivable(0.00);
                    stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                    stockSaleReceiptReport.setStatusFlag(StatusEnum.TO_BE_RECEIVED.getFlag());
                    stockSaleReceiptReport.setStatus(StatusEnum.TO_BE_RECEIVED.getName());
                    CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId()));
                    if (costManagementInfo != null) {
                        stockSaleReceiptReport.setCost(costManagementInfo.getCost());

                    }
                    stockSaleReceiptReportService.insert(stockSaleReceiptReport);
                }
                //自运的销售合同
                ContractManagementInfo contractManagementInfo2 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                        .eq("contract_no", warehouseInOutInfo.getContractNo())
                        .eq("deliver_type", "1")
                        .eq("contract_type", "1")
                        .eq("delete_flag", "0"));
                if (contractManagementInfo2 != 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", contractManagementInfo2.getContractNo())
                            .eq("comp_id", contractManagementInfo2.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());
                            stockSaleReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                            List<TranCarInfo> tranCarInfoList = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                                    .eq("contract_no", contractManagementInfo2.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(contractManagementInfo2.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);
                        }
                    } 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()!=null?warehouseInOutInfo.getGrossWeight():0f)));
                    stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare()!=null?warehouseInOutInfo.getTare():0f)));
                    stockSaleReceiptReport.setNetWeight(warehouseInOutInfo.getNetWeight());
                    stockSaleReceiptReport.setDeliveryDate(warehouseInOutInfo.getInOutDate());
                    stockSaleReceiptReport.setSettlementWeight(weighingManagement1.getSettleWeight());
                    //按出库重量结算时
                    if ("1".equals(contractManagementInfo2.getSettlementWeightMethod())) {
                        stockSaleReceiptReport.setSettlementWeight(weighingManagement1.getSettleWeight());
                        stockSaleReceiptReport.setSettlementPrice(weighingManagement1.getSettlePrice());
                        stockSaleReceiptReport.setAmountIngReceivable(weighingManagement1.getSettleMoney());
                        stockSaleReceiptReport.setAmountEdReceivable(0.00);
                        stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                    }
                    stockSaleReceiptReport.setStatusFlag(StatusEnum.TO_BE_RECEIVED.getFlag());
                    stockSaleReceiptReport.setStatus(StatusEnum.TO_BE_RECEIVED.getName());
                    CostManagementInfo costManagementInfo = costManagementInfoService.selectOne(new EntityWrapper<CostManagementInfo>().eq("warehouse_id", warehouseInOutInfo.getBaseId()));
                    if (costManagementInfo != null) {
                        stockSaleReceiptReport.setCost(costManagementInfo.getCost());

                    }
                    stockSaleReceiptReportService.insert(stockSaleReceiptReport);
                }
            }
            //临时库出库
            else {
                //自动创建的临时库(采购报表进数据，销售报表也进数据)
                if ("1".equals(warehouseBaseInfo.getCreateType())) {
                    ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                            .eq("contract_no", warehouseBaseInfo.getWarehouseName())
                            .eq("deliver_type", "1")
                            .eq("delete_flag", "0"));
                    if (contractManagementInfo1 != null) {
                        //现货采购入库报表
                        StockPurchaseReceiptReport stockPurchaseReceiptReport = new StockPurchaseReceiptReport();
                        stockPurchaseReceiptReport.setId(IdGenerator.generateUUID());
                        stockPurchaseReceiptReport.setCompId(warehouseBaseInfo.getCompId());
                        stockPurchaseReceiptReport.setWarehouseRecordId(warehouseInOutInfo.getId());
                        stockPurchaseReceiptReport.setContractNo(contractManagementInfo1.getContractNo());
                        stockPurchaseReceiptReport.setWarehouseName(warehouseInOutInfo.getWarehouseName());
                        stockPurchaseReceiptReport.setCarNo(warehouseInOutInfo.getCarNo());
                        stockPurchaseReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight()!=null?warehouseInOutInfo.getGrossWeight():0f)));
                        stockPurchaseReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare()!=null?warehouseInOutInfo.getTare():0f)));
                        stockPurchaseReceiptReport.setNetWeight(warehouseInOutInfo.getNetWeight());
                        stockPurchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                        stockPurchaseReceiptReport.setSettlementWeight(warehouseInOutInfo.getNetWeight());
                        if (contractManagementInfo1.getUnitContractPrice() != null) {
                            stockPurchaseReceiptReport.setSettlementPrice(contractManagementInfo1.getUnitContractPrice());
                            stockPurchaseReceiptReport.setAmountIngPayable(warehouseInOutInfo.getNetWeight() * contractManagementInfo1.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 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()!=null?warehouseInOutInfo.getGrossWeight():0f)));
                    stockSaleReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare()!=null?warehouseInOutInfo.getTare():0f)));
                    stockSaleReceiptReport.setNetWeight(warehouseInOutInfo.getNetWeight());
                    stockSaleReceiptReport.setSettlementWeight(weighingManagement1.getSettleWeight());
                    stockSaleReceiptReport.setSettlementPrice(weighingManagement1.getSettlePrice());
                    stockSaleReceiptReport.setAmountEdReceivable(0.0d);
                    stockSaleReceiptReport.setDeliveryDate(warehouseInOutInfo.getInOutDate());
                    stockSaleReceiptReport.setAmountIngReceivable(weighingManagement1.getSettleMoney());
                    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());
                    }
                    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 inOutWarehouseTask1 = inOutWarehouseTaskService.selectOne(inOutWarehouseTaskWrapper);
                    if (inOutWarehouseTask1 != 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));
                            tranCarInfo.setInfoId(tranTaskInfo.getId());
                        } else {
                            throw new YException(YExceptionEnum.TRANTASK_NOT_CREATED_ERROR);
                        }
                        tranCarInfo.setCompId(warehouseBaseInfo.getCompId());
                        tranCarInfo.setTranType("1");
                        tranCarInfo.setSubmit("1");
                        //出库时打入成本
                        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);
                    }
                }
            }
        }
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        return "ok";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importWeighingMoveOut(WeighingManagement weighingManagement) {
        List<WeighingManagement> weighingManagementList=weighingManagement.getWeighingManagementList();
        InOutWarehouseTask inOutWarehouseTask=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                .eq("in_out_task_no",weighingManagementList.get(0).getInOutTaskNo()));
        //合计净重
        double weight = weighingManagementList.stream().mapToDouble(WeighingManagement::getNetWeight).sum();
        inOutWarehouseTask.setCompletedQuantity(inOutWarehouseTask.getCompletedQuantity() + weight);
        if (inOutWarehouseTask.getCompletedQuantity() > inOutWarehouseTask.getWeight() + inOutWarehouseTask.getWeight() * 0.05f) {
            throw new YException(YExceptionEnum.TASK_WEIGHT_EXCEEDED_ERROR);
        } else {
            inOutWarehouseTaskService.updateById(inOutWarehouseTask);
        }
        //更新库存量
        WarehouseBaseInfo warehouseBaseInfo=warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                .eq("warehouse_name",weighingManagement.getWarehouseName())
                .eq("comp_id",inOutWarehouseTask.getCompId()));
        String positionId="";
        if ("1".equals(warehouseBaseInfo.getWarehouseType())) {
            //  查询库位
            WarehousePositionInfo warehousePositionInfo = warehousePositionInfoService.selectOne(new EntityWrapper<WarehousePositionInfo>()
                    .eq("base_id", warehouseBaseInfo.getId())
                    .eq("delete_flag", "0"));
            if (warehousePositionInfo != null) {
                positionId=warehousePositionInfo.getId();
                // 查询货物库存量
                WarehousePositionStorageInfo warehousePositionStorageInfo = warehousePositionStorageInfoService.selectOne(new EntityWrapper<WarehousePositionStorageInfo>()
                        .eq("position_id", warehousePositionInfo.getId())
                        .eq("goods_name", "玉米")
                        .eq("delete_flag", "0"));
                // 判断是否有货
                if (warehousePositionStorageInfo != null) {
                    if (weight <= warehousePositionStorageInfo.getStorage()) {
                        // 更新库存量
                        warehousePositionStorageInfo.setStorage(warehousePositionStorageInfo.getStorage() - weight);
                        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);
            }
        }
        for (WeighingManagement weighingManagement1:weighingManagementList) {
            //生成出库记录
            WarehouseInOutInfo warehouseInOutInfo = new WarehouseInOutInfo();
            warehouseInOutInfo.setId(IdGenerator.generateUUID());
            warehouseInOutInfo.setBaseId(warehouseBaseInfo.getId());
            warehouseInOutInfo.setInOutTaskNo(weighingManagement1.getInOutTaskNo());
            warehouseInOutInfo.setContractNo(inOutWarehouseTask.getMoveTaskNo());
            warehouseInOutInfo.setWarehouseName(weighingManagement.getWarehouseName());
            warehouseInOutInfo.setOutType(weighingManagement1.getOutType());
            warehouseInOutInfo.setInOutFlag("1");
            warehouseInOutInfo.setBinNumber("1");
            warehouseInOutInfo.setPositionId(positionId);
            warehouseInOutInfo.setGoodsNameKey("1");
            warehouseInOutInfo.setGoodsName("玉米");
            warehouseInOutInfo.setGrossWeight(weighingManagement1.getGrossWeight());
            warehouseInOutInfo.setTare(weighingManagement1.getTare());
            warehouseInOutInfo.setNetWeight(Double.valueOf(String.valueOf(weighingManagement1.getNetWeight())));
            warehouseInOutInfo.setInOutDate(weighingManagement1.getGrossDate());
            warehouseInOutInfo.setInOutTypeKey("3");
            warehouseInOutInfo.setInOutType("移库出库");
            warehouseInOutInfo.setCarNo(weighingManagement1.getCarNumber());
            warehouseInOutInfo.setStatusFlag(StatusEnum.SUBMITTED.getFlag());
            warehouseInOutInfo.setStatus(StatusEnum.SUBMITTED.getName());
            //生成入库详情
            WarehouseInOutDetail warehouseInOutDetail = new WarehouseInOutDetail();
            warehouseInOutDetail.setInfoId(warehouseInOutInfo.getId());
            warehouseInOutDetail.setId(IdGenerator.generateUUID());
            String relationId = IdGenerator.generateUUID();
            QualityInspectionManagement qualityInspectionManagement = new QualityInspectionManagement();
            qualityInspectionManagement.setId(IdGenerator.generateUUID());
            qualityInspectionManagement.setWarehouseInOutId(warehouseInOutInfo.getId());
            qualityInspectionManagement.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
            qualityInspectionManagement.setRelationId(relationId);
            qualityInspectionManagement.setGoodsName("玉米");
            qualityInspectionManagement.setNatureOfGrainPurchase("贸易粮");
            qualityInspectionManagement.setBinNumber("1");
            qualityInspectionManagement.setServiceManagementType("2");
            qualityInspectionManagement.setQualityNo(weighingManagement1.getNumber());
            qualityInspectionManagement.setContractNo(inOutWarehouseTask.getMoveTaskNo());
            qualityInspectionManagement.setCarNumber(weighingManagement1.getCarNumber());
            qualityInspectionManagement.setWarehouseName(weighingManagement.getWarehouseName());
            qualityInspectionManagement.setInOutTaskNo(weighingManagement1.getInOutTaskNo());
            qualityInspectionManagement.setInOutTypeKey("3");
            qualityInspectionManagement.setInOutType("移库出库");
            qualityInspectionManagement.setQualityDate(weighingManagement1.getGrossDate());
            qualityInspectionManagement.setManagementType("3");
            qualityInspectionManagement.setType("干粮");
            CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
            qualityInspectionManagement.setQualityInspector(commonStaff.getStaffName());
            qualityInspectionManagement.setReInspector(commonStaff.getStaffName());
            //状态为已称皮重
            qualityInspectionManagement.setStatus(StatusEnum.TARED.getName());
            qualityInspectionManagement.setStatusFlag(StatusEnum.TARED.getFlag());
            qualityInspectionManagement.setAgentKey(AuthSecurityUtils.getCurrentUserId());
            qualityInspectionManagement.setAgent(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getStaffName());
            //生成检斤信息
            weighingManagement1.setId(IdGenerator.generateUUID());
            weighingManagement1.setRelationId(relationId);
            weighingManagement1.setNumber(weighingManagement1.getNumber());
            weighingManagement1.setCarNumber(weighingManagement1.getCarNumber());
            weighingManagement1.setWarehouseInOutId(warehouseInOutInfo.getId());
            weighingManagement1.setContractNo(inOutWarehouseTask.getMoveTaskNo());
            weighingManagement1.setCompId(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getCompId());
            weighingManagement1.setServiceManagementType("2");
            weighingManagement1.setInOutTaskNo(weighingManagement1.getInOutTaskNo());
            weighingManagement1.setGoodsName("玉米");
            weighingManagement1.setType("干粮");
            weighingManagement1.setBinNumber("1");
            weighingManagement1.setPositionId(positionId);
            weighingManagement1.setOutType(weighingManagement1.getOutType());
            weighingManagement1.setSecretaryWeigher(commonStaff.getStaffName());
            weighingManagement1.setSkinInspector(commonStaff.getStaffName());
            if (weighingManagement1.getGrossWeight()!=null) {
                weighingManagement1.setGrossWeight(weighingManagement1.getGrossWeight() * 1000);
                weighingManagement1.setTare(weighingManagement1.getTare() * 1000);
            }
            weighingManagement1.setNetWeight(weighingManagement1.getNetWeight() * 1000);
            weighingManagement1.setManagementType("3");
            weighingManagement1.setWarehouseName(weighingManagement.getWarehouseName());
            weighingManagement1.setGrossDate(weighingManagement1.getGrossDate());
            weighingManagement1.setTareDate(weighingManagement1.getGrossDate());
            //状态为已称皮重
            weighingManagement1.setStatus(StatusEnum.TARED.getName());
            weighingManagement1.setStatusFlag(StatusEnum.TARED.getFlag());
            warehouseInOutInfoService.insert(warehouseInOutInfo);
            warehouseInOutDetailService.insert(warehouseInOutDetail);
            qualityInspectionManagementService.insert(qualityInspectionManagement);
            this.insert(weighingManagement1);
            //更新合同移库库存
            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);
            }
            //常用库出库
            if ("1".equals(warehouseBaseInfo.getWarehouseType())) {
                InOutWarehouseTask inOutWarehouseTask1 = inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                        .eq("move_task_no", warehouseInOutInfo.getContractNo())
                        .eq("in_out_flag", "1")
                        .eq("delete_flag", "0"));
                if (inOutWarehouseTask1 != null) {
                    //更新所属仓库收购库存
                    ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                            .eq("comp_id",inOutWarehouseTask1.getCompId()).eq("inventory_type","3").eq("warehouse",inOutWarehouseTask1.getWarehouseName())
                            .eq("locus_warehouse",inOutWarehouseTask1.getWarehouseName())
                            .eq("goods_name",warehouseInOutInfo.getGoodsName()));
                    if (contractInventoryDistribution!=null){
                        contractInventoryDistribution.setInventory(contractInventoryDistribution.getInventory()-warehouseInOutInfo.getNetWeight());
                        contractInventoryDistributionService.updateById(contractInventoryDistribution);
                    }
                    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));
                    } 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);
                }
            }
            //临时库出库
            else {
                //更新合同移库库存
                ContractInventoryDistribution contractInventoryDistribution2=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                        .eq("comp_id",warehouseBaseInfo.getCompId()).eq("inventory_type","1").eq("contract_no",warehouseInOutInfo.getContractNo())
                        .eq("warehouse",warehouseInOutInfo.getWarehouseName()));
                if (contractInventoryDistribution2!=null){
                    contractInventoryDistribution2.setRemoveStorage(contractInventoryDistribution2.getRemoveStorage()+warehouseInOutInfo.getNetWeight());
                    contractInventoryDistributionService.updateById(contractInventoryDistribution2);
                }
                //按出库重量结算
                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());
                    if(warehouseInOutInfo.getGrossWeight()!=null) {
                        stockPurchaseReceiptReport.setGrossWeight(Double.valueOf(String.valueOf(warehouseInOutInfo.getGrossWeight())));
                        stockPurchaseReceiptReport.setTare(Double.valueOf(String.valueOf(warehouseInOutInfo.getTare())));
                    }
                    stockPurchaseReceiptReport.setNetWeight(warehouseInOutInfo.getNetWeight());
                    stockPurchaseReceiptReport.setWarehousingDate(warehouseInOutInfo.getInOutDate());
                    stockPurchaseReceiptReport.setSettlementWeight(warehouseInOutInfo.getNetWeight());
                    if (contractManagementInfo.getUnitContractPrice() != null) {
                        stockPurchaseReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(contractManagementInfo.getUnitContractPrice())));
                        stockPurchaseReceiptReport.setAmountIngPayable(warehouseInOutInfo.getNetWeight() *
                                (Double.valueOf(String.valueOf(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());
                    }
                }
                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 inOutWarehouseTask1 = inOutWarehouseTaskService.selectOne(inOutWarehouseTaskWrapper);
                if (inOutWarehouseTask1 != 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));
                        tranCarInfo.setInfoId(tranTaskInfo.getId());
                    } else {
                        throw new YException(YExceptionEnum.TRANTASK_NOT_CREATED_ERROR);
                    }
                    tranCarInfo.setCompId(warehouseBaseInfo.getCompId());
                    tranCarInfo.setTranType("1");
                    tranCarInfo.setSubmit("1");
                    //出库时打入成本
                    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);
                }
            }
        }
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO);
        cacheComponent.delPrefixKey(Const.ADMIN_WEIGHINGINFO_NUM);
        return "ok";
    }
}
