package com.prolog.cs.base.gsp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.StopWatch;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.codingapi.tx.annotation.TxTransaction;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.prolog.cs.base.gsp.QueryDTO;
import com.prolog.cs.base.gsp.dao.DxiGspMaintenanceRecordMapper;
import com.prolog.cs.base.gsp.dao.GspUpkeepCheckMapper;
import com.prolog.cs.base.gsp.dao.GspUpkeepCheckPlanMapper;
import com.prolog.cs.base.gsp.model.DxiGspMaintenanceRecord;
import com.prolog.cs.base.gsp.model.GspUpkeepCheck;
import com.prolog.cs.base.gsp.model.GspUpkeepCheckPlan;
import com.prolog.cs.base.gsp.resource.*;
import com.prolog.cs.base.gsp.service.GspUpkeepCheckService;
import com.prolog.cs.base.gsp.utils.RestMsgHelper;
import com.prolog.cs.base.gsp.vo.*;
import com.prolog.cs.basic.chain.model.cargo.BaseCargoOwnerMst;
import com.prolog.cs.basic.common.model.BaseCommonDict;
import com.prolog.cs.basic.item.model.BaseMtlItemHealth;
import com.prolog.cs.basic.item.model.BaseMtlItemMst;
import com.prolog.cs.basic.item.model.vo.ItemBaseInfoVO;
import com.prolog.cs.basic.warehouse.model.BaseWmsWarehouseArea;
import com.prolog.cs.basic.warehouse.model.BaseWmsWarehouseMst;
import com.prolog.cs.basic.warehouse.model.vo.WarehouseLocatorBasicInfo;
import com.prolog.cs.biz.outbound.model.dto.ContainerConfirmDto;
import com.prolog.cs.biz.outbound.model.dto.EisConfirmSubVo;
import com.prolog.entity.vo.OperationCompleteItemVO;
import com.prolog.entity.vo.OperationCompleteVO;
import com.prolog.entity.vo.OutBoundRequestItemVO;
import com.prolog.entity.vo.OutBoundRequestVO;
import com.prolog.enums.OutBoundRequestEnum;
import com.prolog.framework.authority.core.dto.UserDTO;
import com.prolog.framework.authority.user.UserTemplate;
import com.prolog.framework.bz.core.collection.ValidList;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.core.exception.ParameterException;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.core.pojo.Page;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Order;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.framework.dao.util.PageUtils;
import com.prolog.framework.toolkit.MapToolKit;
import com.prolog.framework.utils.*;
import com.prolog.inte.EisHandler;
import com.prolog.upcloud.base.inventory.model.WmsInvStockLot;
import com.prolog.upcloud.base.inventory.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static com.prolog.cs.base.gsp.constant.EisConstant.*;
import static com.prolog.cs.base.gsp.constant.MsgTemplate.DATA_OVERDUE;
import static com.prolog.cs.base.gsp.constant.WhOperataConstant.PICK_MODE_DEVICE;

@Service
public class GspUpkeepCheckServiceImpl implements GspUpkeepCheckService {

    private static Logger logger = LoggerFactory.getLogger(GspUpkeepCheckServiceImpl.class);

    @Autowired
    private GspUpkeepCheckMapper mapper;

    @Autowired
    private GspUpkeepCheckPlanMapper upkeepCheckPlanMapper;

    @Autowired
    private UserTemplate userTemplate;

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private WarehouseClient warehouseClient;

    @Autowired
    private ChainClient chainClient;

    @Autowired
    private CommonClient commonClient;

    @Autowired
    private DxiGspMaintenanceRecordMapper dxiOmsMaintenanceRecordMapper;

    @Autowired
    private InventoryClient inventoryClient;

    @Autowired
    private AutoUpKeepTask autoUpKeepTask;

    @Resource
    private EisHandler eisHandler;

    // 可配置自动养护定时任务的用户信息
    @Value("${prolog.autoUpkeep.userId:599299328393220096}")
    private String autoUserId;
    @Value("${prolog.autoUpkeep.userName:昆中药WMS管理员}")
    private String autoUserName;
    @Value("${prolog.autoUpkeep.enterpriseId:106}")
    private String autoEnterpriseId;

    @Autowired
    private IntegrationResource integrationResource;

    // 设备下发配置 - by Huanglh 2022-03-01
    @Value("${prolog.integration.sendDeviceId:}")
    private String sendDeviceId;

    @Value("${prolog.integration.sendWmsId:}")
    private String sendWmsId;

    @Value("${prolog.integration.updateDeviceId:}")
    private String updateDeviceId;

    @Value("${prolog.integration.updateDeviceOkId:}")
    private String updateDeviceOkId;

    @Value("${prolog.integration.token:}")
    private String token;

    @Value("${oms.dxiGspMaintenanceRecordUrl}")
    private String dxiGspMaintenanceRecordUrl;
    @Resource
    private EisResource eisResource;

    @Override
    public void batchAdd(String source, List<GspUpkeepCheck> modelList) {
        RestMessage<Map<String,String>> upKeepDictResult = commonClient.findUpKeepDict(0);
        if (upKeepDictResult==null || !upKeepDictResult.isSuccess() || upKeepDictResult.getData() == null) {
            throw new ParameterException("数据字典【GSP养护关联商品大类】配置错误，请联系管理员");
        }
        RestMessage<Map<String,String>> upKeepDictResultVip = commonClient.findUpKeepDict(1);
        if (upKeepDictResultVip==null || !upKeepDictResultVip.isSuccess() || upKeepDictResultVip.getData() == null) {
            throw new ParameterException("数据字典【GSP养护关联商品大类】配置错误，请联系管理员");
        }
        BaseWmsWarehouseMst wmsWarehouseMst=null;
        String warehouseId = modelList.get(0).getWarehouseId();
        RestMessage<BaseWmsWarehouseMst> itemResultWarehouse = warehouseClient.warehouse(warehouseId);
        if (itemResultWarehouse.isSuccess() && itemResultWarehouse.getData() != null) {
            wmsWarehouseMst=itemResultWarehouse.getData();
        }
        if (null == wmsWarehouseMst) {
            throw new ParameterException("仓库不能为空");
        }
        //请求商品信息
        String[] itemIds = modelList.stream().map(GspUpkeepCheck::getItemId).distinct().toArray(String[]::new);
        RestMessage<List<BaseMtlItemMst>> itemResult = itemClient.getListByIds(itemIds);
        if (itemResult==null || !itemResult.isSuccess() || itemResult.getData() == null) {
            throw new ParameterException("获取商品资料异常，请联系管理员");
        }
        // 自动或手动的情况下，获取用户信息
        UserDTO userDTO = this.getUpkeepUser(source);
        for (int i = 1; i < 9; i++) {
            List<GspUpkeepCheck> list = new ArrayList<>();
            for (int j = 0; j < modelList.size(); j++) {
                GspUpkeepCheck gspUpkeepCheck = modelList.get(j);
                if (gspUpkeepCheck == null) {
                    continue;
                }
                BaseMtlItemMst itemBaseInfoVO = itemResult.getData().stream().filter(item -> item.getItemId().equals(gspUpkeepCheck.getItemId())).findFirst().orElse(null);
                if (itemBaseInfoVO == null || itemBaseInfoVO.getBaseMtlItemHealth() == null || StringUtils.isBlank(itemBaseInfoVO.getBaseMtlItemHealth().getItemHealthCategoryName())) {
                    if (i == 3) {
                        list.add(gspUpkeepCheck);
                    }
                } else {
                    String itemHealthCategoryName = itemBaseInfoVO.getBaseMtlItemHealth().getItemHealthCategoryName();
                    if(gspUpkeepCheck.getIsProtected()==null){
                        if(itemBaseInfoVO.getBaseMtlItemHealth().getIsProtected()!=null){
                            gspUpkeepCheck.setIsProtected(itemBaseInfoVO.getBaseMtlItemHealth().getIsProtected());
                        }
                    }
                    if (gspUpkeepCheck.getIsProtected() == 1) {
                        Integer upKeepType = parseUpKeepTypeVip(upKeepDictResultVip.getData().get(itemHealthCategoryName));
                        if (i == 3 && (upKeepType == null || upKeepType == i || upKeepType < 6)) {
                            list.add(gspUpkeepCheck);
                        } else if (upKeepType != null && upKeepType == i) {
                            list.add(gspUpkeepCheck);
                        }
                    } else {
                        Integer integer = parseUpKeepType(upKeepDictResult.getData().get(itemHealthCategoryName));
                        if (i == 6 && (integer == null || integer == i)) {
                            list.add(gspUpkeepCheck);
                        } else if (integer != null && integer == i) {
                            list.add(gspUpkeepCheck);
                        }
                    }
                }
            }
            logger.info("生成养护计划入参:{}", JSONUtil.toJsonStr(list));
            batchAddDbPage(source,userDTO,wmsWarehouseMst,list,i);
        }
    }

    private void addDbPage(List<GspUpkeepCheck> modelList, Map<String, String> upKeepDictResult, Map<String, String> upKeepDictResultVip, List<BaseMtlItemMst> itemList, int i, List<GspUpkeepCheck> list) {
        for (int j = 0; j < modelList.size(); j++) {
            GspUpkeepCheck gspUpkeepCheck = modelList.get(j);
            if (gspUpkeepCheck == null) {
                continue;
            }
            BaseMtlItemMst itemBaseInfoVO = itemList.stream().filter(item -> item.getItemId().equals(gspUpkeepCheck.getItemId())).findFirst().orElse(null);
            if (itemBaseInfoVO == null || itemBaseInfoVO.getBaseMtlItemHealth() == null || StringUtils.isBlank(itemBaseInfoVO.getBaseMtlItemHealth().getItemHealthCategoryName())) {
                if (i == 3) {
                    list.add(gspUpkeepCheck);
                }
            } else {
                String itemHealthCategoryName = itemBaseInfoVO.getBaseMtlItemHealth().getItemHealthCategoryName();
                if (gspUpkeepCheck.getIsProtected() == null || gspUpkeepCheck.getIsProtected() == 1) {
                    Integer upKeepType = parseUpKeepTypeVip(upKeepDictResultVip.get(itemHealthCategoryName));
                    if (i == 3 && (upKeepType == null || upKeepType == i || upKeepType > 5)) {
                        list.add(gspUpkeepCheck);
                    } else if (upKeepType != null && upKeepType == i) {
                        list.add(gspUpkeepCheck);
                    }
                } else {
                    Integer integer = parseUpKeepType(upKeepDictResult.get(itemHealthCategoryName));
                    if (i == 6 && (integer == null || integer == i)) {
                        list.add(gspUpkeepCheck);
                    } else if (integer != null && integer == i) {
                        list.add(gspUpkeepCheck);
                    }
                }
            }
        }
    }

    /**
     * 获取用户信息，自动创建任务时，使用自己构建的用户DTO
     *
     * @param source
     * @return
     */
    private UserDTO getUpkeepUser(String source) {
        UserDTO userDTO;
        if (source.equals("1")) {
            // 自动情况下需要创建UserDTO
            userDTO = new UserDTO();
            RestMessage<List<BaseCommonDict>> autoGspConfig = commonClient.getDictBasicListByCodes("autoGspConfig", null);
            if (null == autoGspConfig || CollUtil.isEmpty(autoGspConfig.getData())) {
                throw new BizException("请配置自动养护字典项");
            }
            List<BaseCommonDict> dictList = autoGspConfig.getData();
            userDTO.setId(dictList.stream().filter(x->x.getDictCode().equals("userId")).findFirst().orElse(null).getDictName());
            userDTO.setNickname(dictList.stream().filter(x->x.getDictCode().equals("userName")).findFirst().orElse(null).getDictName());
            userDTO.setEnterpriseId(dictList.stream().filter(x->x.getDictCode().equals("enterpriseId")).findFirst().orElse(null).getDictName());
//            userDTO.setId(autoUserId);
//            userDTO.setNickname(autoUserName);
//            userDTO.setEnterpriseId(autoEnterpriseId);
        } else {
            userDTO = userTemplate.getUserDTO();
        }
        return userDTO;
    }

    public void batchAddDbPage(String source, UserDTO userDTO, BaseWmsWarehouseMst wmsWarehouseMst, List<GspUpkeepCheck> modelList, Integer upkeepType) {
        int pageSize = 1000;
        int size = modelList.size();
        if (size < pageSize) {
            batchAddDb(source, userDTO, wmsWarehouseMst, upkeepType, modelList);
            return;
        }
        int pageNum = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;
        for (int i = 0; i < pageNum; i++) {
            if (i != (pageNum - 1)) {
                batchAddDb(source, userDTO, wmsWarehouseMst, upkeepType, modelList.subList(i * pageSize, i * pageSize + pageSize));
            } else {
                batchAddDb(source, userDTO, wmsWarehouseMst, upkeepType, modelList.subList(i * pageSize, size));
            }
        }
    }

    @Override
    public void batchAddStockLockDb(List<WmsInvStockLot> wmsInvStockLots) {

        UserDTO userDTO = this.getUpkeepUser("0");
        String userId = userDTO.getId();
        String userName = userDTO.getNickname();
        Date date = new Date();
        String enterpriseId = userDTO.getEnterpriseId();
        Set<String> locids = new HashSet<>();
        Set<String> itemids = new HashSet<>();
        Set<String> warehouseIds = new HashSet<>();
        for (WmsInvStockLot stockLot : wmsInvStockLots) {
            locids.add(stockLot.getLocatorId());
            itemids.add(stockLot.getItemId());
            warehouseIds.add(stockLot.getWarehouseId());
        }
        Map<String, BaseWmsWarehouseMst> warehouseMstMap = new HashMap<>();
        //批量查询仓信息
        if (warehouseIds.size() > 0) {
            warehouseMstMap = RestMsgHelper.unpack(warehouseClient.mapbyids(warehouseIds));
        }
        Map<String, WarehouseLocatorBasicInfo> locationMstMap = new HashMap<>();
        //批量查询货位信息
        if (locids.size() > 0) {
            //获取货位信息
            RestMessage<List<WarehouseLocatorBasicInfo>> locationBasicInfos = warehouseClient.getLocationBasicInfos(locids.toArray(new String[]{}));
            if (!locationBasicInfos.isSuccess() || locationBasicInfos.getData() == null) {
                throw new BizException("查询货位关联信息失败!请重试或联系管理员!");
            }
            for (WarehouseLocatorBasicInfo locinfo : locationBasicInfos.getData()) {
                locationMstMap.put(locinfo.getWarehouseLocatorId(), locinfo);
            }
        }
        Map<String, BaseMtlItemMst> litemMstMap = new HashMap<>();
        //批量查询商品信息
        if (itemids.size() > 0) {
            RestMessage<List<BaseMtlItemMst>> itemResult = itemClient.getListByIds(itemids.toArray(new String[]{}));
            if (!itemResult.isSuccess() || itemResult.getData() == null) {
                throw new BizException("查询商品关联信息失败!请重试或联系管理员!");
            }
            for (BaseMtlItemMst iteminfo : itemResult.getData()) {
                litemMstMap.put(iteminfo.getItemId(), iteminfo);
            }
        }
        GspUpkeepCheckPlan plan = new GspUpkeepCheckPlan();
        String planId = String.valueOf(SnowFlakeUtils.getId());
        String code = "SDD" + planId.substring(planId.length() - 8);
        plan.setId(planId);
        plan.setCode(code);
        plan.setCreator(userId);
        plan.setCreatorName(userName);
        plan.setGmtCreate(date);
        plan.setModifier(userId);
        plan.setModifierName(userName);
        plan.setGmtModified(date);
        plan.setDcId(warehouseMstMap.get(wmsInvStockLots.get(0).getWarehouseId()).getDcId());
        plan.setEnterpriseId(enterpriseId);
        plan.setWarehouseId(wmsInvStockLots.get(0).getWarehouseId());
        //        plan.setBldgId(wmsInvStockLots.get(0).getBldgId());
        plan.setStatus("4");
        plan.setCargoOwnerId(wmsInvStockLots.get(0).getCargoOwnerId());
        plan.setSource("1");//数据来源：0=手动 1=自动
        plan.setPrintCount(0);
        upkeepCheckPlanMapper.save(plan);
        List<GspUpkeepCheck> gspUpkeepCheckList = new ArrayList<>();
        for (WmsInvStockLot wmsInvStockLot : wmsInvStockLots) {
            GspUpkeepCheck model = new GspUpkeepCheck();
            String id = String.valueOf(SnowFlakeUtils.getId());
            model.setId(id);
            model.setCode("SDD" + id.substring(id.length() - 8));
            model.setEnterpriseId(enterpriseId);
            model.setPlanUpkeepDate(date);
            model.setUpkeepDate(date);
            model.setUpkeepType(6);
            model.setPlanId(plan.getId());
            model.setPlanCode(code);
            model.setBatchId(wmsInvStockLot.getBatchId());
            BaseWmsWarehouseMst baseWmsWarehouseMst = warehouseMstMap.get(wmsInvStockLot.getWarehouseId());
            //获取仓信息
            model.setDcId(baseWmsWarehouseMst.getDcId());
            model.setWarehouseName(baseWmsWarehouseMst.getWarehouseName());
            model.setWarehouseId(model.getWarehouseId());
            model.setStockQty(model.getStockQty());
            // 需要初始化养护数量(默认等于库存数量，解决空指针异常问题)
            model.setUpkeepQty(model.getStockQty());
            model.setPlanStockQty(model.getStockQty());
            model.setCreator(userId);
            model.setCreatorName(userName);
            model.setGmtCreate(date);
            model.setModifier(userId);
            model.setModifierName(userName);
            model.setGmtModified(date);
            model.setStatus("4");
            // 数据来源：0=手动 1=自动 - by Huanglh 2022-01-20
            model.setSourceType("0");
            model.setWarehouseId(wmsInvStockLot.getWarehouseId());
            //获取商品资料
            model.setUpkeepConclusion(0);
            BaseMtlItemMst iteminfo = litemMstMap.get(wmsInvStockLot.getItemId());
            model.setItemCode(iteminfo.getItemCode());
            model.setItemId(wmsInvStockLot.getItemId());
            model.setItemName(iteminfo.getItemName());
            model.setCargoOwnerId(wmsInvStockLot.getCargoOwnerId());
            model.setUpkeepQty(wmsInvStockLot.getQuantity().toString());
            model.setStockQty(wmsInvStockLot.getQuantity().toString());
            model.setLotNum(wmsInvStockLot.getBatchNum());
            model.setUpkeepOperator(userDTO.getNickname());

            //获取货位信息
            WarehouseLocatorBasicInfo locatorBasicInfo = locationMstMap.get(wmsInvStockLot.getLocatorId());
            model.setLocatorId(wmsInvStockLot.getLocatorId());
            model.setLocatorCode(locatorBasicInfo.getWarehouseLocatorCode());
            model.setLocatorName(locatorBasicInfo.getWarehouseLocatorName());
            gspUpkeepCheckList.add(model);
        }


        mapper.saveBatch(gspUpkeepCheckList);
    }

    public void batchAddDb(String source, UserDTO userDTO, BaseWmsWarehouseMst wmsWarehouseMst, Integer upkeepType, List<GspUpkeepCheck> modelList) {
        if (modelList == null || modelList.size() == 0) {
            return;
        }
        String userId = userDTO.getId();
        String userName = userDTO.getNickname();
        String enterpriseId = userDTO.getEnterpriseId();
        Date date = new Date();
        GspUpkeepCheckPlan plan = new GspUpkeepCheckPlan();
        String planId = String.valueOf(SnowFlakeUtils.getId());
        String code = "YHD" + planId.substring(planId.length() - 8);
        plan.setId(planId);
        plan.setCode(code);
        plan.setCreator(userId);
        plan.setCreatorName(userName);
        plan.setGmtCreate(date);
        plan.setModifier(userId);
        plan.setModifierName(userName);
        plan.setGmtModified(date);
        plan.setDcId(wmsWarehouseMst.getDcId());
        plan.setEnterpriseId(enterpriseId);
        plan.setWarehouseId(wmsWarehouseMst.getWarehouseId());
        plan.setBldgId(modelList.get(0).getBldgId());
        plan.setStatus("0");
        plan.setCargoOwnerId(modelList.get(0).getCargoOwnerId());
        plan.setSource(source);//数据来源：0=手动 1=自动
        plan.setPrintCount(0);
        plan.setIsProtected(modelList.get(0).getIsProtected());
        if (plan.getIsProtected() == null && upkeepType != null) {
            if (upkeepType < 6) {
                plan.setIsProtected(1);
            } else {
                plan.setIsProtected(0);
            }
        }
        plan.setUpkeepType(upkeepType);
        upkeepCheckPlanMapper.save(plan);
        for (int i = 0; i < modelList.size(); i++) {
            GspUpkeepCheck model = modelList.get(i);
            String id = String.valueOf(SnowFlakeUtils.getId());
            model.setContainerCode(model.getContainerCode());
            model.setId(id);
            model.setCode("YHD" + id.substring(id.length() - 8));
            model.setPlanId(planId);
            model.setPlanCode(code);
            model.setEnterpriseId(enterpriseId);
            model.setPlanUpkeepDate(date);
            model.setUpkeepDate(date);
            //客户要求，没有的分类大类先划到其他里面
            if (upkeepType != null) {
                model.setUpkeepType(upkeepType);
            } else {
                if ("1".equals(model.getIsProtected())) {
                    if (model.getUpkeepType() == null || model.getUpkeepType() > 5) {
                        model.setUpkeepType(3);
                    }
                } else {
                    if (model.getUpkeepType() == null || model.getUpkeepType() <= 5) {
                        model.setUpkeepType(6);
                    }
                }
            }
            model.setDcId(wmsWarehouseMst.getDcId());
            model.setWarehouseId(model.getWarehouseId());
            model.setStockQty(model.getStockQty());
            // 需要初始化养护数量(默认等于库存数量，解决空指针异常问题)
            model.setUpkeepQty(model.getStockQty());
            model.setPlanStockQty(model.getStockQty());
            model.setCreator(userId);
            model.setCreatorName(userName);
            model.setGmtCreate(date);
            model.setModifier(userId);
            model.setModifierName(userName);
            model.setGmtModified(date);
            model.setStatus("0");
            model.setUpkeepConclusion(0);
            // 数据来源：0=手动 1=自动 - by Huanglh 2022-01-20
            model.setSourceType(source);
            mapper.save(model);
        }
        //pushDevice(sendDeviceId, modelList);
    }

    private void pushDevice(String interfaceId, List<GspUpkeepCheck> modelList) {
        String[] locatorIdList = modelList.stream().map(GspUpkeepCheck::getLocatorId).toArray(String[]::new);
        RestMessage<List<WarehouseLocatorBasicInfo>> locationBasicInfos = warehouseClient.getLocationBasicInfos(locatorIdList);
        if (!locationBasicInfos.isSuccess() || locationBasicInfos.getData() == null) {
            throw new BizException("查询货位关联信息失败!请重试或联系管理员!");
        } else {
            Set<String> set = locationBasicInfos.getData().stream().filter(t -> "Device".equals(t.getPickMode())).map(WarehouseLocatorBasicInfo::getWarehouseLocatorId).collect(Collectors.toSet());
            List<GspUpkeepCheck> deviceList = modelList.stream().filter(t -> set.contains(t.getLocatorId())).collect(Collectors.toList());
            logger.info("WmsReplenishH replenishH deviceList：" + JSONObject.toJSONString(deviceList));
            if (deviceList != null && deviceList.size() > 0) {
                askIntegration(interfaceId, deviceList);
            }
        }
    }

    private Integer parseUpKeepType(String upKeepType) {
        if (StringUtils.isBlank(upKeepType)) {
            return null;
        }
        switch (upKeepType) {
//            case "GSP_YH_ZD_YaoPin_TeShu":
//                return 1;
//            case "GSP_YH_ZD_YaoPin_ZhuanGuan":
//                return 2;
//            case "GSP_YH_ZD_YaoPin_QiTa":
//                return 3;
//            case "GSP_YH_ZD_QiXie":
//                return 4;
//            case "GSP_YH_ZD_No_YaoPin":
//                return 5;
            case "GSP_YH_YaoPin":
                return 6;
            case "GSP_YH_QiXie":
                return 7;
            case "GSP_YH_No_YaoPin":
                return 8;
            default:
                return 6;
        }
    }

    private Integer parseUpKeepTypeVip(String upKeepType) {
        if (StringUtils.isBlank(upKeepType)) {
            return null;
        }
        switch (upKeepType) {
            case "GSP_YH_ZD_YaoPin_TeShu":
                return 1;
            case "GSP_YH_ZD_YaoPin_ZhuanGuan":
                return 2;
            case "GSP_YH_ZD_YaoPin_QiTa":
                return 3;
            case "GSP_YH_ZD_QiXie":
                return 4;
            case "GSP_YH_ZD_No_YaoPin":
                return 5;
//            case "GSP_YH_YaoPin":
//                return 6;
//            case "GSP_YH_QiXie":
//                return 7;
//            case "GSP_YH_No_YaoPin":
//                return 8;
            default:
                return 3;
        }
    }

    @Override
    public Page<GspUpkeepCheckVO> listPage(String warehouseId, String cargoOwnerId, String status, String billtype, Integer pageSize, Integer pageNum) {
        UserDTO userDTO = userTemplate.getUserDTO();
        String enterpriseId = userDTO.getEnterpriseId();
        if ("-1".equals(warehouseId) && "-1".equals(cargoOwnerId)) {//手动执行定时任务，待优化
            autoUpKeepTask.autoUpKeepTask(null,null,null);
        }
        Restriction r5 = null;
        if (!StringUtils.isBlank(billtype)) {
            r5 = Restrictions.like("code", billtype + "%");
        }
        PageHelper.startPage(pageNum, pageSize);
        Criteria crt = Criteria.forClass(GspUpkeepCheck.class);
        Restriction r1 = Restrictions.eq("enterpriseId", enterpriseId);
        Restriction r2 = Restrictions.eq("warehouseId", warehouseId);
        Restriction r3 = StringUtils.isEmpty(cargoOwnerId) ? null : Restrictions.eq("cargoOwnerId", cargoOwnerId);
        Restriction r4 = Restrictions.eq("status", status);
        crt.setOrder(Order.newInstance().asc("gmtCreate"));
        crt.setRestriction(Restrictions.and(r1, r2, r3, r4, r5));
        List<GspUpkeepCheck> list = mapper.findByCriteria(crt);
        Page<GspUpkeepCheck> page = PageUtils.getPage(list);
        Page<GspUpkeepCheckVO> pageResult = new Page<>();
        BeanUtil.copyProperties(page, pageResult);
        List<GspUpkeepCheckVO> result = spellGspUpkeepCheckVOS(list);
        pageResult.setList(result);
        return pageResult;
        //return PageUtils.getPage(spellGspUpkeepCheckVOS(list));
    }

    @Override
    public Page<GspUpkeepCheckVO> findUpkeepPage(QueryDTO dto) {
        dto.initialPageWhenValueIsNull(userTemplate.getUserDTO());
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<GspUpkeepCheck> list = getGspUpkeepChecks(dto);
        if (CollUtil.isEmpty(list)) {
            return PageUtils.getPage(Collections.emptyList());
        }
        Page<GspUpkeepCheck> page = PageUtils.getPage(list);
        Page<GspUpkeepCheckVO> pageResult = new Page<>();
        BeanUtil.copyProperties(page, pageResult);
        List<GspUpkeepCheckVO> result = spellGspUpkeepCheckVOS(list);
        pack4FindUpkeepPage(result);
        pageResult.setList(result);
        return pageResult;
    }

    private void pack4FindUpkeepPage(List<GspUpkeepCheckVO> result) {
        List<WmsInvStockQtyQueryVO> qtyQueries = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            WmsInvStockQtyQueryVO wmsInvStockQtyQueryVO = new WmsInvStockQtyQueryVO();
            BeanUtils.copyProperties(result.get(i), wmsInvStockQtyQueryVO);
            wmsInvStockQtyQueryVO.setStatus("1");
            wmsInvStockQtyQueryVO.setEnterpriseId(userTemplate.getUserDTO().getEnterpriseId());
            qtyQueries.add(wmsInvStockQtyQueryVO);
        }
        RestMessage<List<WmsInvStockQtyVO>> restRet = inventoryClient.getAvailableQuantityList(qtyQueries);
        if (restRet != null && restRet.isSuccess() && restRet.getData() != null && restRet.getData().size() == result.size()) {
            for (int i = 0; i < result.size(); i++) {
                GspUpkeepCheckVO gspUpkeepCheckVO = result.get(i);
                WmsInvStockQtyVO wmsInvStockQtyVO = restRet.getData().stream().filter(x -> x.getBatchId().equals(gspUpkeepCheckVO.getBatchId()) && x.getLocatorId().equals(gspUpkeepCheckVO.getLocatorId())).findFirst().orElse(null);
                if(wmsInvStockQtyVO!=null){
                    String stockQty = wmsInvStockQtyVO.getAvailableQuantity().toString();
                    gspUpkeepCheckVO.setStockQty(stockQty);
                    gspUpkeepCheckVO.setUpkeepQty(stockQty);
                }
//                String stockQty = restRet.getData().get(i).getAvailableQuantity().toString();
//                result.get(i).setStockQty(stockQty);
//                result.get(i).setUpkeepQty(stockQty);
            }
        }
    }


    private List<GspUpkeepCheck> getGspUpkeepChecks(QueryDTO upkeepCheckDTO) {
        Criteria crt = Criteria.forClass(GspUpkeepCheck.class);
        Restriction r1 = Restrictions.eq("planId", upkeepCheckDTO.getId());
        String upkeepType = upkeepCheckDTO.getUpkeepType();
        Restriction r2 = StringUtils.isEmpty(upkeepType) ? null : Restrictions.eq("upkeepType", upkeepType);
        Restriction r3 = Restrictions.eq("status", 0);
        String itemHealthCategory = upkeepCheckDTO.getItemHealthCategory();
        Restriction r4 = StringUtils.isEmpty(itemHealthCategory) ? null : Restrictions.eq("itemHealthCategory", itemHealthCategory);
        String itemId = upkeepCheckDTO.getItemId();
        Restriction r5 = StringUtils.isEmpty(itemId) ? null : Restrictions.eq("itemId", itemId);
        crt.setOrder(Order.newInstance().asc("storeTemperature","locatorCode", "itemCode", "lotNum"));
        crt.setRestriction(Restrictions.and(r1, r2, r3, r4, r5));
        return mapper.findByCriteria(crt);
    }

    @Override
    public List<GspUpkeepCheckVO> spellGspUpkeepCheckVOSPage(List<GspUpkeepCheck> list) {
        if (list == null) {
            return null;
        }
        int pageSize = 1000;
        int size = list.size();
        if (size < pageSize) {
            return spellGspUpkeepCheckVOS(list);
        }
        int pageNum = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;
        List<GspUpkeepCheckVO> retList = new ArrayList<>();
        for (int i = 0; i < pageNum; i++) {
            if (i != (pageNum - 1)) {
                retList.addAll(spellGspUpkeepCheckVOS(list.subList(i * pageSize, i * pageSize + pageSize)));
            } else {
                retList.addAll(spellGspUpkeepCheckVOS(list.subList(i * pageSize, size)));
            }
        }
        return retList;
    }

    public List<GspUpkeepCheckVO> spellGspUpkeepCheckVOS(List<GspUpkeepCheck> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        String[] itemIds = list.stream().map(GspUpkeepCheck::getItemId).distinct().toArray(String[]::new);
        //请求商品信息
        RestMessage<List<BaseMtlItemMst>> itemResult = itemClient.getListByIds(itemIds);
        //组合id
        String[] locatorIds = list.stream().map(GspUpkeepCheck::getLocatorId).distinct().toArray(String[]::new);
        //请求仓库信息，超长已经设置长度
        RestMessage<List<WarehouseLocatorBasicInfo>> warehouseResult = warehouseClient.getLocationBasicInfos(locatorIds);
        //组合id,转换并组装
        String[] cargoOwnerIds = list.stream().map(GspUpkeepCheck::getCargoOwnerId).distinct().toArray(String[]::new);
        //请求货位信息
        RestMessage<Map<String, BaseCargoOwnerMst>> cargoOwnerResult = chainClient.getCargoOwnerMstByIds(cargoOwnerIds);
        List<GspUpkeepCheckVO> listRet = new ArrayList<>();
        for (GspUpkeepCheck gspUpkeepCheckD : list) {
            GspUpkeepCheckVO gspUpkeepCheckVO = new GspUpkeepCheckVO();
            BeanUtils.copyProperties(gspUpkeepCheckD, gspUpkeepCheckVO);
            gspUpkeepCheckVO.setInContainerCode(gspUpkeepCheckD.getContainerCode());
            gspUpkeepCheckVO.setPendingQty(gspUpkeepCheckD.getPendingQty() == null?"0":gspUpkeepCheckD.getPendingQty().toString());
            gspUpkeepCheckVO.setRemark("检查外观，包装等质量状况。");
            List<BaseMtlItemMst> resultData = itemResult.getData();
            if (itemResult.isSuccess() && resultData != null) {
                if (CollUtil.isNotEmpty(warehouseResult.getData())) {
                    Optional<WarehouseLocatorBasicInfo> optional = warehouseResult.getData().stream().filter(y -> y.getWarehouseLocatorId().equals(gspUpkeepCheckD.getLocatorId())).findFirst();
                    if (optional.isPresent()) {
                        WarehouseLocatorBasicInfo locatorBasicInfo = optional.get();
                        gspUpkeepCheckVO.setWarehouseName(locatorBasicInfo.getWarehouseName());
                        gspUpkeepCheckVO.setLocatorCode(locatorBasicInfo.getWarehouseLocatorCode());
                        gspUpkeepCheckVO.setLocatorName(locatorBasicInfo.getWarehouseLocatorName());
                        gspUpkeepCheckVO.setWhWarehouseLocatorType(locatorBasicInfo.getWarehouseLocatorType());
                        gspUpkeepCheckVO.setBldgName(locatorBasicInfo.getBldgName());
                        gspUpkeepCheckVO.setOutWhAreaCategory(locatorBasicInfo.getWarehouseAreaCategory());
                        gspUpkeepCheckVO.setOutWhAreaCategoryName(locatorBasicInfo.getWarehouseAreaCategoryName());
                        gspUpkeepCheckVO.setWarehouseRoomName(locatorBasicInfo.getWarehouseRoomName());
                        gspUpkeepCheckVO.setWarehouseAreaCategory(locatorBasicInfo.getWarehouseAreaCategory());
                        gspUpkeepCheckVO.setWarehouseAreaName(locatorBasicInfo.getWarehouseAreaName());
                    }
                }
                BaseMtlItemMst itemBaseInfoVO = resultData.stream().filter(item -> item.getItemId().equals(gspUpkeepCheckD.getItemId())).findFirst().orElse(null);
                if (itemBaseInfoVO != null) {
                    gspUpkeepCheckVO.setItemName(itemBaseInfoVO.getItemName());
                    gspUpkeepCheckVO.setManufacturerName(itemBaseInfoVO.getManufacturerId());
                    gspUpkeepCheckVO.setSpecification(itemBaseInfoVO.getSpecification());
                    gspUpkeepCheckVO.setCaseUom(itemBaseInfoVO.getCaseUom());
                    gspUpkeepCheckVO.setCaseConversionRate(itemBaseInfoVO.getCaseConversionRate());
                    gspUpkeepCheckVO.setCountryOriginName(itemBaseInfoVO.getCountryOriginId());
                    String upkeepQty = gspUpkeepCheckVO.getUpkeepQty();
                    if ("0".equals(gspUpkeepCheckVO.getWhWarehouseLocatorType())) {
                        gspUpkeepCheckVO.setCaseQuantity(new BigDecimal(upkeepQty).divide(itemBaseInfoVO.getCaseConversionRate(), RoundingMode.HALF_UP));
                        gspUpkeepCheckVO.setOddPieceQuantity(BigDecimal.ZERO);
                    } else {
                        gspUpkeepCheckVO.setCaseQuantity(BigDecimal.ZERO);
                        if (!StringUtils.isBlank(upkeepQty)) {
                            gspUpkeepCheckVO.setOddPieceQuantity(new BigDecimal(upkeepQty));
                        }
                    }
                    BaseMtlItemHealth baseMtlItemHealth = itemBaseInfoVO.getBaseMtlItemHealth();
                    if (baseMtlItemHealth != null) {
                        gspUpkeepCheckVO.setItemHealthCategoryName(baseMtlItemHealth.getItemHealthCategoryName());
                        gspUpkeepCheckVO.setItemHealthApprovalNbr(baseMtlItemHealth.getItemHealthApprovalNbr());
                        gspUpkeepCheckVO.setItemHealthListedLicensor(baseMtlItemHealth.getItemHealthListedLicensor());
                        gspUpkeepCheckVO.setItemHealthApprovalNbr(baseMtlItemHealth.getItemHealthApprovalNbr());
                        gspUpkeepCheckVO.setItemHealthRegisterNbr(baseMtlItemHealth.getItemHealthRegisterNbr());

                    }
                }
            }
            String cargoOwnerId = gspUpkeepCheckD.getCargoOwnerId();
            if (cargoOwnerResult != null && cargoOwnerResult.getData() != null && cargoOwnerResult.getData().get(cargoOwnerId) != null) {
                gspUpkeepCheckVO.setCargoOwnerName(cargoOwnerResult.getData().get(cargoOwnerId).getCargoOwnerName());
            }
            listRet.add(gspUpkeepCheckVO);
        }
        return listRet;
    }

    @Override
    public List<GspUpkeepCheckVO> findUpkeepItem4MovePick(String id) {
        Criteria crtD = Criteria.forClass(GspUpkeepCheck.class);
        Restriction r11 = Restrictions.eq("planId", id);
        Restriction r22 = Restrictions.in("conclusion", new String[]{"2","3"});//不合格,退货库
        crtD.setOrder(Order.newInstance().asc("gmtCreate"));
        crtD.setRestriction(Restrictions.and(r11, r22));
        List<GspUpkeepCheck> list = mapper.findByCriteria(crtD);
        List<GspUpkeepCheckVO> gspUpkeepCheckVOS = spellGspUpkeepCheckVOS1(list);
        String[] batchIds = list.stream().map(GspUpkeepCheck::getBatchId).distinct().toArray(String[]::new);
        RestMessage<List<BatchNumberListVO>> upKeepDictResult = inventoryClient.getBatchNumberBasicInfo(batchIds);
        for (int i = 0; i < gspUpkeepCheckVOS.size(); i++) {
            GspUpkeepCheckVO gspUpkeepCheckVO = gspUpkeepCheckVOS.get(i);
            gspUpkeepCheckVO.setGspBillId(gspUpkeepCheckVO.getPlanId());
            gspUpkeepCheckVO.setGspBillNo(gspUpkeepCheckVO.getPlanCode());
            gspUpkeepCheckVO.setGspLineId(gspUpkeepCheckVO.getId());
            if (upKeepDictResult != null && upKeepDictResult.isSuccess() && upKeepDictResult.getData() != null) {
                List<BatchNumberListVO> data = upKeepDictResult.getData();
                for (int j = 0; j < data.size(); j++) {
                    BatchNumberListVO batchNumberListVO = data.get(j);
                    if (batchNumberListVO.getBatchId().equals(gspUpkeepCheckVO.getBatchId())) {
                        gspUpkeepCheckVO.setProductionDate(batchNumberListVO.getBatchProductionDate());
                        gspUpkeepCheckVO.setExpiredDate(batchNumberListVO.getBatchExpiredDate());
                        gspUpkeepCheckVO.setShowProductionDate(batchNumberListVO.getBatchProductionDateShow());
                        gspUpkeepCheckVO.setShowExpiredDate(batchNumberListVO.getBatchExpiredDateShow());
                    }
                }
            }
            BigDecimal[] bigDecimals = new BigDecimal(gspUpkeepCheckVO.getPendingQty()).divideAndRemainder(gspUpkeepCheckVO.getCaseConversionRate());
            gspUpkeepCheckVO.setCaseQuantity(bigDecimals[0]);
            gspUpkeepCheckVO.setOddPieceQuantity(bigDecimals[1]);
            if(gspUpkeepCheckVO.getConclusion().equals("3")){
                gspUpkeepCheckVO.setInWhAreaCategory("THK");
                gspUpkeepCheckVO.setInWhAreaCategoryName("退货库");
                gspUpkeepCheckVO.setInStockStatus("4");
                gspUpkeepCheckVO.setOutStockStatus("1");
                gspUpkeepCheckVO.setOutLocatorId(gspUpkeepCheckVO.getLocatorId());
                gspUpkeepCheckVO.setOutLocatorName(gspUpkeepCheckVO.getLocatorName());
            }else if(gspUpkeepCheckVO.getConclusion().equals("2")){
                gspUpkeepCheckVO.setInWhAreaCategory("NHK");
                gspUpkeepCheckVO.setInWhAreaCategoryName("不合格库");
                gspUpkeepCheckVO.setInStockStatus("2");
                gspUpkeepCheckVO.setOutStockStatus("1");
                gspUpkeepCheckVO.setOutLocatorId(gspUpkeepCheckVO.getLocatorId());
                gspUpkeepCheckVO.setOutLocatorName(gspUpkeepCheckVO.getLocatorName());
            }else {
                throw new BizException("当前复核状态为合格，不可移库！");
            }

        }
        return gspUpkeepCheckVOS;
    }

    public List<GspUpkeepCheckVO> spellGspUpkeepCheckVOS1(List<GspUpkeepCheck> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        String[] itemIds = list.stream().map(GspUpkeepCheck::getItemId).distinct().toArray(String[]::new);
        //请求商品信息
        RestMessage<List<BaseMtlItemMst>> itemResult = itemClient.getListByIds(itemIds);
        //组合id
        String[] locatorIds = list.stream().map(GspUpkeepCheck::getLocatorId).distinct().toArray(String[]::new);
        //请求仓库信息，超长已经设置长度
        RestMessage<List<WarehouseLocatorBasicInfo>> warehouseResult = warehouseClient.getLocationBasicInfos(locatorIds);
        //组合id,转换并组装
        String[] cargoOwnerIds = list.stream().map(GspUpkeepCheck::getCargoOwnerId).distinct().toArray(String[]::new);
        //请求货位信息
        RestMessage<Map<String, BaseCargoOwnerMst>> cargoOwnerResult = chainClient.getCargoOwnerMstByIds(cargoOwnerIds);
        List<GspUpkeepCheckVO> listRet = new ArrayList<>();
        for (GspUpkeepCheck gspUpkeepCheckD : list) {
            GspUpkeepCheckVO gspUpkeepCheckVO = new GspUpkeepCheckVO();
            BeanUtils.copyProperties(gspUpkeepCheckD, gspUpkeepCheckVO);
            gspUpkeepCheckVO.setOutContainerCode(gspUpkeepCheckD.getContainerCode());
            if (StrUtil.isNotBlank(gspUpkeepCheckD.getLocationNo())){
                gspUpkeepCheckVO.setOutContainerCode(gspUpkeepCheckD.getLocationNo());
                gspUpkeepCheckVO.setOutGoodsCaseCode(gspUpkeepCheckD.getLocationNo());
            }
            gspUpkeepCheckVO.setConclusion(gspUpkeepCheckD.getConclusion().toString());
            gspUpkeepCheckVO.setUpkeepConclusion(gspUpkeepCheckD.getUpkeepConclusion().toString());
            if(gspUpkeepCheckD.getCheckConclusion()!=null){
                gspUpkeepCheckVO.setCheckConclusion(gspUpkeepCheckD.getCheckConclusion().toString());
            }
            if(gspUpkeepCheckD.getRecheckConclusion()!=null){
                gspUpkeepCheckVO.setRecheckConclusion(gspUpkeepCheckD.getRecheckConclusion().toString());
            }
//            gspUpkeepCheckVO.setInContainerCode(gspUpkeepCheckD.getContainerCode());
            gspUpkeepCheckVO.setPendingQty(gspUpkeepCheckD.getPendingQty().toString());
            List<BaseMtlItemMst> resultData = itemResult.getData();
            if (itemResult.isSuccess() && resultData != null) {
                if (CollUtil.isNotEmpty(warehouseResult.getData())) {
                    Optional<WarehouseLocatorBasicInfo> optional = warehouseResult.getData().stream().filter(y -> y.getWarehouseLocatorId().equals(gspUpkeepCheckD.getLocatorId())).findFirst();
                    if (optional.isPresent()) {
                        WarehouseLocatorBasicInfo locatorBasicInfo = optional.get();
                        gspUpkeepCheckVO.setWarehouseName(locatorBasicInfo.getWarehouseName());
                        gspUpkeepCheckVO.setLocatorName(locatorBasicInfo.getWarehouseLocatorName());
                        gspUpkeepCheckVO.setWhWarehouseLocatorType(locatorBasicInfo.getWarehouseLocatorType());
                        gspUpkeepCheckVO.setBldgName(locatorBasicInfo.getBldgName());
                        gspUpkeepCheckVO.setOutWhAreaCategory(locatorBasicInfo.getWarehouseAreaCategory());
                        gspUpkeepCheckVO.setOutWhAreaCategoryName(locatorBasicInfo.getWarehouseAreaCategoryName());
                        gspUpkeepCheckVO.setWarehouseRoomName(locatorBasicInfo.getWarehouseRoomName());
                        gspUpkeepCheckVO.setWarehouseAreaCategory(locatorBasicInfo.getWarehouseAreaCategory());
                        gspUpkeepCheckVO.setWarehouseAreaName(locatorBasicInfo.getWarehouseAreaName());
                    }
                }
                BaseMtlItemMst itemBaseInfoVO = resultData.stream().filter(item -> item.getItemId().equals(gspUpkeepCheckD.getItemId())).findFirst().orElse(null);
                if (itemBaseInfoVO != null) {
                    gspUpkeepCheckVO.setItemName(itemBaseInfoVO.getItemName());
                    gspUpkeepCheckVO.setManufacturerName(itemBaseInfoVO.getManufacturerId());
                    gspUpkeepCheckVO.setSpecification(itemBaseInfoVO.getSpecification());
                    gspUpkeepCheckVO.setCaseUom(itemBaseInfoVO.getCaseUom());
                    gspUpkeepCheckVO.setCaseConversionRate(itemBaseInfoVO.getCaseConversionRate());
                    gspUpkeepCheckVO.setCountryOriginName(itemBaseInfoVO.getCountryOriginId());
                    String upkeepQty = gspUpkeepCheckVO.getUpkeepQty();
                    String pendingQty = gspUpkeepCheckVO.getPendingQty();
                    if ("0".equals(gspUpkeepCheckVO.getWhWarehouseLocatorType())) {
                        if(StringUtils.isEmpty(pendingQty)){
                            gspUpkeepCheckVO.setCaseQuantity(new BigDecimal(upkeepQty).divide(itemBaseInfoVO.getCaseConversionRate(), RoundingMode.HALF_UP));
                            gspUpkeepCheckVO.setOddPieceQuantity(BigDecimal.ZERO);
                            gspUpkeepCheckVO.setQuantity(new BigDecimal(upkeepQty));
                        }else{
                            gspUpkeepCheckVO.setCaseQuantity(new BigDecimal(pendingQty).divide(itemBaseInfoVO.getCaseConversionRate(), RoundingMode.HALF_UP));
                            gspUpkeepCheckVO.setOddPieceQuantity(BigDecimal.ZERO);
                            gspUpkeepCheckVO.setUpkeepQty(pendingQty);
                            gspUpkeepCheckVO.setQuantity(new BigDecimal(pendingQty));
                        }
                    } else {
                        gspUpkeepCheckVO.setCaseQuantity(BigDecimal.ZERO);
                        if (!StringUtils.isBlank(upkeepQty)) {
                            gspUpkeepCheckVO.setOddPieceQuantity(new BigDecimal(upkeepQty));
                            gspUpkeepCheckVO.setQuantity(new BigDecimal(upkeepQty));
                        }
                        if (!StringUtils.isBlank(pendingQty)) {
                            gspUpkeepCheckVO.setOddPieceQuantity(new BigDecimal(pendingQty));
                            gspUpkeepCheckVO.setUpkeepQty(pendingQty);
                            gspUpkeepCheckVO.setQuantity(new BigDecimal(pendingQty));
                        }
                    }
                    BaseMtlItemHealth baseMtlItemHealth = itemBaseInfoVO.getBaseMtlItemHealth();
                    if (baseMtlItemHealth != null) {
                        gspUpkeepCheckVO.setItemHealthCategoryName(baseMtlItemHealth.getItemHealthCategoryName());
                        gspUpkeepCheckVO.setItemHealthApprovalNbr(baseMtlItemHealth.getItemHealthApprovalNbr());
                        gspUpkeepCheckVO.setItemHealthListedLicensor(baseMtlItemHealth.getItemHealthListedLicensor());
                        gspUpkeepCheckVO.setItemHealthApprovalNbr(baseMtlItemHealth.getItemHealthApprovalNbr());
                        gspUpkeepCheckVO.setItemHealthRegisterNbr(baseMtlItemHealth.getItemHealthRegisterNbr());
                    }
                }
            }
            String cargoOwnerId = gspUpkeepCheckD.getCargoOwnerId();
            if (cargoOwnerResult != null && cargoOwnerResult.getData() != null && cargoOwnerResult.getData().get(cargoOwnerId) != null) {
                gspUpkeepCheckVO.setCargoOwnerName(cargoOwnerResult.getData().get(cargoOwnerId).getCargoOwnerName());
            }
            listRet.add(gspUpkeepCheckVO);
        }
        return listRet;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @TxTransaction(isStart = true)
    public String[] batchEdit(List<GspUpkeepCheck> gspUpkeepCheckList, boolean isCheck) {
        String[] ids = gspUpkeepCheckList.stream().map(GspUpkeepCheck::getId).toArray(String[]::new);
        Assert.notEmpty(ids, "主键ID不能为空");
        List<GspUpkeepCheck> checks = mapper.findByIds(GspUpkeepCheck.class, ids, null);
        Assert.notEmpty(checks, "获取数据失败，请刷新页面");
        Map<String, List<GspUpkeepCheck>> checksMap = checks.stream().collect(Collectors.groupingBy(GspUpkeepCheck::getId));
        Map<String, List<GspUpkeepCheck>> paramMap = gspUpkeepCheckList.stream().collect(Collectors.groupingBy(GspUpkeepCheck::getId));
        // 数据填充
        dataFilling(gspUpkeepCheckList, checks, paramMap, checksMap);
        UserDTO userDTO = userTemplate.getUserDTO();
        String userId = "EIS";
        String userName = "EIS";
        if (null != userDTO){
            userId = userDTO.getId();
            userName = userDTO.getNickname();
        }
        Date date = new Date();
//        List<GspUpkeepCheck> toOMSList = new ArrayList<>();
        List<GspUpkeepCheck> lockList = new ArrayList<>();
        List<GspUpkeepCheck> cancelLockList = new ArrayList<>();
        List<GspUpkeepCheck> toEisList = new ArrayList<>();
        //查询货位信息，得到库别 库区
        String[] locatorIdList = gspUpkeepCheckList.stream().map(GspUpkeepCheck::getLocatorId).toArray(String[]::new);
        RestMessage<List<WarehouseLocatorBasicInfo>> locationBasicInfos = warehouseClient.getLocationBasicInfos(locatorIdList);
        if (!locationBasicInfos.isSuccess() || locationBasicInfos.getData() == null) {
            throw new BizException("查询货位关联信息失败!请重试或联系管理员!");
        }
        List<WarehouseLocatorBasicInfo>  warehouselocators = locationBasicInfos.getData();
        // 校验托盘是否出库    MJK,AGVZ 支持不发送设备指令
        checkIsConclusioned(checks, warehouselocators);
        for (int i = 0; i < gspUpkeepCheckList.size(); i++) {
            GspUpkeepCheck gspUpkeepCheck = gspUpkeepCheckList.get(i);
            if (ObjectUtil.isEmpty(gspUpkeepCheck.getEnterpriseId())) gspUpkeepCheck.setEnterpriseId(userDTO.getEnterpriseId());
            GspUpkeepCheck gspData = checks.stream().filter(check -> check.getId().equals(gspUpkeepCheck.getId())).findFirst().orElse(null);
            if (null == gspData) {
                throw new BizException("根据ID【" + gspUpkeepCheck.getId() + "】没有查询到养护记录!");
            }
            gspUpkeepCheck.setOutboundInstruct(gspData.getOutboundInstruct());

            String stockQty = gspUpkeepCheck.getStockQty();
            String upkeepQty = gspUpkeepCheck.getUpkeepQty();
            if ((StringUtils.isBlank(stockQty) || StringUtils.isBlank(upkeepQty)) || (new BigDecimal(stockQty)).compareTo(new BigDecimal(upkeepQty)) < 0) {
                throw new BizException("养护数量不能大于库存数量：第" + (i + 1) + "行");
            }
            gspUpkeepCheck.setModifier(userId);
            gspUpkeepCheck.setModifierName(userName);
            gspUpkeepCheck.setGmtModified(date);
            if (!isCheck) {
                Integer upkeepConclusion = gspUpkeepCheck.getUpkeepConclusion();
                if (upkeepConclusion != null) {
                    if (0 == upkeepConclusion) {
                        if(gspUpkeepCheck.getPendingQty()==null||gspUpkeepCheck.getPendingQty().compareTo(BigDecimal.ZERO)==0){
                            throw new BizException("养护结论待处理，待处理数量不能为0");
                        }
                        gspUpkeepCheck.setStatus("4");
                    } else {
                        if(gspUpkeepCheck.getPendingQty()==null||gspUpkeepCheck.getPendingQty().compareTo(BigDecimal.ZERO)>0){
                            throw new BizException("养护结论合格，待处理数量不能大于0");
                        }
                        gspUpkeepCheck.setConclusion(upkeepConclusion);
                        gspUpkeepCheck.setStatus("1");
//                        toOMSList.add(gspUpkeepCheck);
                    }
                    if (1 != upkeepConclusion) {
                        lockList.add(gspUpkeepCheck);
                    }
                    gspUpkeepCheck.setUpkeepOperator(userName);
                    gspUpkeepCheck.setUpkeepDate(date);
                }
            } else {
                //审核状态：0初始，1-正常无需质检，2-质检，3-质检无需复检，4-复检，5-复检完成，6-复检不合格待移库，7-发起移库完成，B -库存状态ERP审核驳回
                Integer checkConclusion = gspUpkeepCheck.getCheckConclusion();
                Integer recheckConclusion = gspUpkeepCheck.getRecheckConclusion();

                if (recheckConclusion == null) {// 判断是否复检
                    if ( null == checkConclusion || 0 == checkConclusion) {
                        gspUpkeepCheck.setStatus("4");
                    } else {
                        gspUpkeepCheck.setStatus("4");
                        gspUpkeepCheck.setConclusion(checkConclusion);
//                        toOMSList.add(gspUpkeepCheck);
                    }
                    gspUpkeepCheck.setCheckOperator(userName);
                    gspUpkeepCheck.setCheckDate(date);

                } else {
                    gspUpkeepCheck.setStatus("5");
                    gspUpkeepCheck.setConclusion(recheckConclusion);
//                    toOMSList.add(gspUpkeepCheck);
                    gspUpkeepCheck.setRecheckOperator(userName);
                    gspUpkeepCheck.setRecheckDate(date);
                }
                if ((recheckConclusion != null&& 1 == recheckConclusion) || (checkConclusion != null && 1 == checkConclusion)) {
                    cancelLockList.add(gspUpkeepCheck);
                }
            }
            boolean isAdd = false;
            for (int j = 0; j < i; j++) {
                GspUpkeepCheck gspUpkeepCheckDTOJ = gspUpkeepCheckList.get(j);
                if (gspUpkeepCheckDTOJ.getId().equals(gspUpkeepCheck.getId())) {//同ID,则为拆分数据
                    String id = String.valueOf(SnowFlakeUtils.getId());
                    gspUpkeepCheck.setId(id);
                    gspUpkeepCheck.setCode("YH" + id.substring(id.length() - 8));
                    this.mapper.save(gspUpkeepCheck);
                    isAdd = true;
                }
            }
            if (!isAdd) {
                this.mapper.updateWithValidate(gspUpkeepCheck, p -> ObjectUtils.isNotNull(p) && ObjectUtils.isNotNull(p.getValue()));
            }
            WarehouseLocatorBasicInfo basicInfo = warehouselocators.stream().filter(var -> gspUpkeepCheck.getLocatorId().equals(var.getWarehouseLocatorId())).findFirst().orElse(null);
            if (null != basicInfo
                    && (basicInfo.getWarehouseAreaCategory().equals("AGVZ") || basicInfo.getWarehouseAreaCategory().equals("MJK")
                    || basicInfo.getWarehouseAreaCategory().equals("AGVSP") || basicInfo.getWarehouseAreaCategory().equals("AGVQX")
                    || basicInfo.getWarehouseAreaCategory().equals("AGVZY"))
                    && (gspUpkeepCheck.getStatus().equals("4") || gspUpkeepCheck.getStatus().equals("1"))
            ) {
                // 生成出库指令且托盘到位的 才需要回告 EIS 托盘回库
                if (OUTBOUND_INSTRUCT_DELIVERY.equals(gspUpkeepCheck.getOutboundInstruct())) {
                    //养护完成， 回告EIS托盘回库 MJK和AGVL内部盘点不出库
                    toEisList.add(gspUpkeepCheck);
                }
            }
        }
        if (lockList.size() > 0) {
            ValidList<InvStockMaintain> invStockList = new ValidList<>();
            for (int i = 0; i < lockList.size(); i++) {
                GspUpkeepCheck gspUpkeepCheck = lockList.get(i);
                InvStockMaintain invStockMaintain = spellInvStockVO(gspUpkeepCheck);
                invStockList.add(invStockMaintain);
            }

            logger.info("maintainStock:{}", JSON.toJSONString(invStockList));
            RestMessage upKeepDictResult = inventoryClient.maintainStock(invStockList);
            if (upKeepDictResult == null || !upKeepDictResult.isSuccess()) {
                throw new PrologException("调用库存：" + upKeepDictResult.getMessage());
            }
        }
        if (CollUtil.isNotEmpty(toEisList)){
            this.workFinish(toEisList);
        }
        if (cancelLockList.size() > 0) {
            String[] cancelIds = cancelLockList.stream().map(GspUpkeepCheck::getId).toArray(String[]::new);
            InvStockCancel invStockCancel = new InvStockCancel();
            invStockCancel.setLineBillIds(cancelIds);
            RestMessage upKeepDictResult = inventoryClient.maintainCancel(invStockCancel);
            if (upKeepDictResult == null || !upKeepDictResult.isSuccess()) {
                throw new PrologException("调用库存：" + upKeepDictResult.getMessage());
            }
            // 迁移到设备养护结果的定时任务去同步
            //            askIntegration(updateDeviceOkId, cancelLockList);
        }
//        ifHasDeviceThenHandleThem(gspUpkeepCheckList, warehouselocators);
//        if (toOMSList.size() > 0) {
//            dxiOmsMaintenanceRecordMapper.saveBatch(spellDxi(toOMSList));
//            return toOMSList.stream().map(GspUpkeepCheck::getId).toArray(String[]::new);
//        }
        return null;
    }

    private void dataFilling(List<GspUpkeepCheck> gspUpkeepCheckList, List<GspUpkeepCheck> checks, Map<String, List<GspUpkeepCheck>> paramMap, Map<String, List<GspUpkeepCheck>> checksMap) {
        for (GspUpkeepCheck check : checks) {
            if (paramMap.containsKey(check.getId())) {
                check.setOutWhAreaCategory(paramMap.get(check.getId()).get(0).getOutWhAreaCategory());
            }
        }
        for (GspUpkeepCheck gspUpkeepCheck : gspUpkeepCheckList) {
            if (checksMap.containsKey(gspUpkeepCheck.getId())) {
                gspUpkeepCheck.setOutboundInstruct(checksMap.get(gspUpkeepCheck.getId()).get(0).getOutboundInstruct());
            }
        }
    }

    private void workFinish(List<GspUpkeepCheck> toEisList){
        //通知托盘回库
        String[] locationIds = toEisList.stream().map(GspUpkeepCheck::getLocatorId).distinct().toArray(String[]::new);
        List<WarehouseLocatorBasicInfo> locations = RestMsgHelper.unpack(warehouseClient.getLocationBasicInfos(locationIds));
        Assert.notEmpty(locations, "获取货位信息失败");
        List<GspUpkeepCheck> needBackList = new ArrayList<>();
        //只有AGV托盘库/四向库才需要回告作业完成(发送过设备指令的才需要回告作业完成)
        for (GspUpkeepCheck gspUpkeepCheck : toEisList) {
            GspUpkeepCheck byId = mapper.findById(gspUpkeepCheck.getId(), GspUpkeepCheck.class);
            if(byId.getOutboundInstruct()!=null){
                gspUpkeepCheck.setOutboundInstruct(byId.getOutboundInstruct());
            }
            WarehouseLocatorBasicInfo location = locations.stream().filter(x -> x.getWarehouseLocatorId().equals(gspUpkeepCheck.getLocatorId())).findFirst().orElse(null);
            if(location!=null){
                if(gspUpkeepCheck.getOutboundInstruct() != null && gspUpkeepCheck.getOutboundInstruct() != 0
                        && (location.getWarehouseAreaCategory().equals("AGVZ") || location.getWarehouseAreaCategory().equals("MJK")
                        || location.getWarehouseAreaCategory().equals("AGVSP") || location.getWarehouseAreaCategory().equals("AGVQX")
                        || location.getWarehouseAreaCategory().equals("AGVZY"))){
                    needBackList.add(gspUpkeepCheck);
                }
            }
//            for (WarehouseLocatorBasicInfo location : locations) {
//                if (gspUpkeepCheck.getLocatorId().equals(location.getWarehouseLocatorId())
//                        && (location.getWarehouseAreaCategory().equals("AGVZ") || location.getWarehouseAreaCategory().equals("MJK"))
//                ){
//                    needBackList.add(gspUpkeepCheck);
//                }
//            }
        }
        if (CollUtil.isEmpty(needBackList)){
            return;
        }
        List<BaseMtlItemMst> items = RestMsgHelper.unpack(itemClient.getListByIds(toEisList.stream().map(GspUpkeepCheck::getItemId).collect(Collectors.toSet()).toArray(new String[]{})));
        if (CollUtil.isEmpty(items)){
            throw new BizException("商品信息不存在！");
        }
        //通过托盘分组
        Map<String, List<GspUpkeepCheck>> containerGroup = needBackList.stream().collect(Collectors.groupingBy(GspUpkeepCheck::getContainerCode));

        List<OperationCompleteVO> list = new ArrayList<>();
        for (String containerCode : containerGroup.keySet()) {
            OperationCompleteVO operationCompleteVO = new OperationCompleteVO();
            operationCompleteVO.setMsgId(IdUtil.fastSimpleUUID());
            operationCompleteVO.setContainerNo(containerCode);
            List<OperationCompleteItemVO> subList = new ArrayList<>();
            //for (GspUpkeepCheck gspUpkeepCheck : containerGroup.get(containerCode)) {
                GspUpkeepCheck gspUpkeepCheck = containerGroup.get(containerCode).get(0);
                BaseMtlItemMst itemMst = items.stream().filter(var->gspUpkeepCheck.getItemId().equals(var.getItemId())).findFirst().orElse(null);
                WarehouseLocatorBasicInfo locator = locations.stream().filter(var->var.getWarehouseLocatorId().equals(gspUpkeepCheck.getLocatorId())).findFirst().orElse(null);
                if (null == itemMst){
                    throw new BizException("商品信息不存在！");
                }
                if (null == locator){
                    throw new BizException("查询货位信息失败！");
                }
                OperationCompleteItemVO operationCompleteItemVO = new OperationCompleteItemVO();
                operationCompleteItemVO.setTaskId(gspUpkeepCheck.getPlanId());
                operationCompleteItemVO.setItemId(gspUpkeepCheck.getItemId());
                operationCompleteItemVO.setEnterpriseId(gspUpkeepCheck.getEnterpriseId());
                operationCompleteItemVO.setWarehouseId(gspUpkeepCheck.getWarehouseId());
                operationCompleteItemVO.setWorkType(OutBoundRequestEnum.INV_CONSERVE.getWorkType());
                operationCompleteItemVO.setBusinessType(OutBoundRequestEnum.INV_CONSERVE.getBusinessType());
                operationCompleteItemVO.setTaskLineId(gspUpkeepCheck.getId());
                operationCompleteItemVO.setOwnerId(gspUpkeepCheck.getCargoOwnerId());
//                List<BaseWmsWarehouseArea> area = RestMsgHelper.unpack(warehouseClient.getWarehouseAreaBasicInfos(new String[]{locator.getWarehouseAreaId()}));
                operationCompleteItemVO.setWmsLocationCode("MJK".equals(locator.getWarehouseAreaCode()) ? "MJZ" : locator.getWarehouseAreaCode());
                operationCompleteItemVO.setQty(gspUpkeepCheck.getPlanStockQty());
                operationCompleteItemVO.setBillNo(gspUpkeepCheck.getPlanId());
                subList.add(operationCompleteItemVO);
//            }
            operationCompleteVO.setSubList(subList);
            list.add(operationCompleteVO);
        }
        eisHandler.operationComplete(list);
    }

    private void checkIsConclusioned(List<GspUpkeepCheck> checks, List<WarehouseLocatorBasicInfo> locations) {
        //状态：0初始，1-正常无需质检，2-质检，3-质检无需复检，4-复检，5-复检完成，6-发起移库完成
       for (GspUpkeepCheck check : checks) {
            if (check.getUpkeepConclusion() > 0){
                if (check.getStatus() != null){
                    if (check.getStatus().equals("1")){
                        throw new BizException("当前养护记录已被养护，请刷新记录");
                    }
                    if (check.getStatus().equals("3")){
                        throw new BizException("当前养护记录已质检完成，请刷新记录");
                    }
                    if (check.getStatus().equals("5")){
                        throw new BizException("当前养护记录已复检，请刷新记录");
                    }
                    if (check.getStatus().equals("6")){
                        throw new BizException("当前养护记录已移库完成，请刷新记录");
                    }
                }
            }
        }

        // 拣货方式 设备且非货架库
        List<String> locatorIds = locations.stream().filter(t -> PICK_MODE_DEVICE.equals(t.getPickMode())).map(WarehouseLocatorBasicInfo::getWarehouseLocatorId).collect(Collectors.toList());

        List<GspUpkeepCheck> areaNoSend = checks.stream().filter(d -> "MJK".equals(d.getOutWhAreaCategory())
                        || "AGVZ".equals(d.getOutWhAreaCategory())
                || "AGVSP".equals(d.getOutWhAreaCategory())
                || "AGVQX".equals(d.getOutWhAreaCategory()))
                .filter(d -> OUTBOUND_INSTRUCT_NO_SEND.equals(d.getOutboundInstruct()) || ObjectUtil.isNull(d.getOutboundInstruct())).collect(Collectors.toList());
        //List<GspUpkeepCheck> areaNoSend = checks.stream().filter(d -> "MJK".equals(d.getOutWhAreaCategory()) || "AGVZ".equals(d.getOutWhAreaCategory())).filter(d -> OUTBOUND_INSTRUCT_NO_SEND.equals(d.getOutboundInstruct()) || ObjectUtil.isNull(d.getOutboundInstruct())).collect(Collectors.toList());
        if (Objects.equals(areaNoSend.size(), checks.size())) {
            return;
        }
        GspUpkeepCheck unSendCheckD = checks.stream().filter(d -> locatorIds.contains(d.getLocatorId()) && !OUTBOUND_INSTRUCT_DELIVERY.equals(d.getOutboundInstruct())).findFirst().orElse(null);
        if (unSendCheckD != null) {
            throw new PrologException(String.format("托盘号【%s】未出库不能养护录入操作", unSendCheckD.getContainerCode()));
        }
    }

    private void ifHasDeviceThenHandleThem(List<GspUpkeepCheck> list, List<WarehouseLocatorBasicInfo> locations) {
        String[] itemIds = list.stream().map(GspUpkeepCheck::getItemId).toArray(String[]::new);
        List<BaseMtlItemMst> itemList = RestMsgHelper.unpack(itemClient.getListByIds(itemIds));
        Assert.notEmpty(itemList, "获取商品信息失败");
        List<GspUpkeepCheck> deviceList = list.stream().filter(d -> StrUtil.isNotBlank(d.getContainerCode()) && isDevice(d.getLocatorId(), locations)).collect(Collectors.toList());
        if (CollUtil.isEmpty(deviceList)) {
            return;
        }
        Map<String, List<GspUpkeepCheck>> collect = deviceList.stream().collect(Collectors.groupingBy(GspUpkeepCheck::getContainerCode));
        for (String containerCode : collect.keySet()) {
            if (CollUtil.isEmpty(collect.get(containerCode))){
                continue;
            }
            ContainerConfirmDto vo = generateTaskFinishedConfirmSubListVO(containerCode,collect.get(containerCode),itemList,locations);
            logger.info("- taskFinishedConfirm.params:{}", JSONObject.toJSONString(vo));
            eisResource.taskFinishedConfirm(vo);
        }
    }

    private boolean isDevice(String locationId, List<WarehouseLocatorBasicInfo> locations) {
        return locations.stream().anyMatch(l -> l.getWarehouseLocatorId().equals(locationId) && PICK_MODE_DEVICE.equals(l.getPickMode()));
    }

    private ContainerConfirmDto generateTaskFinishedConfirmSubListVO(
            String containerCode,
            List<GspUpkeepCheck> dList,
            List<BaseMtlItemMst> items,
            List<WarehouseLocatorBasicInfo> locators
    ) {
        ContainerConfirmDto vo = new ContainerConfirmDto();
        vo.setContainerNo(containerCode);
        vo.setContainerType("3");

        List<EisConfirmSubVo> confirmVOS = new ArrayList<>();
        for (GspUpkeepCheck gspUpkeepCheck : dList) {
            BaseMtlItemMst itemMst = items.stream().filter(var->gspUpkeepCheck.getItemId().equals(var.getItemId())).findFirst().orElse(null);
            WarehouseLocatorBasicInfo locator = locators.stream().filter(var->var.getWarehouseLocatorId().equals(gspUpkeepCheck.getLocatorId())).findFirst().orElse(null);
            if (null == itemMst){
                throw new BizException("商品信息不存在！");
            }
            if (null == locator){
                throw new BizException("查询货位信息失败！");
            }
            EisConfirmSubVo subVo = new EisConfirmSubVo();
            subVo.setMsgId(IdUtil.fastSimpleUUID());
            subVo.setTaskId(gspUpkeepCheck.getPlanId());
            subVo.setSeqNo(gspUpkeepCheck.getId());
            subVo.setBusinessType("40");
            subVo.setWorkType("40");
            subVo.setItemId(gspUpkeepCheck.getItemId());
            subVo.setLotId(gspUpkeepCheck.getBatchId());
            subVo.setOwnerId(gspUpkeepCheck.getCargoOwnerId());
            String packId = "";
            if (CollUtil.isNotEmpty(itemMst.getBaseMtlItemUomConversionsList())){
                packId = itemMst.getBaseMtlItemUomConversionsList().get(0).getItemUomId();
            }
            subVo.setPackId(packId);
            subVo.setWarehouseId("JXYJ");
            subVo.setWmslocationCode(locator.getWarehouseLocatorCode());
            subVo.setInventoryQty(new BigDecimal(gspUpkeepCheck.getStockQty()));
            subVo.setCountQty(new BigDecimal(gspUpkeepCheck.getUpkeepQty()));
            confirmVOS.add(subVo);
        }
        vo.setSubList(confirmVOS);
        return vo;
    }


    private InvStockMaintain spellInvStockVO(GspUpkeepCheck gspUpkeepCheck) {
        InvStockMaintain invStockMaintain = new InvStockMaintain();
        invStockMaintain.setBillId(gspUpkeepCheck.getPlanId());
        invStockMaintain.setLineBillId(gspUpkeepCheck.getId());
        invStockMaintain.setWarehouseId(gspUpkeepCheck.getWarehouseId());
        InvStockMaintainDetail invStockMaintainDetail = new InvStockMaintainDetail();
        invStockMaintainDetail.setBatchId(gspUpkeepCheck.getBatchId());
        invStockMaintainDetail.setLocatorId(gspUpkeepCheck.getLocatorId());
        invStockMaintainDetail.setQuantity(new BigDecimal(gspUpkeepCheck.getUpkeepQty()));
        if(gspUpkeepCheck.getPendingQty()!=null&&gspUpkeepCheck.getPendingQty().compareTo(BigDecimal.ZERO)>0){
            invStockMaintainDetail.setQuantity(gspUpkeepCheck.getPendingQty());
        }
        invStockMaintain.setDetails(new ArrayList<InvStockMaintainDetail>() {{
            add(invStockMaintainDetail);
        }});
        return invStockMaintain;
    }

    @Override
    public void confirmDevice() {//0=初始化 1=正在作业 2=养护完成 3=养护WMS已接收 4=复检合格 5=复检不合格
        try {
            JSONObject JSONObject = askIntegration(sendWmsId, null);
            List<GspUpkeepCheck> list = JSON.parseArray(JSON.toJSONString(JSONObject.getJSONArray("data")), GspUpkeepCheck.class);
            logger.info("设备养护数据:" + JSON.toJSONString(JSONObject.getJSONArray("data")));
            if (list != null && list.size() > 0) {
                List<GspUpkeepCheck> checkList = new ArrayList<>();
                List<GspUpkeepCheck> wmsList = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    GspUpkeepCheck GspUpkeepCheck = list.get(i);
                    // 当前的status是设备表的状态，提取出来后需要设置为 null
                    String status = GspUpkeepCheck.getStatus();
                    GspUpkeepCheck.setStatus(null);
                    if (GspUpkeepCheck != null) {
                        // wms回传agv已接收
                        if (status.equals("2")) {
                            // 检查养护结果，设置养护结论(设备养护不会拆分)
                            Integer okNum = StringUtils.isBlank(GspUpkeepCheck.getOkQty()) ? 0 : Integer.valueOf(GspUpkeepCheck.getOkQty());
                            Integer paddingNum = GspUpkeepCheck.getPendingQty() == null ? 0 : GspUpkeepCheck.getPendingQty().intValue();
                            if ((okNum > 0 && paddingNum > 0) || (okNum.equals(0) && paddingNum.equals(0))) {
                                // 同时存在合格和待处理的设备，提示错误
                                throw new PrologException("设备养护同时存在/不存在合格和待处理的设备,养护id:" + GspUpkeepCheck.getId());
                            }

                            if (okNum > 0) {
                                // 合格：合格数量大于 0
                                GspUpkeepCheck.setUpkeepConclusion(1);
                                GspUpkeepCheck.setConclusion(1);
                                GspUpkeepCheck.setStatus("1");
                            } else {
                                // 待处理
                                GspUpkeepCheck.setUpkeepConclusion(0);
                                GspUpkeepCheck.setStatus("4");
                            }

                            this.mapper.updateWithValidate(GspUpkeepCheck, p -> ObjectUtils.isNotNull(p) && ObjectUtils.isNotNull(p.getValue()));
                            wmsList.add(GspUpkeepCheck);
                        } else {
                            // 需要更新agv复检状态的数据
                            checkList.add(GspUpkeepCheck);
                        }
                    }
                }
                // 复检数据处理
                String[] ids = checkList.stream().map(GspUpkeepCheck::getId).distinct().toArray(String[]::new);
                Criteria crtD = Criteria.forClass(GspUpkeepCheck.class);
                Restriction r1 = Restrictions.in("id", ids);
                Restriction r2 = Restrictions.isNotNull("conclusion");
                crtD.setRestriction(Restrictions.and(r1, r2));
                List<GspUpkeepCheck> checkResList = mapper.findByCriteria(crtD);

                // wms已接收数据下传
                if (wmsList.size() > 0) {
                    askIntegration(updateDeviceId, wmsList);
                }
                // 复检数据下传
                if (checkResList.size() > 0) {
                    askIntegration(updateDeviceOkId, checkResList);
                }
            }
        } catch (Exception e) {
            logger.info("设备养护数据", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @TxTransaction(isStart = true)
    public void sendTaskToEis(List<String> ids) {

        List<GspUpkeepCheck> list = mapper.findByIds(GspUpkeepCheck.class, ids.toArray(), null);
        Assert.notEmpty(list, DATA_OVERDUE);

        checkIsRepeatPushTask(list);

        List<WarehouseLocatorBasicInfo> deviceLocList = getDeviceListByUpkeepCheck(list);

        updateOutboundInstruct2DB(list);

        List<BaseMtlItemMst> items = RestMsgHelper.unpack(itemClient.getListByIds(list.stream().map(GspUpkeepCheck::getItemId).collect(Collectors.toSet()).toArray(new String[]{})));

        pushTask2Eis(list, items, deviceLocList);
    }

    @Override
    public Page<RfGspUpkeepCheckVO> findUpkeepPageByRf(QueryDTO dto) {
        QueryDTO queryDTO = initDTO(dto);
        PageUtils.startPage(dto.getPageNum(), dto.getPageSize());
        List<RfGspUpkeepCheckVO> list = mapper.findUpkeepPageByRf(queryDTO);
        if (CollUtil.isEmpty(list)) {
            return PageUtils.getPage(list);
        }

        String[] locationIds = list.stream().map(RfGspUpkeepCheckVO::getLocatorId).distinct().toArray(String[]::new);
        Assert.notEmpty(locationIds, "获取货位ID失败");
        List<WarehouseLocatorBasicInfo> locations = RestMsgHelper.unpack(warehouseClient.getLocationBasicInfos(locationIds));
        Assert.notEmpty(locations, "获取货位信息失败");
        List<RfGspUpkeepCheckVO> resultList = Lists.newArrayList();
        locations.stream().filter(l -> PICK_MODE_DEVICE.equals(l.getPickMode())).forEach(l -> resultList.addAll(getDeviceByLocation(l, list)));
        if (CollUtil.isEmpty(resultList)) {
            return PageUtils.getPage(list);
        }

        String[] cargoOwnerIds = resultList.stream().map(RfGspUpkeepCheckVO::getCargoOwnerId).toArray(String[]::new);
        Map<String, BaseCargoOwnerMst> cargoOwnerMstMap = RestMsgHelper.unpack(chainClient.getCargoOwnerMstByIds(cargoOwnerIds));
        String[] itemIds = resultList.stream().map(RfGspUpkeepCheckVO::getItemId).toArray(String[]::new);
        List<BaseMtlItemMst> items = RestMsgHelper.unpack(itemClient.getListByIds(itemIds));
        Set<String> warehouseIds = resultList.stream().map(RfGspUpkeepCheckVO::getWarehouseId).collect(Collectors.toSet());
        Map<String, BaseWmsWarehouseMst> warehouseMstMap = RestMsgHelper.unpack(warehouseClient.mapbyids(warehouseIds));
        for (RfGspUpkeepCheckVO vo : resultList) {
            Optional.ofNullable(warehouseMstMap).flatMap(t -> Optional.ofNullable(t.get(vo.getWarehouseId()))).ifPresent(t2 -> vo.setWarehouseName(t2.getWarehouseName()));
            Optional.ofNullable(cargoOwnerMstMap).flatMap(t -> Optional.ofNullable(t.get(vo.getCargoOwnerId()))).ifPresent(t2 -> vo.setCargoOwnerName(t2.getCargoOwnerName()));
            items.stream().filter(i -> i.getItemId().equals(vo.getItemId())).findFirst().ifPresent(i -> {
                vo.setItemName(i.getItemName());
                vo.setItemCode(i.getItemCode());
            });
            locations.stream().filter(l -> l.getWarehouseLocatorId().equals(vo.getLocatorId())).findFirst().ifPresent(l -> {
                vo.setWarehouseAreaCategory(l.getWarehouseAreaCategory());
                vo.setLocatorCode(l.getWarehouseLocatorCode());
            });
        }
        return PageUtils.getPage(resultList);
    }

    @Override
    public GspUpkeepCheckVO findUpkeepDtlByRf(QueryDTO dto) {
        initDTO(dto);
        if (StrUtil.isBlank(dto.getId())) {
            throw new PrologException("ID不能为空");
        }
        GspUpkeepCheck check = mapper.findById(dto.getId(), GspUpkeepCheck.class);
        Assert.notNull(check, "获取详情失败");
        List<GspUpkeepCheckVO> list = spellGspUpkeepCheckVOS(Collections.singletonList(check));
        return list.get(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void callbackPushTask(List<String> ids) {
        Assert.notEmpty(ids, "业务ID不能为空");
        mapper.updateOutboundInstructById(ids, DateUtil.date());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void gspUpKeepOutBack(List<InfTaskOutBackDTO> upkeepList) {
        List<GspUpkeepCheck> editList = new ArrayList<>();
        List<GspUpkeepCheck> checkList = new ArrayList<>();
        for (InfTaskOutBackDTO infTaskOutBackVO : upkeepList) {
            GspUpkeepCheck gspUpkeepCheck = mapper.findById(infTaskOutBackVO.getSeqNo(),GspUpkeepCheck.class);
            gspUpkeepCheck.setOutboundInstruct(OUTBOUND_INSTRUCT_DELIVERY);
            mapper.update(gspUpkeepCheck);
            //判断养护的库别 AGVZ/MJK/AGVL
            String locatorId = gspUpkeepCheck.getLocatorId();
            RestMessage<List<WarehouseLocatorBasicInfo>> locationBasicInfos = warehouseClient.getLocationBasicInfos(new String[]{locatorId});
            WarehouseLocatorBasicInfo basicInfo = locationBasicInfos.getData().get(0);
            String warehouseAreaCategory = basicInfo.getWarehouseAreaCategory();
            if (warehouseAreaCategory.equals("AGVZ")){
                //更新状态为EIS出库
            }else if (warehouseAreaCategory.equals("AGVL")){
                //货格回告 需要拆分GspUpkeepCheck，并记录货格号
                if (CollUtil.isEmpty(infTaskOutBackVO.getItemList())){
                    throw new BizException("养护结论不能为空");
                }
                List<GspUpkeepCheck> saveList = new ArrayList<>();
                for (EisCheckBackDetailVo detailVo : infTaskOutBackVO.getItemList()) {
                    //根据结论拆分 gspUpkeepCheck
                    GspUpkeepCheck tempCheck = new GspUpkeepCheck();
                    BeanUtils.copyProperties(gspUpkeepCheck, tempCheck);
                    tempCheck.setLocationNo(detailVo.getLocationNo());
                    tempCheck.setUpkeepQty(detailVo.getInventoryQty().toString());
                    tempCheck.setStockQty(detailVo.getInventoryQty().toString());
                    tempCheck.setId(String.valueOf(SnowFlakeUtils.getId()));
                    saveList.add(tempCheck);
                    GspUpkeepCheck editCheck = new GspUpkeepCheck();
                    BeanUtils.copyProperties(tempCheck, editCheck);
                    editCheck.setUpkeepConclusion(Convert.toInt(detailVo.getYhResult()));
                    editCheck.setUpkeepConclusion(editCheck.getUpkeepConclusion() == 3?0:editCheck.getUpkeepConclusion());
                    if (editCheck.getUpkeepConclusion() != 1){
                        editCheck.setPendingQty(detailVo.getInventoryQty());
                    } else {
                        editCheck.setPendingQty(BigDecimal.ZERO);
                    }
                    editCheck.setCheckFanDuo(StrUtil.isNotBlank(detailVo.getYhItem1()) && Convert.toInt(detailVo.getYhItem1(), 0) == 1);
                    editCheck.setCheckChuShi(StrUtil.isNotBlank(detailVo.getYhItem2()) && Convert.toInt(detailVo.getYhItem2(), 0) == 1);
                    editCheck.setCheckJiaShi(StrUtil.isNotBlank(detailVo.getYhItem3()) && Convert.toInt(detailVo.getYhItem3(), 0) == 1);
                    editCheck.setCheckShenWen(StrUtil.isNotBlank(detailVo.getYhItem4()) && Convert.toInt(detailVo.getYhItem4(), 0) == 1);
                    editCheck.setCheckJiangWen(StrUtil.isNotBlank(detailVo.getYhItem5()) && Convert.toInt(detailVo.getYhItem5(), 0) == 1);
                    editCheck.setCheckTongFeng(StrUtil.isNotBlank(detailVo.getYhItem6()) && Convert.toInt(detailVo.getYhItem6(), 0) == 1);
                    editCheck.setCheckChuChen(StrUtil.isNotBlank(detailVo.getYhItem7()) && Convert.toInt(detailVo.getYhItem7(), 0) == 1);
                    editCheck.setCheckChongZhu(StrUtil.isNotBlank(detailVo.getYhItem9()) && Convert.toInt(detailVo.getYhItem9(), 0) == 1);
                    editCheck.setCheckFaMei(StrUtil.isNotBlank(detailVo.getYhItem10()) && Convert.toInt(detailVo.getYhItem10(), 0) == 1);
                    editCheck.setCheckChaoJie(StrUtil.isNotBlank(detailVo.getYhItem11()) && Convert.toInt(detailVo.getYhItem11(), 0) == 1);
                    editCheck.setCheckZheGuang(StrUtil.isNotBlank(detailVo.getYhItem12()) && Convert.toInt(detailVo.getYhItem12(), 0) == 1);

                    if (editCheck.getUpkeepConclusion() == 2){
                        checkList.add(editCheck);
                    }else {
                        editList.add(editCheck);
                    }
                }
                mapper.saveBatch(saveList);
                mapper.deleteById(gspUpkeepCheck.getId(), GspUpkeepCheck.class);
            }else if (warehouseAreaCategory.equals("MJK")){
                //四向库回告 记录回告信息
            }else {
                throw new BizException("库别错误！");
            }
            if (CollUtil.isNotEmpty(editList)){
                this.batchEdit(editList, false);
            }
            if (CollUtil.isNotEmpty(checkList)){
                this.batchEdit(checkList, true);
            }
        }
    }

    @Override
    public String getLocationNoByLineId(String lineId) {
        GspUpkeepCheck byId = mapper.findById(lineId, GspUpkeepCheck.class);
        if (byId == null){
            return "";
        }
        if (StrUtil.isNotBlank(byId.getLocationNo())){
            return byId.getLocationNo();
        }
        return "";
    }

    @TxTransaction
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addStockUnLock(List<WmsInvStockLot> wmsInvStockLots) {
        logger.info("库存解锁复检不合格转gsp移库=》{}",JSONObject.toJSONString(wmsInvStockLots));
        UserDTO userDTO = this.getUpkeepUser("0");
        String userId = userDTO.getId();
        String userName = userDTO.getNickname();
        Date date = new Date();
        String enterpriseId = userDTO.getEnterpriseId();
        Set<String> locids = new HashSet<>();
        Set<String> itemids = new HashSet<>();
        Set<String> warehouseIds = new HashSet<>();
        for (WmsInvStockLot stockLot : wmsInvStockLots) {
            locids.add(stockLot.getLocatorId());
            itemids.add(stockLot.getItemId());
            warehouseIds.add(stockLot.getWarehouseId());
        }
        Map<String, BaseWmsWarehouseMst> warehouseMstMap = new HashMap<>();
        //批量查询仓信息
        if (warehouseIds.size() > 0) {
            warehouseMstMap = RestMsgHelper.unpack(warehouseClient.mapbyids(warehouseIds));
        }
        Map<String, WarehouseLocatorBasicInfo> locationMstMap = new HashMap<>();
        //批量查询货位信息
        if (locids.size() > 0) {
            //获取货位信息
            RestMessage<List<WarehouseLocatorBasicInfo>> locationBasicInfos = warehouseClient.getLocationBasicInfos(locids.toArray(new String[]{}));
            if (!locationBasicInfos.isSuccess() || locationBasicInfos.getData() == null) {
                throw new BizException("查询货位关联信息失败!请重试或联系管理员!");
            }
            for (WarehouseLocatorBasicInfo locinfo : locationBasicInfos.getData()) {
                locationMstMap.put(locinfo.getWarehouseLocatorId(), locinfo);
            }
        }
        Map<String, BaseMtlItemMst> litemMstMap = new HashMap<>();
        //批量查询商品信息
        if (itemids.size() > 0) {
            RestMessage<List<BaseMtlItemMst>> itemResult = itemClient.getListByIds(itemids.toArray(new String[]{}));
            if (!itemResult.isSuccess() || itemResult.getData() == null) {
                throw new BizException("查询商品关联信息失败!请重试或联系管理员!");
            }
            for (BaseMtlItemMst iteminfo : itemResult.getData()) {
                litemMstMap.put(iteminfo.getItemId(), iteminfo);
            }
        }
        GspUpkeepCheckPlan plan = new GspUpkeepCheckPlan();
        String planId = String.valueOf(SnowFlakeUtils.getId());
        String code = "SDD" + planId.substring(planId.length() - 8);
        plan.setId(planId);
        plan.setCode(code);
        plan.setCreator(userId);
        plan.setCreatorName(userName);
        plan.setGmtCreate(date);
        plan.setModifier(userId);
        plan.setModifierName(userName);
        plan.setGmtModified(date);
        plan.setDcId(warehouseMstMap.get(wmsInvStockLots.get(0).getWarehouseId()).getDcId());
        plan.setEnterpriseId(enterpriseId);
        plan.setWarehouseId(wmsInvStockLots.get(0).getWarehouseId());
        //        plan.setBldgId(wmsInvStockLots.get(0).getBldgId());
        plan.setStatus("4");
        plan.setCargoOwnerId(wmsInvStockLots.get(0).getCargoOwnerId());
        plan.setSource("1");//数据来源：0=手动 1=自动
        plan.setPrintCount(0);
        upkeepCheckPlanMapper.save(plan);
        List<GspUpkeepCheck> gspUpkeepCheckList = new ArrayList<>();
        for (WmsInvStockLot wmsInvStockLot : wmsInvStockLots) {
            GspUpkeepCheck model = new GspUpkeepCheck();
            String id = String.valueOf(SnowFlakeUtils.getId());
            model.setId(id);
            model.setCode("SDD" + id.substring(id.length() - 8));
            model.setEnterpriseId(enterpriseId);
            model.setPlanUpkeepDate(date);
            model.setUpkeepDate(date);
            model.setUpkeepType(6);
            model.setPlanId(plan.getId());
            model.setPlanCode(code);
            model.setBatchId(wmsInvStockLot.getBatchId());
            BaseWmsWarehouseMst baseWmsWarehouseMst = warehouseMstMap.get(wmsInvStockLot.getWarehouseId());
            //获取仓信息
            model.setDcId(baseWmsWarehouseMst.getDcId());
            model.setWarehouseName(baseWmsWarehouseMst.getWarehouseName());
            model.setWarehouseId(model.getWarehouseId());
            model.setStockQty(wmsInvStockLot.getQuantity().toString());
            // 需要初始化养护数量(默认等于库存数量，解决空指针异常问题)
            model.setUpkeepQty(model.getStockQty());
            model.setPlanStockQty(model.getStockQty());
            model.setPendingQty(wmsInvStockLot.getQuantity());
            model.setCreator(userId);
            model.setCreatorName(userName);
            model.setGmtCreate(date);
            model.setModifier(userId);
            model.setModifierName(userName);
            model.setGmtModified(date);
            model.setStatus("5");
            // 数据来源：0=手动 1=自动 - by Huanglh 2022-01-20
            model.setSourceType("0");
            model.setWarehouseId(wmsInvStockLot.getWarehouseId());
            //获取商品资料
            model.setConclusion(2);
            model.setUpkeepConclusion(2);
            BaseMtlItemMst iteminfo = litemMstMap.get(wmsInvStockLot.getItemId());
            model.setItemCode(iteminfo.getItemCode());
            model.setItemId(wmsInvStockLot.getItemId());
            model.setItemName(iteminfo.getItemName());
            model.setCargoOwnerId(wmsInvStockLot.getCargoOwnerId());
            model.setUpkeepQty(wmsInvStockLot.getQuantity().toString());
            model.setStockQty(wmsInvStockLot.getQuantity().toString());
            model.setLotNum(wmsInvStockLot.getBatchNum());
            model.setUpkeepOperator(userDTO.getNickname());

            //获取货位信息
            WarehouseLocatorBasicInfo locatorBasicInfo = locationMstMap.get(wmsInvStockLot.getLocatorId());
            model.setLocatorId(wmsInvStockLot.getLocatorId());
            model.setLocatorCode(locatorBasicInfo.getWarehouseLocatorCode());
            model.setLocatorName(locatorBasicInfo.getWarehouseLocatorName());
            gspUpkeepCheckList.add(model);
        }


        mapper.saveBatch(gspUpkeepCheckList);

    }

    private List<RfGspUpkeepCheckVO> getDeviceByLocation(WarehouseLocatorBasicInfo locator, List<RfGspUpkeepCheckVO> list) {
        return list.stream().filter(t -> t.getLocatorId().equals(locator.getWarehouseLocatorId())).collect(Collectors.toList());
    }

    private QueryDTO initDTO(QueryDTO dto) {
        UserDTO user = userTemplate.getUserDTO();
        if (dto == null) {
            dto = new QueryDTO();
        }
        dto.initialPageWhenValueIsNull(user);
        return dto;
    }

    private List<WarehouseLocatorBasicInfo> getDeviceListByUpkeepCheck(List<GspUpkeepCheck> list) {
        String[] locationIds = list.stream().map(GspUpkeepCheck::getLocatorId).distinct().toArray(String[]::new);
        List<WarehouseLocatorBasicInfo> locations = RestMsgHelper.unpack(warehouseClient.getLocationBasicInfos(locationIds));
        Assert.notEmpty(locations, "获取货位信息失败");
        //拣货方式 设备且非货架库
        List<WarehouseLocatorBasicInfo> deviceLocList = locations.stream().filter(t -> PICK_MODE_DEVICE.equals(t.getPickMode())).collect(Collectors.toList());
        Assert.notEmpty(deviceLocList, "勾选的养护记录中没有需要发送设备指令的记录");
        return deviceLocList;
    }

    private void checkIsRepeatPushTask(List<GspUpkeepCheck> list) {
        GspUpkeepCheck check = list.stream().filter(d -> d.getOutboundInstruct() != null && !OUTBOUND_INSTRUCT_NO_SEND.equals(d.getOutboundInstruct())).findFirst().orElse(null);
        if (check != null) {
            BaseMtlItemMst item = RestMsgHelper.unpack(itemClient.getItemById(check.getItemId()));
            throw new PrologException(String.format("商品编码【%s】已发送指令，不能重复发送", item.getItemCode()));
        }
    }

    private void pushTask2Eis(List<GspUpkeepCheck> list, List<BaseMtlItemMst> items, List<WarehouseLocatorBasicInfo> deviceLocList) {
//        List<String> deviceLocId = deviceLocList.stream().map(WarehouseLocatorBasicInfo::getWarehouseLocatorId).collect(Collectors.toList());
//        List<GspUpkeepCheck> gspUpkeepCheckList = list.stream().filter(t -> deviceLocId.contains(t.getLocatorId())).collect(Collectors.toList());
//        List<EisPushTaskVO> params = new ArrayList<>(gspUpkeepCheckList.size());
//        for (GspUpkeepCheck gspUpkeepCheck : gspUpkeepCheckList) {
//            params.add(convert(gspUpkeepCheck, items, deviceLocList));
//        }
//        RestMsgHelper.unpack(inventoryClient.askIntegration(new AskIntegrationVo("outback", params)));

        List<String> deviceLocId = deviceLocList.stream().map(WarehouseLocatorBasicInfo::getWarehouseLocatorId).collect(Collectors.toList());
        List<GspUpkeepCheck> gspUpkeepCheckList = list.stream().filter(t -> deviceLocId.contains(t.getLocatorId())).collect(Collectors.toList());
        List<OutBoundRequestVO> params = new ArrayList<>(gspUpkeepCheckList.size());
        for (GspUpkeepCheck gspUpkeepCheck : gspUpkeepCheckList) {
            params.add(convert(gspUpkeepCheck, items, deviceLocList));
        }
        //调用出库推送任务接口
        com.prolog.common.RestMsgHelper.getData(eisResource.outBoundRequest(params));
    }

    private void updateOutboundInstruct2DB(List<GspUpkeepCheck> list) {
        UserDTO user = userTemplate.getUserDTO();
        DateTime now = DateUtil.date();
        list.forEach(t -> {
            t.setOutboundInstruct(OUTBOUND_INSTRUCT_UN_DELIVERY);
            t.setGmtModified(now);
            t.setModifierName(user.getNickname());
            t.setModifier(user.getId());
            mapper.update(t);
        });
    }

//    private EisPushTaskVO convert(GspUpkeepCheck dInfo, List<BaseMtlItemMst> items, List<WarehouseLocatorBasicInfo> stereoLocations ){
//        BaseMtlItemMst itemMst = items.stream().filter(var->dInfo.getItemId().equals(var.getItemId())).findFirst().orElse(null);
//        WarehouseLocatorBasicInfo locator = stereoLocations.stream().filter(var->var.getWarehouseLocatorId().equals(dInfo.getLocatorId())).findFirst().orElse(null);
//        if (null == itemMst){
//            throw new BizException("商品信息不存在！");
//        }
//        if (null == locator){
//            throw new BizException("查询货位信息失败！");
//        }
//        EisPushTaskVO vo = new EisPushTaskVO();
//        vo.setMsgId(cn.hutool.core.util.IdUtil.fastSimpleUUID());
//        vo.setTaskId(dInfo.getPlanId());
//        vo.setWarehouseId("JXYJ");
//        vo.setWorkType("40");
//        vo.setBusinessType("40");
//        vo.setPriority(10);
//        vo.setSeqNo(dInfo.getId());
//        vo.setOwnerId(dInfo.getCargoOwnerId());
//        vo.setItemId(dInfo.getItemId());
//        vo.setLotId(dInfo.getBatchId());
//        String packId = "";
//        vo.setContainerNo(dInfo.getContainerCode());
//        if (CollUtil.isNotEmpty(itemMst.getBaseMtlItemUomConversionsList())){
//            packId = itemMst.getBaseMtlItemUomConversionsList().get(0).getItemUomId();
//        }
//        vo.setPackId(packId);
//        vo.setQty(null != dInfo.getStockQty()?new BigDecimal(dInfo.getStockQty()):BigDecimal.ZERO);
//        vo.setOriginalArea("");
//        vo.setOriginalLocation("");
//        vo.setTargetLocation("");
//        if (locator.getWarehouseAreaCategory().equals("AGVZ")) {
//            vo.setWmslocationCode("AGVTP01");
//            vo.setTargetArea("");
//        }
//        if (locator.getWarehouseAreaCategory().equals("AGVL")) {
//            vo.setWmslocationCode("AGVHJ01");
//            vo.setTargetArea("");
//        }
//        if (locator.getWarehouseAreaCategory().equals("MJK")) {
//            vo.setWmslocationCode("SX01");
//            vo.setTargetArea("");
//        }
//        //eisConvert.packCallOutTaskVOMove(dInfo);
//        return vo;
//    }
    private OutBoundRequestVO convert(GspUpkeepCheck dInfo, List<BaseMtlItemMst> items, List<WarehouseLocatorBasicInfo> stereoLocations ){
        BaseMtlItemMst itemMst = items.stream().filter(var->dInfo.getItemId().equals(var.getItemId())).findFirst().orElse(null);
        WarehouseLocatorBasicInfo locator = stereoLocations.stream().filter(var->var.getWarehouseLocatorId().equals(dInfo.getLocatorId())).findFirst().orElse(null);
        if (null == itemMst){
            throw new BizException("商品信息不存在！");
        }
        if(StringUtils.isEmpty(itemMst.getItemCategoryCode())){
            throw new BizException("商品对应的商品大类编号为空");
        }
        if (null == locator){
            throw new BizException("查询货位信息失败！");
        }
        OutBoundRequestVO vo = new OutBoundRequestVO();
        vo.setMsgId(IdUtil.fastSimpleUUID());
        vo.setWarehouseId(dInfo.getWarehouseId());
        vo.setGroupOrderPolicy("4");//按容器
        List<OutBoundRequestItemVO> subList =new ArrayList<>();
        OutBoundRequestItemVO outBoundRequestItemVO =new OutBoundRequestItemVO();
        outBoundRequestItemVO.setWorkType(OutBoundRequestEnum.INV_CONSERVE.getWorkType());
        outBoundRequestItemVO.setBusinessType(OutBoundRequestEnum.INV_CONSERVE.getBusinessType());
        outBoundRequestItemVO.setWaveNo("");
        outBoundRequestItemVO.setTaskId(dInfo.getPlanId());
        outBoundRequestItemVO.setBillNo(dInfo.getPlanId());
        outBoundRequestItemVO.setStr1("0");
        outBoundRequestItemVO.setStr2("0");
        outBoundRequestItemVO.setCompanyId(dInfo.getCargoOwnerId());
        outBoundRequestItemVO.setCompanyName("");
        if ("AGVL".equals(locator.getWarehouseAreaCode())) {
            outBoundRequestItemVO.setItemId(dInfo.getItemId());
            outBoundRequestItemVO.setLotId(dInfo.getBatchId());
        } else {
            outBoundRequestItemVO.setContainerNo(dInfo.getContainerCode());
        }
        outBoundRequestItemVO.setTaskLineId(dInfo.getId());
        outBoundRequestItemVO.setPriority(10D);
        outBoundRequestItemVO.setOwnerId(dInfo.getCargoOwnerId());
        outBoundRequestItemVO.setEnterpriseId(dInfo.getEnterpriseId());
//        List<BaseWmsWarehouseArea> area = RestMsgHelper.unpack(warehouseClient.getWarehouseAreaBasicInfos(new String[]{locator.getWarehouseAreaId()}));
        outBoundRequestItemVO.setWmsLocationCode("MJK".equals(locator.getWarehouseAreaCode()) ? "MJZ" : locator.getWarehouseAreaCode());
        outBoundRequestItemVO.setTargetArea("");
        subList.add(outBoundRequestItemVO);
        vo.setSubList(subList);
        return vo;
    }
    private List<DxiGspMaintenanceRecord> spellDxi(List<GspUpkeepCheck> list) {
        //组合id
        String[] locatorIds = list.stream().map(GspUpkeepCheck::getLocatorId).distinct().toArray(String[]::new);
        //请求仓库信息，超长已经设置长度
        RestMessage<List<WarehouseLocatorBasicInfo>> warehouseResult = warehouseClient.getLocationBasicInfos(locatorIds);
        List<DxiGspMaintenanceRecord> retList = new ArrayList<>();
        List<BatchNumberListVO> batchNumberListVOList = null;
        String[] batchIds = list.stream().map(GspUpkeepCheck::getBatchId).distinct().toArray(String[]::new);
        RestMessage<List<BatchNumberListVO>> upKeepDictResult = inventoryClient.getBatchNumberBasicInfo(batchIds);
        if (upKeepDictResult != null && upKeepDictResult.isSuccess() && upKeepDictResult.getData() != null) {
            batchNumberListVOList = upKeepDictResult.getData();
        }
        //获取货主信息
        String[] ids = list.stream().map(x -> x.getCargoOwnerId()).distinct().toArray(String[]::new);
        RestMessage<Map<String, BaseCargoOwnerMst>> cargoOwnerMstByIds = chainClient.getCargoOwnerMstByIds(ids);
        Map<String, BaseCargoOwnerMst> data = null;
        if (cargoOwnerMstByIds != null && cargoOwnerMstByIds.isSuccess() && upKeepDictResult.getData() != null) {
            data = cargoOwnerMstByIds.getData();
        }
        //获取商品信息
        String[] itemIds = list.stream().map(x -> x.getItemId()).distinct().toArray(String[]::new);
        RestMessage<List<ItemBaseInfoVO>> itemBaseList = itemClient.getItemBaseList(itemIds);
        List<ItemBaseInfoVO> infoList = null;
        if (itemBaseList != null && itemBaseList.isSuccess() && upKeepDictResult.getData() != null) {
            infoList = itemBaseList.getData();
        }
        List<DxiGspMaintenanceRecordVO> recordVOList = new ArrayList<>();
        UserDTO userDTO = userTemplate.getUserDTO();
        if (null == userDTO){
            userDTO = new UserDTO();
            userDTO.setId("EIS");
            userDTO.setNickname("EIS");
        }
        BaseWmsWarehouseMst wmsWarehouseMst = null;

        for (int i = 0; i < list.size(); i++) {
            GspUpkeepCheck dto = list.get(i);
            ItemBaseInfoVO baseInfoVO = infoList.stream().filter(x -> x.getItemId().equals(dto.getItemId())).findFirst().orElse(null);
            if (i == 0) {
                RestMessage<BaseWmsWarehouseMst> itemResultWarehouse = warehouseClient.warehouse(dto.getWarehouseId());
                if (itemResultWarehouse.isSuccess() && itemResultWarehouse.getData() != null) {
                    wmsWarehouseMst = itemResultWarehouse.getData();
                }
            }
            DxiGspMaintenanceRecord omsDto = new DxiGspMaintenanceRecord();
            omsDto.setBillid(dto.getId());//单据ID
            omsDto.setBillno(dto.getCode());//单据编号
            omsDto.setBranchid(dto.getWarehouseId());//仓库ID
            if (wmsWarehouseMst != null) {
                omsDto.setBranchcode(wmsWarehouseMst.getWarehouseCode());
                omsDto.setBranchname(wmsWarehouseMst.getWarehouseName());//仓库名称
            }
            omsDto.setConsignorid(dto.getCargoOwnerId());//货主ID
            omsDto.setConsignorname(dto.getCargoOwnerName());//货主名称
            omsDto.setLineid(dto.getId());//行ID
            omsDto.setSeqno("1");//行号
            omsDto.setBilldate(dto.getPlanUpkeepDate());//养护计划日期
            omsDto.setItemid(dto.getItemId());//商品ID
            omsDto.setItemcode(baseInfoVO.getItemCode());//商品编号
            omsDto.setItemname(baseInfoVO.getItemName());//商品名称
            omsDto.setLotno(dto.getLotNum());//批号
            omsDto.setLocno(dto.getLocatorCode());//货位编号
            omsDto.setStockqty(dto.getStockQty());//库存数量
            Integer isProtected = dto.getIsProtected();
            if (isProtected == null) {
                omsDto.setItemtype("1");//养护商品类型
            } else {
                omsDto.setItemtype(isProtected.toString());//养护商品类型
            }
            omsDto.setStockstate(dto.getQualityStatus());
            Integer conclusion = dto.getConclusion();
            if ("1".equals(conclusion)) {//商品库存状态
                omsDto.setStockstate("合格");
            } else if ("2".equals(conclusion)) {
                omsDto.setStockstate("不合格");
            }
            omsDto.setStatus(conclusion.toString());//养护审核状态
            omsDto.setSourcetype("WMS");//养护数据来源
            omsDto.setUpkeepoperator(dto.getUpkeepOperator());//养护员
            omsDto.setProcessopinion(dto.getProcessOpinion());//处理意见
            omsDto.setRecheckoperator(dto.getCheckOperator());//复检员
            omsDto.setRecheckopinion(dto.getCheckOpinion());//复检意见
            omsDto.setAuditoperator(dto.getRecheckOperator());//审核员
            omsDto.setAuditopinion(dto.getRecheckOpinion());//审核意见
            omsDto.setCheckoperation(spellUpkeepOperation(dto));
            omsDto.setQualifiedqty(dto.getUpkeepQty());//养护数量
            omsDto.setPendingqty(dto.getPendingQty() == null ? "0" : dto.getPendingQty().toString());//养护待处理数量
            omsDto.setQualitystatus(dto.getQualityStatus());//质量状况
            omsDto.setThstatus(dto.getThsTatus());//温湿度状况
            omsDto.setPendingreason(dto.getPendingReason());//养护待处理原因
            omsDto.setUpkeepdate(dto.getUpkeepDate());//养护时间
            omsDto.setRecheckdate(dto.getRecheckDate());//复检日期
            String remark = dto.getRemark();
            omsDto.setRemark(remark);//备注
            //		omsDto.setAttr_str1();//字符扩展属性1
            if (batchNumberListVOList != null && batchNumberListVOList.size() > 0) {
                BatchNumberListVO vo = batchNumberListVOList.stream().filter(item -> item.getBatchId().equals(dto.getBatchId())).findFirst().orElse(null);
                if (vo != null) {
                    omsDto.setAttrStr2(vo.getBatchProductionDateShow());
                    omsDto.setAttrStr3(vo.getBatchExpiredDateShow());
                }
            }
            //		omsDto.setAttr_num1();//字符扩展属性3
            //		omsDto.setAttr_num2();//字符扩展属性4
            //		omsDto.setAttr_dte1();//字符扩展属性5
            //		omsDto.setAttr_dte2();//字符扩展属性6
            omsDto.setCheckmemo("现场查看");
            omsDto.setCreateby(userDTO.getUsername());//录入员
            omsDto.setCreatedate(dto.getGmtCreate());//录入时间
            omsDto.setLastmodifyby(dto.getModifierName());//修改人
            omsDto.setLastmodifydate(dto.getGmtModified());//修改时间
            omsDto.setEnterpriseid(userDTO.getEnterpriseId());//dto.getEnterpriseId();//企业ID
            omsDto.setEnterprisename(userDTO.getEnterpriseName());//企业名称
            if (!StringUtils.isBlank(remark) && "近效期".equals(remark)) {
                omsDto.setIsneardate("是");
            } else {
                omsDto.setIsneardate("否");
            }
            Optional<WarehouseLocatorBasicInfo> optional = warehouseResult.getData().stream().filter(y -> y.getWarehouseLocatorId().equals(dto.getLocatorId())).findFirst();
            if (optional.isPresent()) {
                WarehouseLocatorBasicInfo locatorBasicInfo = optional.get();
                omsDto.setBuilding(locatorBasicInfo.getBldgName());
            }

            retList.add(omsDto);

            //封装OMS接口平台对象
            DxiGspMaintenanceRecordVO recordVO = new DxiGspMaintenanceRecordVO();
            recordVO.setBillno(dto.getCode());//单据编号
            recordVO.setBilldate(DateUtils.format(dto.getPlanUpkeepDate(),"yyyy-MM-dd HH:mm:ss"));//养护计划日期
            if (isProtected == null) {
                recordVO.setMaintenanceType("1");//养护商品类型
            } else {
                recordVO.setMaintenanceType(isProtected.toString());//养护商品类型
            }
            if (wmsWarehouseMst != null) {
                recordVO.setBranchcode(wmsWarehouseMst.getWarehouseCode());
            }
            if(data!=null){
                BaseCargoOwnerMst baseCargoOwnerMst = data.get(dto.getCargoOwnerId());
                recordVO.setConsignorcode(baseCargoOwnerMst!=null?baseCargoOwnerMst.getCargoOwnerCode():"");
            }
            recordVO.setItemcode(dto.getItemCode());
            if(infoList!=null){
                if(baseInfoVO!=null){
                    recordVO.setCapacity(baseInfoVO.getSpecification());
                    recordVO.setFsymbol(baseInfoVO.getItemHealthApprovalNbr());
                    recordVO.setFfactory(baseInfoVO.getManufacturerName());
                }
                recordVO.setMaintenanceMeasure("现场查看");
                recordVO.setLotNo(dto.getLotNum());
                recordVO.setOnhandQuantity(dto.getStockQty());
                if ("1".equals(conclusion)) {//养护结论
                    recordVO.setMaintenanceResult("合格");
                } else if ("2".equals(conclusion)) {
                    recordVO.setMaintenanceResult("不合格");
                }
                recordVO.setMaintenanceby(dto.getUpkeepOperator());
                recordVO.setAuditby(dto.getRecheckOperator());
                recordVO.setAuditOpinion(dto.getRecheckOpinion());
                recordVO.setMaintenanceNum(dto.getUpkeepQty());
                recordVO.setPendingNum(dto.getPendingQty()!=null?dto.getPendingQty().toString():"0");
                recordVO.setQualityState(dto.getQualityStatus());
                recordVO.setHumitureState(dto.getThsTatus());
                recordVO.setManageReason(dto.getPendingReason());
                recordVO.setRecheckby(dto.getCheckOperator());
                recordVO.setMaintenanceDate(null == dto.getUpkeepDate()?null:DateUtils.format(dto.getUpkeepDate(),"yyyy-MM-dd HH:mm:ss"));
                recordVO.setRecheckDate(null == dto.getRecheckDate()?null:DateUtils.format(dto.getRecheckDate(),"yyyy-MM-dd HH:mm:ss"));
                recordVO.setReviewOpinion(dto.getRecheckOpinion());
                recordVO.setRemark(dto.getRemark());
                recordVO.setItemid(dto.getItemId());
                recordVO.setPenterpriseid(dto.getEnterpriseId());
                recordVOList.add(recordVO);
            }
        }
        //调用接口平台推送养护记录
        try {
            if(recordVOList.size()>0){
                if (StringUtils.isEmpty(dxiGspMaintenanceRecordUrl)) {
                    throw new BizException("请求路径配置为空");
                }
                System.out.println(JSON.toJSONString(recordVOList));
                logger.info("养护回传OMS====>"+JSON.toJSONString(recordVOList));
                String url = dxiGspMaintenanceRecordUrl;
                String result = HttpUtil.post(url, JSONObject.toJSONString(recordVOList));
                JSONObject parse = JSONObject.parseObject(result);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return retList;
    }

    private String spellUpkeepOperation(GspUpkeepCheck dto) {
        String checkOperation;
        if (dto.getCheckFanDuo() != null && dto.getCheckFanDuo())
            checkOperation = "Y,";
        else
            checkOperation = "N,";
        if (dto.getCheckChuShi() != null && dto.getCheckChuShi())
            checkOperation = checkOperation + "Y,";
        else
            checkOperation = checkOperation + "N,";
        if (dto.getCheckJiaShi() != null && dto.getCheckJiaShi())
            checkOperation = checkOperation + "Y,";
        else
            checkOperation = checkOperation + "N,";

        if (dto.getCheckShenWen() != null && dto.getCheckShenWen())
            checkOperation = checkOperation + "Y,";
        else
            checkOperation = checkOperation + "N,";

        if (dto.getCheckJiangWen() != null && dto.getCheckJiangWen())
            checkOperation = checkOperation + "Y,";
        else
            checkOperation = checkOperation + "N,";

        if (dto.getCheckChuChen() != null && dto.getCheckChuChen())
            checkOperation = checkOperation + "Y,";
        else
            checkOperation = checkOperation + "N,";

        if (dto.getCheckWaiGuan() != null && dto.getCheckWaiGuan())
            checkOperation = checkOperation + "Y,";
        else
            checkOperation = checkOperation + "N,";

        if (dto.getCheckBaoZhuang() != null && dto.getCheckBaoZhuang())
            checkOperation = checkOperation + "Y,";
        else
            checkOperation = checkOperation + "N,";

        if (dto.getCheckChenChuTiaoJian() != null && dto.getCheckChenChuTiaoJian())
            checkOperation = checkOperation + "Y,";
        else
            checkOperation = checkOperation + "N,";

        if (dto.getCheckTongFeng() != null && dto.getCheckTongFeng())
            checkOperation = checkOperation + "Y";
        else
            checkOperation = checkOperation + "N";
        return checkOperation;
    }

    @Override
    @Transactional
    public void confirmUpkeepMove(String[] arrList) {
        MapToolKit put = MapUtils.put("status", "6").put("gmtModified", new Date());
        for (int i = 0; i < arrList.length; i++) {
            mapper.updateMapById(arrList[i], put.getMap(), GspUpkeepCheck.class);
        }
    }

    /**
     * 调用接口平台
     *
     * @param interfaceId
     * @param list
     * @return
     */
    public JSONObject askIntegration(String interfaceId, List<GspUpkeepCheck> list) {
        Map paramMap = MapUtils.put("token", token).put("interfaceId", interfaceId).getMap();
        if (list != null) {
            List paramList = new ArrayList<>();
            String paramKey = "param";
            // 需要依据接口来组织请求数据
            for (GspUpkeepCheck upkeepCheck : list) {
                if (interfaceId.equals(sendDeviceId)) {
                    // wms-agv养护下传3
                    // 生成计划时养护数和待处理数量都为0，养护人为空
                    upkeepCheck.setUpkeepQty("0");
                    upkeepCheck.setPendingQty(BigDecimal.ZERO);
                    upkeepCheck.setUpkeepOperator("");

                    paramKey = "resultData";
                    paramList.add(upkeepCheck);
                }

                if (interfaceId.equals(updateDeviceId)) {
                    // 养护WMS回传AGV状态3
                    paramList.add(MapUtils.put("id", upkeepCheck.getId()).getMap());
                }

                if (interfaceId.equals(updateDeviceOkId)) {
                    // 养护WMS回传AGV，待处理结论合格回传3
                    Map paramM;
                    if (upkeepCheck.getConclusion().equals("1")) {
                        // 复检合格
                        paramM = MapUtils.put("id", upkeepCheck.getId()).put("okQty", upkeepCheck.getUpkeepQty()).put("pendingQty", "0").put("status", "4").getMap();
                    } else {
                        // 复检不合格
                        paramM = MapUtils.put("id", upkeepCheck.getId()).put("okQty", "0").put("pendingQty", upkeepCheck.getUpkeepQty()).put("status", "5").getMap();
                    }
                    paramList.add(paramM);
                }
            }
            paramMap.put("data", MapUtils.put(paramKey, paramList).getMap());
        }
        logger.info("integrationResource.httpService入参为interfaceId：" + interfaceId + ",data:" + JSONObject.toJSONString(list));
        String result = integrationResource.httpService(paramMap);
        logger.info("integrationResource.httpService返回为interfaceId：" + interfaceId + ",result:" + result);
        JSONObject json = JSONObject.parseObject(result);
        if (json.containsKey("success") && !json.getBoolean("success")) {
            throw new PrologException("接口平台调用错误:" + json);
        }
        return json;
    }
}
