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

import com.alipay.sofa.runtime.api.annotation.SofaService;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsea.svc.base.base.entity.CommonStaff;
import com.winsea.svc.base.base.service.ICommonStaffService;
import com.winsea.svc.base.base.util.DateUtils;
import com.winsea.svc.base.workflow.entity.Workflow;
import com.winsea.svc.notice.entity.NoticeTaskInfo;
import com.winsea.svc.notice.entity.base.BaseNotice;
import com.winsea.svc.notice.service.INoticeService;
import com.winsea.svc.notice.service.INoticeTaskService;
import com.yh.saas.plugin.yiliangyiyun.entity.InOutWarehouseTask;
import com.yh.saas.plugin.yiliangyiyun.entity.PaymentManagement;
import com.yh.saas.plugin.yiliangyiyun.entity.WarehouseInOutInfo;
import com.yh.saas.plugin.yiliangyiyun.entity.WarehousingOrder;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.WarehousingOrderMapper;
import com.yh.saas.plugin.yiliangyiyun.service.IInOutWarehouseTaskService;
import com.yh.saas.plugin.yiliangyiyun.service.IWarehouseInOutInfoService;
import com.yh.saas.plugin.yiliangyiyun.service.IWarehousingOrderService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.winsea.svc.base.base.entity.CommonRoleResource;
import com.winsea.svc.base.base.service.ICommonRoleResourceService;
import com.winsea.svc.base.security.entity.User;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.base.service.ICommonBillOperateHisService;
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.service.*;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 记录入库单信息 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2022-05-17
 */
@Service
@Slf4j
public class WarehousingOrderServiceImpl extends ServiceImpl<WarehousingOrderMapper, WarehousingOrder> implements IWarehousingOrderService {
    @Autowired
    private IInOutWarehouseTaskService inOutWarehouseTaskService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    private INewWorkflowService workflowService;
    @SofaReference
    private ICommonRoleResourceService roleResourceService;
    @Autowired
    private IPaymentManagementService paymentManagementService;
    @Autowired
    private IContractInventoryDistributionService contractInventoryDistributionService;
    @Value("${file-root-path}")
    private String localPath;
    @Autowired
    private OSSClient ossClient;
    @Value("${oss.endpoint.internal:}")
    private String baseUrl;
    @Getter
    @Value("${oss.bucket.name:}")
    private String bucket;
    @Autowired
    private ICommonBillOperateHisService billOperateHisService;
    @Autowired
    private IExpenseAllocationInfoService expenseAllocationInfoService;
    @Autowired
    private ISourceRelationInfoService sourceRelationInfoService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private INoticeTaskService noticeTaskService;
    @Autowired
    private ICommonStaffService staffService;
    /**
     * 退库货源列表
     * @param warehouseInOutInfo
     */
    @Override
    public Page<SourceRelationInfo> getReturnSourceList(WarehouseInOutInfo warehouseInOutInfo) {
        Page<SourceRelationInfo> sourceRelationInfoPage = new Page<>();
        List<SourceRelationInfo> sourceRelationInfoList=new ArrayList<>();
        Wrapper<WarehouseInOutInfo> warehouseInOutInfoWrapper = new EntityWrapper<>();
        warehouseInOutInfoWrapper.eq("status_flag", "3").eq("delete_flag", "0").ne("return_tick_flag", "2");
        if (!StringUtils.isEmpty(warehouseInOutInfo.getContractNo())) {
            warehouseInOutInfoWrapper.eq("contract_no", warehouseInOutInfo.getContractNo());
        }
        if (!StringUtils.isEmpty(warehouseInOutInfo.getMoveTaskNo())) {
            warehouseInOutInfoWrapper.eq("in_out_task_no", warehouseInOutInfo.getMoveTaskNo());
            warehouseInOutInfoWrapper.eq("in_out_type", "移库出库");
        }
        Page<WarehouseInOutInfo> warehouseInOutInfoPage = warehouseInOutInfoService.selectPage(warehouseInOutInfo.getQueryPage(), warehouseInOutInfoWrapper);
        List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoPage.getRecords();
        if (!CollectionUtils.isEmpty(warehouseInOutInfoList)){
            for (WarehouseInOutInfo warehouseInOutInfo1:warehouseInOutInfoList){
                SourceRelationInfo sourceRelationInfo=new SourceRelationInfo();
                sourceRelationInfo.setCarNo(warehouseInOutInfo1.getCarNo());
                sourceRelationInfo.setEstimateOutWarehouseWeight(Float.valueOf(String.valueOf(warehouseInOutInfo1.getNetWeight())));
                sourceRelationInfo.setIssuingTime(warehouseInOutInfo1.getInOutDate());
                sourceRelationInfo.setIssuingTimeElse(warehouseInOutInfo1.getInOutDate());
                sourceRelationInfo.setWarehouseName(warehouseInOutInfo1.getWarehouseName());
                sourceRelationInfo.setReturnTickFlag(warehouseInOutInfo1.getReturnTickFlag());
                String goodsSource="";
                InOutWarehouseTask inOutWarehouseTask=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                .eq("in_out_task_no",warehouseInOutInfo1.getInOutTaskNo()));
                if (inOutWarehouseTask!=null) {
                    List<SourceRelationInfo> sourceRelationInfoList1 = sourceRelationInfoService.selectList(new EntityWrapper<SourceRelationInfo>()
                            .eq("task_id", inOutWarehouseTask.getId())
                            .eq("delete_flag", "0"));
                    if (!CollectionUtils.isEmpty(sourceRelationInfoList1)){
                        for (SourceRelationInfo sourceRelationInfo1:sourceRelationInfoList1){
                            sourceRelationInfo1.setSurplusWeight(Float.valueOf(String.valueOf(sourceRelationInfo1.getProportion()*warehouseInOutInfo1.getNetWeight())));
                        }
                        sourceRelationInfo.setSourceRelationInfoList(sourceRelationInfoList1);
                    }
                }
                sourceRelationInfo.setReturnTickFlag(warehouseInOutInfo1.getReturnTickFlag());
                sourceRelationInfo.setGoodsSource(goodsSource);
                sourceRelationInfo.setWarehouseInOutId(warehouseInOutInfo1.getId());
                sourceRelationInfoList.add(sourceRelationInfo);
            }
        }
        sourceRelationInfoPage.setRecords(sourceRelationInfoList);
        sourceRelationInfoPage.setTotal(warehouseInOutInfoPage.getTotal());
        return sourceRelationInfoPage;
    }


    @Override
    public Page<WarehousingOrder> selectInfo(WarehousingOrder warehousingOrder) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (warehousingOrder.getCurrentPage() - 1)
                * warehousingOrder.getPageSize());
        List<String> businessKeys = null;
        if ("2".equals(warehousingOrder.getSearchType())) {
            businessKeys = workflowService.getTaskBusinessKeysByCode("WAREHOUSING-ORDER-APPROVE");
        }
        pageView.put("searchKeyWord", warehousingOrder.getSearchKeyWord());
        pageView.put("searchType", warehousingOrder.getSearchType());
        pageView.put("pageSize", warehousingOrder.getPageSize());
        pageView.put("currentPage", warehousingOrder.getCurrentPage());
        pageView.put("startDate", warehousingOrder.getStartDate());
        pageView.put("endDate", warehousingOrder.getEndDate());
        pageView.put("baseId", warehousingOrder.getBaseId());
        pageView.put("businessKeys", businessKeys);
        pageView.put("flag", warehousingOrder.getFlag());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // 查询总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<WarehousingOrder> dataList = baseMapper.getListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            dataList.forEach(warehousingOrder1 -> {
                Wrapper<WarehousingOrder> warehousingOrderWrapper = new EntityWrapper<>();
                warehousingOrderWrapper.eq("comp_id", warehousingOrder1.getCompId())
                        .eq("warehouse_name", warehousingOrder1.getWarehouseName())
                        .like("issuing_time", dateFormat.format(warehousingOrder1.getIssuingTime()));
                if (!StringUtils.isEmpty(warehousingOrder.getSearchKeyWord())) {
                    warehousingOrderWrapper.like("goods_source", "%" + warehousingOrder.getSearchKeyWord() + "%");
                }
                if (!StringUtils.isEmpty(warehousingOrder.getSearchType())) {
                    warehousingOrderWrapper.gt("amount_not_payable", 0);
                }
                if ("2".equals(warehousingOrder.getSearchType())) {
                    warehousingOrderWrapper.eq("batch_id", warehousingOrder1.getBatchId());
                }
                if (!StringUtils.isEmpty(warehousingOrder.getFlag())) {
                    if ("0".equals(warehousingOrder.getFlag())){
                        warehousingOrderWrapper.gt("profit_and_loss", 0);
                    }
                    else {
                        warehousingOrderWrapper.lt("profit_and_loss", 0);
                    }
                }
                List<WarehousingOrder> warehousingOrderList=this.selectList(warehousingOrderWrapper);
                for(WarehousingOrder warehousingOrder2:warehousingOrderList){
                    List<ExpenseAllocationInfo> expenseAllocationInfos=expenseAllocationInfoService.selectList(new EntityWrapper<ExpenseAllocationInfo>()
                            .eq("order_id",warehousingOrder2.getId()));
                    if(!CollectionUtils.isEmpty(expenseAllocationInfos)){
                        warehousingOrder2.setExpenseAllocationInfoList(expenseAllocationInfos);
                    }
                    String taskId = "";
                    // 只有待审核状态才有taskId
                    if (StringUtils.isNotBlank(warehousingOrder2.getWorkflowId())) {
                        JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(warehousingOrder2.getWorkflowId()), warehousingOrder2.getBatchId());
                        taskId = jsonObject.getString("taskId");
                        warehousingOrder2.setTaskId(taskId);
                    }
                }
                warehousingOrder1.setWarehousingOrderList(warehousingOrderList);
            });

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

    /**
     * 添加
     * @return
     */
    /**
     * 每天16.30点更新
     */
    @Transactional
    @Scheduled(cron = "0 30 16 * * ?")
    public String addInfo() {
        //当天零点
        SimpleDateFormat now = new SimpleDateFormat("yyyy-MM-dd 16:30:00");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, -1);
        String beforeDay=now.format(c.getTime());
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("beforeDay", beforeDay);
        //成本
//        List<WarehousingOrder> costList = baseMapper.getGoodCostListByCondition(pageView);
        //收购
        List<WarehousingOrder> dataList = baseMapper.getAcquisitionListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)){
            for (WarehousingOrder warehousingOrder1:dataList) {
//                if(warehousingOrder1.getGoodsName().contains("玉米")&&!warehousingOrder1.getGoodsName().contains("潮粮")){
//                    costList.forEach(warehousingOrder -> {
//                        if ("玉米".equals(warehousingOrder.getGoodsName())){
//                            warehousingOrder1.setAvgCost(warehousingOrder.getAvgCost());
//                        }
//                    });
//                }
//                else {
//                    costList.forEach(warehousingOrder -> {
//                        if (warehousingOrder1.getGoodsName().equals(warehousingOrder.getGoodsName())){
//                            warehousingOrder1.setAvgCost(warehousingOrder.getAvgCost());
//                        }
//                    });
//                }
                List<PaymentManagement> paymentManagementList = paymentManagementService.selectList(new EntityWrapper<PaymentManagement>()
                        .eq("customer_name",warehousingOrder1.getGoodsSource())
                        .eq("contract_no",warehousingOrder1.getContractNo())
                        .eq("goods_name",warehousingOrder1.getGoodsName())
                        .ne("status", "待结算")
                        .ge("settlement_date", beforeDay));
                WarehousingOrder warehousingOrder = new WarehousingOrder();
                warehousingOrder.setId(IdGenerator.generateUUID());
                warehousingOrder.setBaseId(warehousingOrder1.getBaseId());
                warehousingOrder.setContractNo(warehousingOrder1.getContractNo());
                warehousingOrder.setIdentifyId(warehousingOrder1.getIdentifyId());
                warehousingOrder.setWarehouseName(warehousingOrder1.getWarehouseName());
                warehousingOrder.setGoodsSource(warehousingOrder1.getGoodsSource());
                warehousingOrder.setCustomer(warehousingOrder1.getGoodsSource());
                warehousingOrder.setCompId(warehousingOrder1.getCompId());
                warehousingOrder.setGoodsName(warehousingOrder1.getGoodsName());
                warehousingOrder.setInType("收购入库");
                double weight = (paymentManagementList.stream().mapToDouble(PaymentManagement::getNetWeight).sum())/1000;
                warehousingOrder.setInWarehouseWeight(Float.valueOf(String.valueOf(weight)));
                warehousingOrder.setSurplusWeight(Float.valueOf(String.valueOf(weight)));
                double money = paymentManagementList.stream().mapToDouble(PaymentManagement::getAmountIngPayable).sum();
                //收购成本=总应付/总重量
                warehousingOrder.setAvgCost(money/weight);
                warehousingOrder.setAmountNotPayable(money);
                warehousingOrder.setAmountEdPayable(0d);
                warehousingOrder.setIssuingTime(new Date());
                warehousingOrder.setGrainFund(money);
                this.insert(warehousingOrder);
                //更新库点库存 (所在仓库所属仓库货名一致)
                ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                    .eq("comp_id",warehousingOrder1.getCompId()).eq("inventory_type","3").eq("locus_warehouse",warehousingOrder1.getWarehouseName())
                    .eq("warehouse",warehousingOrder1.getWarehouseName())
                    .eq("goods_name",warehousingOrder1.getGoodsName()));
                if (contractInventoryDistribution!=null){
                    contractInventoryDistribution.setInventory(contractInventoryDistribution.getInventory()+weight);
                    contractInventoryDistributionService.updateById(contractInventoryDistribution);
                }
                else {
                    ContractInventoryDistribution contractInventoryDistribution1=new ContractInventoryDistribution();
                    contractInventoryDistribution1.setId(IdGenerator.generateUUID());
                    contractInventoryDistribution1.setCompId(warehousingOrder1.getCompId());
                    contractInventoryDistribution1.setWarehouseId(warehousingOrder1.getBaseId());
                    contractInventoryDistribution1.setInventory(weight);
                    contractInventoryDistribution1.setWarehouse(warehousingOrder1.getWarehouseName());
                    contractInventoryDistribution1.setLocusWarehouse(warehousingOrder1.getWarehouseName());
                    contractInventoryDistribution1.setGoodsName(warehousingOrder1.getGoodsName());
                    contractInventoryDistribution1.setInventoryType("3");
                    contractInventoryDistributionService.insert(contractInventoryDistribution1);

                }

            }
        }
        //采购入库
        List<WarehousingOrder> dataList1 = baseMapper.getPurchaseListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList1)){
            ContractManagementInfo contractManagementInfo=contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
            .eq("contract_no",dataList1.get(0).getContractNo())
            .eq("comp_id",dataList1.get(0).getCompId()));
            for (WarehousingOrder warehousingOrder1:dataList1) {
//                if(warehousingOrder1.getGoodsName().contains("玉米")&&!warehousingOrder1.getGoodsName().contains("潮粮")){
//                    costList.forEach(warehousingOrder -> {
//                        if ("玉米".equals(warehousingOrder.getGoodsName())){
//                            warehousingOrder1.setAvgCost(warehousingOrder.getAvgCost());
//                        }
//                    });
//                }
//                else {
//                    costList.forEach(warehousingOrder -> {
//                        if (warehousingOrder1.getGoodsName().equals(warehousingOrder.getGoodsName())){
//                            warehousingOrder1.setAvgCost(warehousingOrder.getAvgCost());
//                        }
//                    });
//                }
                List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                        .eq("status", "已提交")
                        .eq("contract_no",warehousingOrder1.getContractNo())
                        .eq("warehouse_name",warehousingOrder1.getWarehouseName())
                        .eq("in_out_type", "采购入库")
                        .ge("in_out_date", beforeDay));
                WarehousingOrder warehousingOrder = new WarehousingOrder();
                warehousingOrder.setId(IdGenerator.generateUUID());
                warehousingOrder.setBaseId(warehousingOrder1.getBaseId());
                warehousingOrder.setWarehouseName(warehousingOrder1.getWarehouseName());
                warehousingOrder.setGoodsSource(warehousingOrder1.getContractNo());
                warehousingOrder.setInType("采购入库");
                warehousingOrder.setCustomer(contractManagementInfo.getSeller());
                warehousingOrder.setCompId(warehousingOrder1.getCompId());
                warehousingOrder.setGoodsName(warehousingOrder1.getGoodsName());
                warehousingOrder.setContractNo(warehousingOrder1.getContractNo());
                double weight = warehouseInOutInfoList.stream().mapToDouble(WarehouseInOutInfo::getNetWeight).sum();
                warehousingOrder.setInWarehouseWeight(Float.valueOf(String.valueOf(weight)));
                Double money=0d;
                for (WarehouseInOutInfo warehouseInOutInfo:warehouseInOutInfoList){
                    money=money+warehouseInOutInfo.getCost()*warehouseInOutInfo.getNetWeight();
                }
                warehousingOrder.setAmountNotPayable(money);
                warehousingOrder.setAmountEdPayable(0d);
                warehousingOrder.setAvgCost(money/weight);
                warehousingOrder.setSurplusWeight(Float.valueOf(String.valueOf(weight)));
                warehousingOrder.setIssuingTime(new Date());
                warehousingOrder.setGrainFund(money);
                this.insert(warehousingOrder);
                //更新采购库存
                ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                        .eq("comp_id",warehousingOrder1.getCompId()).eq("inventory_type","1").eq("contract_no",warehousingOrder1.getContractNo())
                        .eq("warehouse",warehousingOrder1.getWarehouseName()));
                if (contractInventoryDistribution!=null){
                    contractInventoryDistribution.setInStorage(contractInventoryDistribution.getInStorage()+warehousingOrder1.getInWarehouseWeight());
                    contractInventoryDistributionService.updateById(contractInventoryDistribution);
                }
                else {
                    ContractInventoryDistribution contractInventoryDistribution1=new ContractInventoryDistribution();
                    contractInventoryDistribution1.setId(IdGenerator.generateUUID());
                    contractInventoryDistribution1.setCompId(warehousingOrder1.getCompId());
                    contractInventoryDistribution1.setInStorage(Double.valueOf(String.valueOf(warehousingOrder.getInWarehouseWeight())));
                    contractInventoryDistribution1.setWarehouse(warehousingOrder1.getWarehouseName());
                    contractInventoryDistribution1.setContractNo(warehousingOrder1.getContractNo());
                    contractInventoryDistribution1.setGoodsName(warehousingOrder1.getGoodsName());
                    contractInventoryDistribution1.setInventoryType("1");
                    contractInventoryDistributionService.insert(contractInventoryDistribution1);

                }
            }
        }
        //移库入库
        List<WarehousingOrder> dataList2 = baseMapper.getMoveListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList2)){
            for (WarehousingOrder warehousingOrder1:dataList2) {
                List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                        .eq("status", "已提交")
                        .eq("in_out_task_no",warehousingOrder1.getInOutTaskNo())
                        .eq("in_out_type", "移库入库")
                        .ge("in_out_date", beforeDay));
                double weight = warehouseInOutInfoList.stream().mapToDouble(WarehouseInOutInfo::getNetWeight).sum();
                //查移库出库任务货源
                List<SourceRelationInfo> sourceRelationInfoList =sourceRelationInfoService.selectList(new EntityWrapper<SourceRelationInfo>()
                        .eq("task_id", warehousingOrder1.getSendTaskId())
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(sourceRelationInfoList)){
                    for (SourceRelationInfo sourceRelationInfo:sourceRelationInfoList){
                        //查货源关联的入库单
                        WarehousingOrder warehousingOrder2=this.selectById(sourceRelationInfo.getSourceId());
                        WarehousingOrder warehousingOrder = new WarehousingOrder();
                        warehousingOrder.setId(IdGenerator.generateUUID());
                        warehousingOrder.setBaseId(warehousingOrder1.getBaseId());
                        warehousingOrder.setWarehouseName(warehousingOrder1.getWarehouseName());
                        warehousingOrder.setInType("移库入库");
                        warehousingOrder.setDeliveryWarehouse(warehousingOrder1.getSendWarehouseName());
                        warehousingOrder.setMoveTaskNo(warehousingOrder1.getMoveTaskNo());
                        warehousingOrder.setContractNo(warehousingOrder2.getContractNo());
                        //取货源入库单成本
                        warehousingOrder.setAvgCost(warehousingOrder2.getAvgCost());
                        warehousingOrder.setCompId(warehousingOrder1.getCompId());
                        warehousingOrder.setGoodsName(warehousingOrder1.getGoodsName());
                        warehousingOrder.setInWarehouseWeight(Float.valueOf(String.valueOf(weight*sourceRelationInfo.getProportion())));
                        warehousingOrder.setSurplusWeight(Float.valueOf(String.valueOf(weight*sourceRelationInfo.getProportion())));
                        warehousingOrder.setIssuingTime(new Date());
                        if ("采购入库".equals(warehousingOrder2.getInType())){
                            warehousingOrder.setGoodsSource(warehousingOrder2.getContractNo());
                            //更新入货库采购合同库存入库量
                            ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                                    .eq("comp_id",warehousingOrder1.getCompId()).eq("inventory_type","1").eq("contract_no",warehousingOrder2.getContractNo())
                                    .eq("warehouse",warehousingOrder1.getWarehouseName()));
                            if (contractInventoryDistribution!=null){
                                contractInventoryDistribution.setInStorage(contractInventoryDistribution.getInStorage()+weight*sourceRelationInfo.getProportion());
                                contractInventoryDistributionService.updateById(contractInventoryDistribution);
                            }
                            else {
                                ContractInventoryDistribution contractInventoryDistribution1=new ContractInventoryDistribution();
                                contractInventoryDistribution1.setId(IdGenerator.generateUUID());
                                contractInventoryDistribution1.setCompId(warehousingOrder1.getCompId());
                                contractInventoryDistribution1.setInStorage(weight*sourceRelationInfo.getProportion());
                                contractInventoryDistribution1.setWarehouse(warehousingOrder1.getWarehouseName());
                                contractInventoryDistribution1.setContractNo(warehousingOrder2.getContractNo());
                                contractInventoryDistribution1.setGoodsName(warehousingOrder1.getGoodsName());
                                contractInventoryDistribution1.setInventoryType("1");
                                contractInventoryDistributionService.insert(contractInventoryDistribution1);

                            }
                            //更新出货库采购合同库存移出量
                            ContractInventoryDistribution contractInventoryDistribution1=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                                    .eq("comp_id",warehousingOrder1.getCompId()).eq("inventory_type","1").eq("contract_no",warehousingOrder2.getContractNo())
                                    .eq("warehouse",warehousingOrder1.getSendWarehouseName()));
                            if (contractInventoryDistribution1!=null){
                                contractInventoryDistribution1.setRemoveStorage(contractInventoryDistribution1.getRemoveStorage()+weight*sourceRelationInfo.getProportion());
                                contractInventoryDistributionService.updateById(contractInventoryDistribution1);
                            }
                        }
                        else if ("收购入库".equals(warehousingOrder2.getInType())){
                            //查收购合同原始货源仓库
                            InOutWarehouseTask inOutWarehouseTask=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                    .eq("comp_id", warehousingOrder2.getCompId())
                                    .eq("contract_no", warehousingOrder2.getContractNo())
                                    .eq("delete_flag", "0"));
                            warehousingOrder.setGoodsSource(inOutWarehouseTask.getWarehouseName());
                            //更新收货库库点库存 (所在仓库为入货库、所属仓库为原始货源仓库、货名一致)
                            ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                                    .eq("comp_id",warehousingOrder1.getCompId()).eq("inventory_type","3").eq("locus_warehouse",warehousingOrder1.getWarehouseName())
                                    .eq("warehouse",inOutWarehouseTask.getWarehouseName())
                                    .eq("goods_name",warehousingOrder1.getGoodsName()));
                            if (contractInventoryDistribution!=null){
                                contractInventoryDistribution.setInventory(contractInventoryDistribution.getInventory()+weight*sourceRelationInfo.getProportion());
                                contractInventoryDistributionService.updateById(contractInventoryDistribution);
                            }
                            else {
                                ContractInventoryDistribution contractInventoryDistribution1=new ContractInventoryDistribution();
                                contractInventoryDistribution1.setId(IdGenerator.generateUUID());
                                contractInventoryDistribution1.setCompId(warehousingOrder1.getCompId());
                                contractInventoryDistribution1.setWarehouseId(warehousingOrder1.getBaseId());
                                contractInventoryDistribution1.setInventory(weight*sourceRelationInfo.getProportion());
                                contractInventoryDistribution1.setWarehouse(warehousingOrder1.getWarehouseName());
                                contractInventoryDistribution1.setLocusWarehouse(warehousingOrder1.getWarehouseName());
                                contractInventoryDistribution1.setGoodsName(warehousingOrder1.getGoodsName());
                                contractInventoryDistribution1.setInventoryType("3");
                                contractInventoryDistributionService.insert(contractInventoryDistribution1);

                            }
                            //更新发货库库点库存 (所在仓库为发货库、所属仓库为原始货源仓库、货名一致)
                            ContractInventoryDistribution contractInventoryDistribution1=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                                    .eq("comp_id",warehousingOrder1.getCompId()).eq("inventory_type","3").eq("locus_warehouse",warehousingOrder1.getSendWarehouseName())
                                    .eq("warehouse",warehousingOrder1.getSendWarehouseName())
                                    .eq("goods_name",warehousingOrder1.getGoodsName()));
                            if (contractInventoryDistribution1!=null){
                                contractInventoryDistribution1.setInventory(contractInventoryDistribution1.getInventory()-weight*sourceRelationInfo.getProportion());
                                contractInventoryDistributionService.updateById(contractInventoryDistribution1);
                            }
                        }
                        this.insert(warehousingOrder);
                    }
                }
            }
        }
        //退库
        List<WarehousingOrder> dataList3 = baseMapper.getMoveListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList3)){
            for (WarehousingOrder warehousingOrder1:dataList3) {
                List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                        .eq("status", "已提交")
                        .eq("in_out_task_no",warehousingOrder1.getInOutTaskNo())
                        .eq("in_out_type", "退库")
                        .ge("in_out_date", beforeDay));
                double weight = warehouseInOutInfoList.stream().mapToDouble(WarehouseInOutInfo::getNetWeight).sum();
                //查退库任务货源
                List<SourceRelationInfo> sourceRelationInfoList =sourceRelationInfoService.selectList(new EntityWrapper<SourceRelationInfo>()
                        .eq("task_id", warehousingOrder1.getSendTaskId())
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(sourceRelationInfoList)){
                    for (SourceRelationInfo sourceRelationInfo:sourceRelationInfoList){
                        WarehousingOrder warehousingOrder2=this.selectById(sourceRelationInfo.getSourceId());
                        WarehousingOrder warehousingOrder = new WarehousingOrder();
                        warehousingOrder.setId(IdGenerator.generateUUID());
                        warehousingOrder.setBaseId(warehousingOrder1.getBaseId());
                        warehousingOrder.setWarehouseName(warehousingOrder1.getWarehouseName());
                        warehousingOrder.setInType("退库");
                        warehousingOrder.setContractNo(warehousingOrder2.getContractNo());
                        //取货源入库单成本
                        warehousingOrder.setAvgCost(warehousingOrder2.getAvgCost());
                        warehousingOrder.setCompId(warehousingOrder1.getCompId());
                        warehousingOrder.setGoodsName(warehousingOrder1.getGoodsName());
                        warehousingOrder.setInWarehouseWeight(Float.valueOf(String.valueOf(weight*sourceRelationInfo.getProportion())));
                        warehousingOrder.setSurplusWeight(Float.valueOf(String.valueOf(weight*sourceRelationInfo.getProportion())));
                        warehousingOrder.setIssuingTime(new Date());
                        if ("采购入库".equals(warehousingOrder2.getInType())){
                            warehousingOrder.setGoodsSource(warehousingOrder2.getContractNo());
                        }
                        else if ("收购入库".equals(warehousingOrder2.getInType())){
                            //查收购合同原始收货库
                            InOutWarehouseTask inOutWarehouseTask=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                                    .eq("comp_id", warehousingOrder1.getCompId())
                                    .eq("contract_no", warehousingOrder1.getContractNo())
                                    .eq("delete_flag", "0"));
                            warehousingOrder.setGoodsSource(inOutWarehouseTask.getWarehouseName());
                            //更新库点库存 (所在仓库为退货库、所属仓库为原始库、货名一致)
                            ContractInventoryDistribution contractInventoryDistribution=contractInventoryDistributionService.selectOne(new EntityWrapper<ContractInventoryDistribution>()
                                    .eq("comp_id",warehousingOrder1.getCompId()).eq("inventory_type","3").eq("locus_warehouse",warehousingOrder1.getWarehouseName())
                                    .eq("warehouse",inOutWarehouseTask.getWarehouseName())
                                    .eq("goods_name",warehousingOrder1.getGoodsName()));
                            if (contractInventoryDistribution!=null){
                                contractInventoryDistribution.setInventory(contractInventoryDistribution.getInventory()+weight*sourceRelationInfo.getProportion());
                                contractInventoryDistributionService.updateById(contractInventoryDistribution);
                            }
                            else {
                                ContractInventoryDistribution contractInventoryDistribution1=new ContractInventoryDistribution();
                                contractInventoryDistribution1.setId(IdGenerator.generateUUID());
                                contractInventoryDistribution1.setCompId(warehousingOrder1.getCompId());
                                contractInventoryDistribution1.setWarehouseId(warehousingOrder1.getBaseId());
                                contractInventoryDistribution1.setInventory(weight*sourceRelationInfo.getProportion());
                                contractInventoryDistribution1.setWarehouse(warehousingOrder1.getWarehouseName());
                                contractInventoryDistribution1.setLocusWarehouse(warehousingOrder1.getWarehouseName());
                                contractInventoryDistribution1.setGoodsName(warehousingOrder1.getGoodsName());
                                contractInventoryDistribution1.setInventoryType("3");
                                contractInventoryDistributionService.insert(contractInventoryDistribution1);

                            }
                        }
                        this.insert(warehousingOrder);
                    }
                }
            }
        }
        return "OK";

    }

    /**
     * 编辑
     * @param warehousingOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editInfo(WarehousingOrder warehousingOrder) {
        // 插入操作历史
        String staffName = this.billOperateHisService.getStaffAndName();
        if ("0".equals(warehousingOrder.getFlag())) {
            warehousingOrder.setInventoryStatus(StatusEnum.GRAIN_REVIEWED.getName());
            warehousingOrder.setOperationFlag("盘盈");
            // 插入操作历史
            this.billOperateHisService.saveBillOperateHis(warehousingOrder.getId(), NumberConstant.INVENTORY_CHECK, staffName, null,
                    "盘盈" + "(审核中)", null, String.valueOf(warehousingOrder.getPlValue()));
//            boolean isStartWorkflow = StringUtils.isBlank(warehousingOrder.getWorkflowId());
//                // 不是退回的单子
//                if (isStartWorkflow) {
//                    Workflow workflow = workflowService
//                            .findLatestWorkflowByBusinessCodeByApp(warehousingOrder.getCompId(), "WAREHOUSING-DEBIT-APPROVE");
//                    // 没配置审核流程，直接结束并处理信息
//                    if (workflow == null) {
//                        throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
//                    }
//                    // 开启审核流
//                    else {
//
//                        // 设置状态 已提交审核
//                        warehousingOrder.setWorkflowId(workflow.getId());
//                        this.updateById(warehousingOrder);
//                        workflowService.startInstance(workflow.getId(), warehousingOrder.getId());
//                    }
//                }
//                // 退回的单子 再启用
//                else {
//
//                    this.updateById(warehousingOrder);
//                    workflowService.activateInstance(warehousingOrder.getWorkflowId(), warehousingOrder.getId());
//                }
        }
        else if ("1".equals(warehousingOrder.getFlag())){
            warehousingOrder.setInventoryStatus(StatusEnum.GRAIN_REVIEWED.getName());
            warehousingOrder.setOperationFlag("盘亏");
            this.billOperateHisService.saveBillOperateHis(warehousingOrder.getId(), NumberConstant.INVENTORY_CHECK, staffName, null,
                    "盘亏" + "(审核中)", null, String.valueOf(warehousingOrder.getPlValue()));
//            boolean isStartWorkflow = StringUtils.isBlank(warehousingOrder.getWorkflowId());
//                // 不是退回的单子
//                if (isStartWorkflow) {
//                    Workflow workflow = workflowService
//                            .findLatestWorkflowByBusinessCodeByApp(warehousingOrder.getCompId(), "WAREHOUSING-DEBIT-APPROVE");
//                    // 没配置审核流程，直接结束并处理信息
//                    if (workflow == null) {
//                        throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
//                    }
//                    // 开启审核流
//                    else {
//
//                        // 设置状态 已提交审核
//                        warehousingOrder.setWorkflowId(workflow.getId());
//                        this.updateById(warehousingOrder);
//                        workflowService.startInstance(workflow.getId(), warehousingOrder.getId());
//                    }
//                }
//                // 退回的单子 再启用
//                else {
//
//                    this.updateById(warehousingOrder);
//                    workflowService.activateInstance(warehousingOrder.getWorkflowId(), warehousingOrder.getId());
//                }
        }
        //盘盈通过
        else if ("2".equals(warehousingOrder.getFlag())){
            warehousingOrder.setProfitAndLoss(warehousingOrder.getProfitAndLoss()+warehousingOrder.getPlValue());
            warehousingOrder.setOperationFlag("");
            warehousingOrder.setInventoryStatus(StatusEnum.GRAIN_ADOPT.getName());
            this.billOperateHisService.saveBillOperateHis(warehousingOrder.getId(), NumberConstant.INVENTORY_CHECK, staffName, null,
                    "盘盈" + "(已通过)", null, String.valueOf(warehousingOrder.getPlValue()));
            warehousingOrder.setPlValue(0f);
        }
        //盘亏通过
        else if ("3".equals(warehousingOrder.getFlag())){
            warehousingOrder.setInventoryStatus(StatusEnum.GRAIN_ADOPT.getName());
            warehousingOrder.setProfitAndLoss(warehousingOrder.getProfitAndLoss()+warehousingOrder.getPlValue());
            warehousingOrder.setOperationFlag("");
            this.billOperateHisService.saveBillOperateHis(warehousingOrder.getId(), NumberConstant.INVENTORY_CHECK, staffName, null,
                    "盘亏" + "(已通过)", null, String.valueOf(warehousingOrder.getPlValue()));
            warehousingOrder.setPlValue(0f);
        }
        //盘盈驳回
        else if ("4".equals(warehousingOrder.getFlag())){
            warehousingOrder.setInventoryStatus(StatusEnum.GRAIN_REJECT.getName());
            warehousingOrder.setOperationFlag("");
            this.billOperateHisService.saveBillOperateHis(warehousingOrder.getId(), NumberConstant.INVENTORY_CHECK, staffName, null,
                    "盘盈" + "(已驳回)", null,  String.valueOf(warehousingOrder.getPlValue()));
            warehousingOrder.setPlValue(0f);
        }
        //盘亏驳回
        else if ("5".equals(warehousingOrder.getFlag())){
            warehousingOrder.setInventoryStatus(StatusEnum.GRAIN_REJECT.getName());
            warehousingOrder.setOperationFlag("");
            this.billOperateHisService.saveBillOperateHis(warehousingOrder.getId(), NumberConstant.INVENTORY_CHECK, staffName, null,
                    "盘亏" + "(已驳回)", null,  String.valueOf(warehousingOrder.getPlValue()));
            warehousingOrder.setPlValue(0f);
        }
        // 主表信息编辑
        boolean one = this.updateById(warehousingOrder);
        // 假如成功返回ok
        if (one) {
            return "OK";
        } else {
            return "NG";
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String payMoney(WarehousingOrder warehousingOrder) {
        List<WarehousingOrder> warehousingOrderList = warehousingOrder.getWarehousingOrderList();
        if (!CollectionUtils.isEmpty(warehousingOrderList)) {
            //付款多条
            if ("0".equals(warehousingOrder.getFlag())) {
                for (WarehousingOrder warehousingOrder1 : warehousingOrderList) {
                    warehousingOrder1.setAmountNotPayable(warehousingOrder1.getAmountNotPayable()-warehousingOrder1.getRequestFunds());
                    warehousingOrder1.setAmountEdPayable(warehousingOrder1.getAmountEdPayable()+warehousingOrder1.getRequestFunds());
                    warehousingOrder1.setRequestFunds(0d);
                    warehousingOrder1.setStatusFlag("");
                    warehousingOrder1.setStatus("");
                    this.updateById(warehousingOrder1);
                }
            }
            //预付款分配
            else if ("2".equals(warehousingOrder.getFlag())) {
                WarehousingOrder warehousingOrder1=warehousingOrder.getWarehousingOrderList().get(0);
                warehousingOrder1.setAmountNotPayable(warehousingOrder1.getAmountNotPayable()-warehousingOrder.getMoney());
                warehousingOrder1.setAmountEdPayable(warehousingOrder1.getAmountEdPayable()+warehousingOrder.getMoney());
                this.updateById(warehousingOrder1);
                ExpenseAllocationInfo expenseAllocationInfo=expenseAllocationInfoService.selectOne(new EntityWrapper<ExpenseAllocationInfo>()
                        .eq("contract_no",warehousingOrder1.getContractNo())
                        .eq("cost_type","1"));
                expenseAllocationInfo.setDistributionMoney(expenseAllocationInfo.getDistributionMoney()+warehousingOrder.getMoney());
                expenseAllocationInfoService.updateById(expenseAllocationInfo);
                // 先删除任务
                noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "WAREHOUSING-ORDER-APPROVE",
                        warehousingOrder1.getId(), null);
                CommonStaff commitUserInfo = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
                String taskContent = "合同" + warehousingOrder1.getContractNo() + "由" +
                        commitUserInfo.getStaffName() + "发起的预付款分配，分配金额为"+warehousingOrder.getMoney();
                NoticeTaskInfo taskInfo = new NoticeTaskInfo();
                taskInfo.setCompId(commitUserInfo.getCompId());
                taskInfo.setAcceptType(BaseNotice.AcceptStatus.STAFF);
                taskInfo.setBusinessId(warehousingOrder1.getId());
                taskInfo.setBusinessType("WAREHOUSE");
                taskInfo.setMessageContent(taskContent);
                taskInfo.setBusinessCode("WAREHOUSING-ORDER-APPROVE");
                //查询单证中心成员
                List<CommonStaff> commonStaffList = staffService.selectList(new EntityWrapper<CommonStaff>()
                        .eq("dept_id", "17197ee578454b2c9f9d18b69cc1bc73")
                        .eq("delete_flag","0"));
                List<String> staffIds = commonStaffList.stream().map(CommonStaff::getStaffId).collect(Collectors.toList());
                noticeTaskService.createNoticeTask(staffIds,
                        null, taskInfo);
            }
            //保证金分配
            else if ("3".equals(warehousingOrder.getFlag())) {
                WarehousingOrder warehousingOrder1=warehousingOrder.getWarehousingOrderList().get(0);
                warehousingOrder1.setAmountNotPayable(warehousingOrder1.getAmountNotPayable()-warehousingOrder.getMoney());
                warehousingOrder1.setAmountEdPayable(warehousingOrder1.getAmountEdPayable()+warehousingOrder.getMoney());
                this.updateById(warehousingOrder1);
                ExpenseAllocationInfo expenseAllocationInfo=expenseAllocationInfoService.selectOne(new EntityWrapper<ExpenseAllocationInfo>()
                        .eq("contract_no",warehousingOrder1.getContractNo())
                        .eq("cost_type","5"));
                expenseAllocationInfo.setDistributionMoney(expenseAllocationInfo.getDistributionMoney()+warehousingOrder.getMoney());
                expenseAllocationInfoService.updateById(expenseAllocationInfo);
                // 先删除任务
                noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "WAREHOUSING-ORDER-APPROVE",
                        warehousingOrder1.getId(), null);
                CommonStaff commitUserInfo = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
                String taskContent = "合同" + warehousingOrder1.getContractNo() + "由" +
                        commitUserInfo.getStaffName() + "发起的保证金分配，分配金额为"+warehousingOrder.getMoney();
                NoticeTaskInfo taskInfo = new NoticeTaskInfo();
                taskInfo.setCompId(commitUserInfo.getCompId());
                taskInfo.setAcceptType(BaseNotice.AcceptStatus.STAFF);
                taskInfo.setBusinessId(warehousingOrder1.getId());
                taskInfo.setBusinessType("WAREHOUSE");
                taskInfo.setMessageContent(taskContent);
                taskInfo.setBusinessCode("WAREHOUSING-ORDER-APPROVE");
                //查询单证中心成员
                List<CommonStaff> commonStaffList = staffService.selectList(new EntityWrapper<CommonStaff>()
                        .eq("dept_id", "17197ee578454b2c9f9d18b69cc1bc73")
                        .eq("delete_flag","0"));
                List<String> staffIds = commonStaffList.stream().map(CommonStaff::getStaffId).collect(Collectors.toList());
                noticeTaskService.createNoticeTask(staffIds,
                        null, taskInfo);
            }
            //请款1
            else {
                String batchId = IdGenerator.generateUUID();
                String workflowId = "";

                if(warehousingOrderList.size() > 0){
                    WarehousingOrder warehousingOrder1 = warehousingOrderList.get(0);
                    boolean isStartWorkflow = StringUtils.isBlank(warehousingOrder1.getWorkflowId());
                    // 不是退回的单子
                    if (isStartWorkflow) {
                        Workflow workflow = workflowService
                                .findLatestWorkflowByBusinessCodeByApp(warehousingOrder1.getCompId(), "WAREHOUSING-ORDER-APPROVE");
                        // 没配置审核流程，直接结束并处理信息
                        if (workflow == null) {
                            throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                        }
                        // 开启审核流
                        else {
                            workflowId = workflow.getId();
                            for (WarehousingOrder warehousingOrder2 : warehousingOrderList) {
                                warehousingOrder2.setStatusFlag(StatusEnum.PENDING_PAYMENT.getFlag());
                                warehousingOrder2.setStatus(StatusEnum.PENDING_PAYMENT.getName());
                                warehousingOrder2.setRequestPerson(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getStaffName());
                                warehousingOrder2.setRequestDate(new Date());
                                warehousingOrder2.setWorkflowId(workflowId);
                                warehousingOrder2.setBatchId(batchId);
                                this.updateById(warehousingOrder2);
                            }
                            // 设置状态 已提交审核
                            workflowService.startInstance(workflow.getId(), batchId);
                        }
                    }
                    // 退回的单子 再启用
                    else {
                        batchId = warehousingOrder1.getBatchId();
                        for (WarehousingOrder warehousingOrder2 : warehousingOrderList) {
                            warehousingOrder2.setStatusFlag(StatusEnum.PENDING_PAYMENT.getFlag());
                            warehousingOrder2.setStatus(StatusEnum.PENDING_PAYMENT.getName());
                            warehousingOrder2.setRequestPerson(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getStaffName());
                            warehousingOrder2.setRequestDate(new Date());
//                            warehousingOrder2.setWorkflowId(workflowId);
                            warehousingOrder2.setBatchId(batchId);
                            this.updateById(warehousingOrder2);
                        }
                        workflowService.activateInstance(warehousingOrder1.getWorkflowId(), warehousingOrder1.getBatchId());
                    }
                }
            }
        }
        return "OK";
    }

    @Override
    public String exportPhone(WarehousingOrder warehousingOrder, HttpServletResponse response) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


        // 1.Excel的头部信息
        String headerTitle = "";

        // 2.创建一个webbook 对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 3.在webbook中添加一个sheet，对应Excel文件中的sheet
        HSSFSheet sheet;

        sheet = wb.createSheet("入库单信息");
        headerTitle = "入库单信息";

        // 4.设置打印参数
        sheet.setMargin(HSSFSheet.TopMargin, (short) 1);// 页边距（上）
        sheet.setMargin(HSSFSheet.BottomMargin, (short) 1);// 页边距（下）
        sheet.setMargin(HSSFSheet.LeftMargin, (short) 1);// 页边距（左）
        sheet.setMargin(HSSFSheet.RightMargin, (short) 1);// 页边距（右）

        // 不显示网格
        sheet.setDisplayGridlines(false);
        // 设置水平居中
        sheet.setHorizontallyCenter(true);

        /**************** 数据行样式 start ****************/
        HSSFFont fontTitle = wb.createFont();
        fontTitle.setFontName("宋体");
        fontTitle.setFontHeightInPoints((short) 14);
        // 设置字体加粗
        fontTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        HSSFFont fontComp = wb.createFont();
        fontComp.setFontName("宋体");
        fontComp.setFontHeightInPoints((short) 16);
        // 设置字体加粗
        fontComp.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        HSSFFont fontDetail = wb.createFont();
        fontDetail.setFontName("宋体");
        fontDetail.setFontHeightInPoints((short) 12);

        HSSFFont fontDetail1 = wb.createFont();
        fontDetail1.setFontName("宋体");
        fontDetail1.setFontHeightInPoints((short) 12);
        fontDetail1.setColor(HSSFColor.RED.index);

        // title
        HSSFCellStyle styleTitle = wb.createCellStyle();
        // 指定单元格居中对齐
        styleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleTitle.setWrapText(true);
        // 设置单元格字体
        styleTitle.setFont(fontTitle);
        // 右边框
        styleTitle.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleTitle.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleTitle.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleTitle.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        // title
        HSSFCellStyle styleComp = wb.createCellStyle();
        // 指定单元格居中对齐
        styleComp.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleComp.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleComp.setWrapText(true);
        // 设置单元格字体
        styleComp.setFont(fontComp);
        // 右边框
        styleComp.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleComp.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleComp.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleComp.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        HSSFCellStyle styleInfo = wb.createCellStyle();
        // 指定单元格居中对齐
        styleInfo.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // 指定单元格垂直居中对齐
        styleInfo.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleInfo.setWrapText(true);
        // 设置单元格字体
        styleInfo.setFont(fontDetail);
        // 右边框
        styleInfo.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleInfo.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleInfo.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleInfo.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        HSSFCellStyle styleDetail = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetail.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleDetail.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetail.setWrapText(true);
        // 设置单元格字体
        styleDetail.setFont(fontDetail);
        // 右边框
        styleDetail.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetail.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetail.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetail.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle styleDetail1 = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetail1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleDetail1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetail1.setWrapText(true);
        // 设置单元格字体
        styleDetail1.setFont(fontDetail1);
        // 右边框
        styleDetail1.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetail1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetail1.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetail1.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle contextstyle = wb.createCellStyle();
        // 指定单元格居中对齐
        contextstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        contextstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        contextstyle.setWrapText(true);
        // 设置单元格字体
        contextstyle.setFont(fontDetail);
        // 右边框
        contextstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        contextstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        contextstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        contextstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle contextstyle1 = wb.createCellStyle();
        // 指定单元格居中对齐
        contextstyle1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        contextstyle1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        contextstyle1.setWrapText(true);
        // 设置单元格字体
        contextstyle1.setFont(fontDetail1);
        // 右边框
        contextstyle1.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        contextstyle1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        contextstyle1.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        contextstyle1.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle styleDetailYellow = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetailYellow.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleDetailYellow.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetailYellow.setWrapText(true);
        // 设置单元格字体
        styleDetailYellow.setFont(fontDetail);
        // 右边框
        styleDetailYellow.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetailYellow.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetailYellow.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetailYellow.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        styleDetailYellow.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        styleDetailYellow.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);


        HSSFCellStyle styleDetailLeft = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetailLeft.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // 指定单元格垂直居中对齐
        styleDetailLeft.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetailLeft.setWrapText(true);
        // 设置单元格字体
        styleDetailLeft.setFont(fontDetail);
        // 右边框
        styleDetailLeft.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetailLeft.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetailLeft.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetailLeft.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        /**************** 数据行样式 end ****************/

        // 设置列宽
        sheet.setColumnWidth(0, 1 * 256 + 184);
        sheet.setColumnWidth(1, "货源".getBytes().length*3*256);
        sheet.setColumnWidth(2, "发货库".getBytes().length*25/10*256);
        sheet.setColumnWidth(3, "货名".getBytes().length*3*256);
        sheet.setColumnWidth(4, 12 * 256 + 184);
        sheet.setColumnWidth(5, 12 * 256 + 184);
        sheet.setColumnWidth(6, 12 * 256 + 184);
        sheet.setColumnWidth(7, 12 * 256 + 184);
        sheet.setColumnWidth(8, 12 * 256 + 184);
        sheet.setColumnWidth(9, 12 * 256 + 184);
        sheet.setColumnWidth(10, 12 * 256 + 184);
        sheet.setColumnWidth(11, 12 * 256 + 184);
        sheet.setColumnWidth(12, 12 * 256 + 184);
        sheet.setColumnWidth(13, 12 * 256 + 184);
        sheet.setColumnWidth(14, 1 * 256 + 184);

        // 创建单元格对象
        HSSFCell cell = null;

        // 创建打印设置对象
        HSSFPrintSetup ps = sheet.getPrintSetup();
        // 打印方向，true：横向，false：纵向(默认)
        ps.setLandscape(false);
        // // 打印质量
        // ps.setVResolution((short) 700)
        // 设置缩放比例
        ps.setScale((short) 80);
        // 纸张类型
        ps.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);


        int rownum = 1;
        HSSFRow row0 = sheet.createRow((int) rownum);
        row0.setHeightInPoints(25);
        cell = row0.createCell(1);
        cell.setCellStyle(styleTitle);
        cell.setCellValue("入库单信息");
        sheet.addMergedRegion(new CellRangeAddress(rownum, rownum, (short) 1, (short) 13));
        cell = row0.createCell(2);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(3);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(4);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(5);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(6);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(7);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(8);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(9);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(10);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(11);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(12);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(13);
        cell.setCellStyle(styleTitle);
        rownum++;

        List<String> businessKeys = null;
        if ("1".equals(warehousingOrder.getSearchType())) {
            businessKeys = workflowService.getTaskBusinessKeysByCode("WAREHOUSING-ORDER-APPROVE");
        }

        Map<String, Object> pageView = new HashMap<>();
        pageView.put("businessKeys", businessKeys);
        pageView.put("batchId", warehousingOrder.getBatchId());
        pageView.put("appFlag", "1");
        // 查询入库单总数
        List<WarehousingOrder> dataList = baseMapper.getListByCondition(pageView);



        Double requestFundsTotal = 0d;//请款合计
        for (int i = 0; i < dataList.size(); i++) {
            WarehousingOrder warehousingOrder1 = dataList.get(i);
            //请款累计和
            requestFundsTotal = requestFundsTotal + warehousingOrder1.getRequestFunds();
        }

        HSSFRow rowp = sheet.createRow((int)(rownum));
        rowp.setHeightInPoints(20);
        cell = rowp.createCell(1);
        cell.setCellValue("合计");
        cell.setCellStyle(styleDetail);
        cell = rowp.createCell(2);
        cell.setCellStyle(styleDetail);
        cell = rowp.createCell(3);
        cell.setCellStyle(styleDetail);
        cell = rowp.createCell(4);
        cell.setCellStyle(styleDetail);
        cell = rowp.createCell(5);
        cell.setCellStyle(styleDetail);
        cell = rowp.createCell(6);
        cell.setCellStyle(styleDetail);
        cell = rowp.createCell(7);
        cell.setCellStyle(styleDetail);
        cell = rowp.createCell(8);
        cell.setCellStyle(styleDetail);
        cell = rowp.createCell(9);
        cell.setCellStyle(styleDetail);
        cell = rowp.createCell(10);
        cell.setCellStyle(styleDetail);
        cell = rowp.createCell(11);
        cell.setCellStyle(styleDetail);
        cell = rowp.createCell(12);
        cell.setCellStyle(styleDetail);
        cell = rowp.createCell(13);
        cell.setCellValue(requestFundsTotal);
        cell.setCellStyle(styleDetail1);
        rownum++;

        HSSFRow row1 = sheet.createRow((int) rownum);
        row1.setHeightInPoints(30);
        cell = row1.createCell(1);
        cell.setCellValue("货源");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(2);
        cell.setCellValue("发货库");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(3);
        cell.setCellValue("货名");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(4);
        cell.setCellValue("入库重量(吨)");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(5);
        cell.setCellValue("出库重量(吨)");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(6);
        cell.setCellValue("盈亏(吨)");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(7);
        cell.setCellValue("剩余重量(吨)");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(8);
        cell.setCellValue("粮款(元)");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(9);
        cell.setCellValue("已付(元)");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(10);
        cell.setCellValue("未付(元)");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(11);
        cell.setCellValue("费用(元)");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(12);
        cell.setCellValue("平均成本(元/吨)");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(13);
        cell.setCellValue("请款(元)");
        cell.setCellStyle(styleDetail);
        rownum++;

        // 详情信息
        if (!CollectionUtils.isEmpty(dataList)) {
            for (int i = 0; i < dataList.size(); i++) {
                WarehousingOrder warehousingOrder1 = dataList.get(i);

                HSSFRow rowx = sheet.createRow((int) rownum);
                rowx.setHeightInPoints(20);
                cell = rowx.createCell(1);
                cell.setCellValue(editString(warehousingOrder1.getGoodsSource()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(2);
                cell.setCellValue(editString(warehousingOrder1.getWarehouseName()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(3);
                cell.setCellValue(editString(warehousingOrder1.getGoodsName()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(4);
                cell.setCellValue(editFloat(warehousingOrder1.getInWarehouseWeight()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(5);
                cell.setCellValue(editFloat(warehousingOrder1.getOutWarehouseWeight()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(6);
                cell.setCellValue(editFloat(warehousingOrder1.getProfitAndLoss()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(7);
                cell.setCellValue(editFloat(warehousingOrder1.getSurplusWeight()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(8);
                cell.setCellValue(editDouble(warehousingOrder1.getGrainFund()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(9);
                cell.setCellValue(editDouble(warehousingOrder1.getAmountEdPayable()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(10);
                cell.setCellValue(editDouble(warehousingOrder1.getAmountNotPayable()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(11);
                cell.setCellValue(editDouble(warehousingOrder1.getAmountMoney()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(12);
                cell.setCellValue(editDouble(warehousingOrder1.getAvgCost()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(13);
                cell.setCellValue(editDouble(warehousingOrder1.getRequestFunds()));
                cell.setCellStyle(styleDetail);
                rownum++;
            }

        }


        String path = null;
        String tempPath = null;
        String excelPath = null;

        try {

            // 取得绝对路径
            tempPath = URLDecoder.decode((localPath), "utf-8");

            // EXCEL路径
            excelPath = "/web/temp/pay/" + DateUtil.formatDate(new Date(), DateUtils.DATE_FMT_YYYYMMDD_NS) + '/'
                    + UUID.randomUUID().toString().replaceAll("-", "");

            path = tempPath + excelPath + '/' + "仓库信息"
                    + ".xlsx";

        } catch (Exception e) {
            log.debug(e.getMessage());
        }

        return downloadPhone(path, response, wb);
    }
    /**
     * 判断字符串
     *
     * @param example
     * @return
     */
    private String editString(String example) {
        String exampleOne = example != null ? example : "";
        return exampleOne;
    }
    /**
     * 判断浮点数
     *
     * @param example
     * @return
     */
    private Float editFloat(Float example) {
        Float exampleOne = example != null ? example : 0f;
        return exampleOne;
    }
    /**
     * 判断浮点数
     *
     * @param example
     * @return
     */
    private Double editDouble(Double example) {
        Double exampleOne = example != null ? example : 0d;
        return exampleOne;
    }

    /**
     * 下载
     *
     * @param path
     * @param response
     */
    private String downloadPhone(String path, HttpServletResponse response, Workbook wb) {

        try {
            // 取得文件名。
            String fileName = "excel";
            // 给文件名编码
            fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 定义byte输出流
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            // 写导出文件
            wb.write(out);

            // 取得模板文件中的数据
            byte[] result = out.toByteArray();

            // 设置输出数据类型
            response.setContentType("application/vnd.ms-excel");
            // 设置输出数据长度
            response.setContentLength(result.length);

            // 设置文件名称
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            // 将文件流输出到画面
//            response.getOutputStream().write(result);

            out.flush();
            out.close();
            //生成的新文件路径
            String outputFile = "templates" + File.separator + fileName + ".xlsx";
            File file1 = new File(new String(outputFile.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
            try (FileOutputStream fos = new FileOutputStream(file1)) {
                wb.write(fos);
            }

            FileInputStream fileInputStream = new FileInputStream(file1.getAbsoluteFile());

            MultipartFile multipartFile = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
            String result1 = upload(multipartFile, fileName);
            file1.delete();
            return result1;
        } catch (IOException ex) {
            log.debug(ex.getMessage());
        }
        return "ng";
    }
    /**
     * 后台通过服务器间接传文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String upload(MultipartFile file, String name) throws IOException {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentType(file.getContentType());
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, "pcfiles/" + name + ".xlsx", file.getInputStream(), objectMetadata);
        ossClient.putObject(putObjectRequest);
        return baseUrl + "pcfiles/" + name + ".xlsx";
    }

    @Override
    public WarehousingOrder exportPhoneData(WarehousingOrder warehousingOrder) {
        List<String> businessKeys = null;
        if ("1".equals(warehousingOrder.getSearchType())) {
            businessKeys = workflowService.getTaskBusinessKeysByCode("WAREHOUSING-ORDER-APPROVE");
        }

        Map<String, Object> pageView = new HashMap<>();
        pageView.put("businessKeys", businessKeys);
        pageView.put("batchId", warehousingOrder.getBatchId());
        pageView.put("appFlag", "1");
        // 查询入库单总数
        List<WarehousingOrder> dataList = baseMapper.getListByCondition(pageView);

        Double requestFundsTotal = 0d;//请款合计
        Float inWarehouseWeightTotal = 0f;//重量合计
        for (int i = 0; i < dataList.size(); i++) {
            WarehousingOrder warehousingOrder1 = dataList.get(i);
            //请款累计和
            requestFundsTotal = requestFundsTotal + warehousingOrder1.getRequestFunds();
            inWarehouseWeightTotal=inWarehouseWeightTotal+warehousingOrder1.getInWarehouseWeight();
        }

        // 返回数据
        WarehousingOrder warehousingOrder1=new WarehousingOrder();
        warehousingOrder1.setRequestFundsTotal(requestFundsTotal);
        warehousingOrder1.setCount(dataList.size());
        warehousingOrder1.setInWarehouseWeightTotal(inWarehouseWeightTotal);
        if (dataList.size()>0) {
            warehousingOrder1.setWarehouseName(dataList.get(0).getWarehouseName());
            warehousingOrder1.setIssuingTime(dataList.get(0).getIssuingTime());
            warehousingOrder1.setRequestPerson(dataList.get(0).getRequestPerson());
            warehousingOrder1.setRequestDate(dataList.get(0).getRequestDate());
            warehousingOrder1.setWarehousingOrderList(dataList);
            String taskId = "";
            // 只有待审核状态才有taskId
            if (StringUtils.isNotBlank(dataList.get(0).getWorkflowId())) {
                JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(dataList.get(0).getWorkflowId()), dataList.get(0).getBatchId());
                taskId = jsonObject.getString("taskId");
                warehousingOrder1.setTaskId(taskId);
            }
        }
        return warehousingOrder1;
    }

    @Override
    public Page<WarehousingOrder> selectGoodSourceInfo(WarehousingOrder warehousingOrder) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (warehousingOrder.getCurrentPage() - 1)
                * warehousingOrder.getPageSize());
        pageView.put("searchKeyWord", warehousingOrder.getSearchKeyWord());
        pageView.put("pageSize", warehousingOrder.getPageSize());
        pageView.put("currentPage", warehousingOrder.getCurrentPage());
        pageView.put("startDate", warehousingOrder.getStartDate());
        pageView.put("endDate", warehousingOrder.getEndDate());
        pageView.put("baseId", warehousingOrder.getBaseId());
        pageView.put("flag", warehousingOrder.getFlag());
        // 查询总数
        Integer dataCount = baseMapper.getGoodSourceCountByCondition(pageView);
        List<WarehousingOrder> dataList = baseMapper.getGoodSourceListByCondition(pageView);
        Page<WarehousingOrder> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(warehousingOrder.getCurrentPage());
        page.setSize(warehousingOrder.getPageSize());
        return page;
    }

    private List<String> getResourceIdList() {
        User currentUser = AuthSecurityUtils.getCurrentUserInfo();
        // 当前登录人主要角色
        return roleResourceService.getBindResourcesByUserId(currentUser.getUserId()).stream()
                .map(CommonRoleResource::getResourceId).collect(Collectors.toList());
    }
}
