package com.tykj.dev.device.packing.controller;

import com.tykj.dev.config.cache.ConfigCache;
import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.library.repository.DeviceLibraryDao;
import com.tykj.dev.device.library.service.DeviceLibraryService;
import com.tykj.dev.device.library.subject.domin.DeviceLibrary;
import com.tykj.dev.device.library.subject.vo.DeviceLibrarySelectVo;
import com.tykj.dev.device.packing.repository.PackingLibraryDao;
import com.tykj.dev.device.packing.service.PackingLibraryService;
import com.tykj.dev.device.packing.subject.domin.PackingLibrary;
import com.tykj.dev.device.packing.subject.vo.*;
import com.tykj.dev.device.user.util.UserUtils;
import com.tykj.dev.misc.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toMap;

/**
 * @author dengdiyi
 */
@RestController
@Api(tags = "列装管理模块", description = "列装管理接口")
@AutoDocument
@RequestMapping("/packing")
@Validated
public class PackingLibraryController {

    @Autowired
    PackingLibraryService packingLibraryService;

    @Autowired
    DeviceLibraryDao deviceLibraryDao;

    @Autowired
    DeviceLibraryService deviceLibraryService;

    @Autowired
    PackingLibraryDao packingLibraryDao;

    @Autowired
    private ConfigCache configCache;

    @Autowired
    private UserUtils userUtils;

    @ApiOperation(value = "申请后入库获取父子结构列装（去除已入库序列号）", notes = "获取父子结构列装")
    @PostMapping("/merge")
    public ResponseEntity merge(@RequestBody List<PackingLibrary> packingLibraries){
        Map<String,DeviceLibrary> map = deviceLibraryService.getAllDeviceSeqMap();
        packingLibraries.forEach(packingLibrary -> {
            List<String> inputSeqs = DeviceSeqUtil.selectDeviceSeqs(packingLibrary.getSeq());
            List<String> outputSeqs = new ArrayList<>();
            inputSeqs.forEach(s -> {
                if (map.get(s)==null){
                    outputSeqs.add(s);
                }
            });
            packingLibrary.setSeq(StringSplitUtil.stringListToString(DeviceSeqUtil.getContinuousSeqs(outputSeqs)));
        });
        //返回父子结构
        Map<Integer, PackingLibrary> nodeCollect =
                packingLibraries.stream().collect(Collectors.toMap(PackingLibrary::getId, packingLibrary -> packingLibrary));
        return ResponseEntity.ok(GetTreeUtils.parseTreeFromDown(
                packingLibraries,
                PackingLibrary::getId,
                packingLibrary -> Optional.ofNullable(nodeCollect.get(packingLibrary.getPartParentId())),
                PackingLibrary::addChildNode
        ));
    }

    @ApiOperation(value = "获取装备单据显示", notes = "获取装备单据显示")
    @PostMapping("/getAllotScript")
    public ResponseEntity getAllotScript(@RequestBody List<Integer> ids){
        return ResponseEntity.ok(packingLibraryService.getDevcieAllotScript(ids));
    }

    @ApiOperation(value = "获取装备单据显示", notes = "获取装备单据显示")
    @PostMapping("/getScript")
    public ResponseEntity setRecord(@RequestBody List<Integer> ids){
//        throw new ApiException(ResponseEntity.status(303).body("aaa"));
        return ResponseEntity.ok(packingLibraryService.getDevcieScript(ids));
    }

    @ApiOperation(value = "列装库分页查询", notes = "可以通过这个接口进行列装查询")
    @PostMapping("/serve/summary")
    public ResponseEntity getPage(@RequestBody PackingLibrarySelectVo packingLibrarySelectVo) {
        Page<PackingLibrary> packingLibraryEntityPage = packingLibraryService.getPage(packingLibrarySelectVo, packingLibrarySelectVo.getPageable());
        packingLibraryEntityPage.getContent().forEach(PackingLibrary::setConfigName);
        return ResultUtil.success(packingLibraryEntityPage);
    }

//    @ApiOperation(value = "列装库退装分页查询", notes = "可以通过这个接口进行列装查询")
//    @PostMapping("/retired/summary")
//    public ResponseEntity getInvalidPage(@RequestBody PackingLibrarySelectVo packingLibrarySelectVo) {
//        List<PackingLibrary> resultList = packingLibraryService.getInvalidPage(packingLibrarySelectVo, packingLibrarySelectVo.getPageable());
//        //返回父子结构
//        Map<Integer, PackingLibrary> nodeCollect =
//                resultList.stream().collect(Collectors.toMap(PackingLibrary::getId, packingLibrary -> packingLibrary));
//            List<PackingLibrary> resultList2 =  GetTreeUtils.parseTreeFromDown(
//                resultList,
//                PackingLibrary::getId,
//                packingLibrary -> Optional.ofNullable(nodeCollect.get(packingLibrary.getPartParentId())),
//                PackingLibrary::addChildNode
//        );
//        Page<PackingLibrary> packingLibraries = PageUtil.getPerPage(packingLibrarySelectVo.getPage(),packingLibrarySelectVo.getSize(),resultList2,packingLibrarySelectVo.getPageable());
//        Map<String,Object> map = new HashMap<>();
//        map.put("pages",packingLibraries);
//        map.put("models",resultList.stream().map(PackingLibrary::getModel).collect(Collectors.toSet()));
//        map.put("names",resultList.stream().map(PackingLibrary::getName).collect(Collectors.toSet()));
//        return ResultUtil.success(map);
//    }
    @ApiOperation(value = "列装库退装分页查询", notes = "可以通过这个接口进行列装查询")
    @PostMapping("/retired/summary")
    public ResponseEntity getInvalidPage(@RequestBody PackingLibrarySelectVo packingLibrarySelectVo) {
        List<PackingLibrary> resultList = packingLibraryService.getInvalidPage(packingLibrarySelectVo, packingLibrarySelectVo.getPageable());
        //返回父子结构
        Map<Integer, PackingLibrary> nodeCollect =
                resultList.stream().collect(Collectors.toMap(PackingLibrary::getId, packingLibrary -> packingLibrary));

        List<PackingLibrary> resultList2 = GetTreeUtils.parseTreeFromDown(
                resultList,
                PackingLibrary::getId,
                packingLibrary -> Optional.ofNullable(nodeCollect.get(packingLibrary.getPartParentId())),
                PackingLibrary::addChildNode
        );
        //resultList2 拿到所有的model
        List<String> models = resultList2.stream().map(PackingLibrary::getModel).collect(Collectors.toList());
        Set<String> names = resultList.stream().filter(packingLibrary -> packingLibrary.getPackingStatus().equals(packingLibrarySelectVo.getPackingStatus()))
                .map(PackingLibrary::getName).collect(Collectors.toSet());
//        Set<String> names = resultList2.stream().map(PackingLibrary::getName).collect(Collectors.toSet());
//        交集集合
        List<PackingLibrary> defectList = new ArrayList<>();
        for (String model : models) {
            //model在models出现的次数
            int count = Collections.frequency(models, model);
            if (count > 1) {
                //取出list<PackingLibrary>
                List<Integer> allByModel = packingLibraryDao.findAllByModel(model).stream().map(PackingLibrary::getId).collect(Collectors.toList());
                //取出交集
                defectList = resultList2.stream().filter(packingLibrary -> allByModel.contains(packingLibrary.getId())).sorted(Comparator.comparing(PackingLibrary::getId)).collect(Collectors.toList());
                //去除交集
                resultList2.removeAll(defectList);
                //进行按照model分组
                Map<String, List<PackingLibrary>> map1 = defectList.stream().collect(Collectors.groupingBy(PackingLibrary::getModel));
                List<PackingLibrary> context1 = getContext1(map1);
                resultList2.addAll(context1);
            }
        }
        //过滤出空目录
        //判断它本身是不是就是空目录
        List<PackingLibrary> finalResult = resultList2.stream().filter(packingLibrary -> (packingLibrary.getChilds() != null && packingLibrary.getChilds().size() != 0))
                .collect(Collectors.toList());
        resultList2.removeAll(finalResult);
        for (PackingLibrary packingLibrary : resultList2) {
            if (packingLibraryDao.findAllByModel(packingLibrary.getModel()).size() >0){
                finalResult.add(packingLibrary);
            }
        }
        Page<PackingLibrary> packingLibraries = PageUtil.getPerPage(packingLibrarySelectVo.getPage(), packingLibrarySelectVo.getSize(), finalResult, packingLibrarySelectVo.getPageable());
        Map<String, Object> map = new HashMap<>();
        map.put("pages", packingLibraries);
//        map.put("models", resultList2.stream().map(PackingLibrary::getModel).collect(Collectors.toSet()));
        map.put("models", models.stream().distinct().collect(Collectors.toList()));
//        map.put("names", resultList2.stream().map(PackingLibrary::getName).collect(Collectors.toSet()));
        map.put("names", names);
        return ResultUtil.success(map);
    }



    @ApiOperation(value = "列装库列表查询", notes = "可以通过这个接口进行列装查询")
    @PostMapping("/getList")
    public ResponseEntity getList(@RequestBody PackingLibrarySelectVo packingLibrarySelectVo) {
        List<PackingLibrary> packingLibraryEntities = packingLibraryService.getList1(packingLibrarySelectVo);
//        if (packingLibrarySelectVo.ids!=null&&packingLibrarySelectVo.ids.size()>0) {
//            packingLibraryEntities.removeIf(p -> packingLibrarySelectVo.ids.contains(p.getId()));
//            packingLibraryEntities.forEach(packingLibrary -> {
//                List<PackingLibrary> childs = packingLibrary.getChilds();
//                if (childs!=null&&childs.size()>0){
//                    childs.removeIf(packingLibrary1 -> packingLibrarySelectVo.ids.contains(packingLibrary1.getId()));
//                }
//            });
//        }
//        packingLibraryEntities.forEach(PackingLibrary::setConfigName);
        if (packingLibrarySelectVo.getIsAllot()!=null){
            packingLibraryEntities = filterDevices(packingLibraryEntities);
        }
        packingLibraryEntities.forEach(PackingLibrary::setConfigName);
        //返回父子结构
        Map<Integer, PackingLibrary> nodeCollect =
                packingLibraryEntities.stream().collect(Collectors.toMap(PackingLibrary::getId, packingLibraryEntity -> packingLibraryEntity));
        List<PackingLibrary> packingLibraryList = GetTreeUtils.parseTreeFromDown(
                packingLibraryEntities,
                PackingLibrary::getId,
                packingLibraryEntity -> Optional.ofNullable(nodeCollect.get(packingLibraryEntity.getPartParentId())),
                PackingLibrary::addChildNode
        ).stream().sorted(Comparator.comparing(PackingLibrary::getModel)).collect(Collectors.toList());

        Map<String,Object> map = new HashMap<>();
        map.put("pages",packingLibraryList);
        List<String> models = new ArrayList<>();
        for (PackingLibrary p : packingLibraryList){
            models.add(p.getModel());
        }
        //添加形态
        Map<Integer, String> styleMap = configCache.getStyleMap();
        Set<Integer> types = packingLibraryEntities.stream().map(PackingLibrary::getType).collect(Collectors.toSet());
        Set<String> names = packingLibraryEntities.stream().map(PackingLibrary::getName).collect(Collectors.toSet());
        //去重
        models = models.stream().distinct().collect(Collectors.toList());
        map.put("models",models);
        map.put("types",types.stream().map(integer -> new PackingTypeVo(integer,styleMap.get(integer))).collect(Collectors.toList()));
        map.put("names",names);
        return ResultUtil.success(map);
    }


    @ApiOperation(value = "更新列装库", notes = "可以通过这个接口更新列装")
    @PostMapping("/updatePackingLibrary")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity updatePackingLibrary(@RequestBody @Validated PackingEditVo packingEditVo) {
        //更新列装信息
        if (packingEditVo.getUpdateVoList() != null) {
            PackingLibrary packingLibraryEntity = packingLibraryService.getOne(packingEditVo.getPackingId());
            //获取配件列装
            List<PackingLibrary> packingLibraries = packingLibraryService.selectAllPart(packingEditVo.getPackingId());
            //获取该列装所有装备
            List<DeviceLibrary> deviceLibraries = deviceLibraryDao.getAllByPackingId(packingEditVo.getPackingId());
            //获取所有列装配件装备
            List<DeviceLibrary> deviceLibraryList = new ArrayList<>();
            packingLibraries.forEach(packingLibrary -> deviceLibraryList.addAll(deviceLibraryDao.getAllByPackingId(packingLibrary.getId())));
            PackingLibraryUpdateVo p = packingEditVo.getUpdateVoList();
            if (p.getApplyType() != null) {
                packingLibraryEntity.setApplyType(p.getApplyType());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setApplyType(p.getApplyType()));
            }
            if (p.getCreateUnit() != null) {
                packingLibraryEntity.setCreateUnit(p.getCreateUnit());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setCreateUnit(p.getCreateUnit()));
            }
            if (p.getFileName() != null) {
                packingLibraryEntity.setFileName(p.getFileName());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setFileName(p.getFileName()));
            }
            if (p.getFileUrl() != null) {
                packingLibraryEntity.setFileUrl(p.getFileUrl());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setFileUrl(p.getFileUrl()));
            }
            if (p.getImageName() != null) {
                packingLibraryEntity.setImageName(p.getImageName());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setImageName(p.getImageName()));
            }
            if (p.getImageUrl() != null) {
                packingLibraryEntity.setImageUrl(p.getImageUrl());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setImageUrl(p.getImageUrl()));
            }
            if (p.getInvisibleRange() != null) {
                packingLibraryEntity.setInvisibleRange(p.getInvisibleRange());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setInvisibleRange(p.getInvisibleRange()));
                deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setInvisibleRange(p.getInvisibleRange()));
                deviceLibraryList.forEach(deviceLibrary -> deviceLibrary.setInvisibleRange(p.getInvisibleRange()));
            }
            if (p.getMatchingRange() != null) {
                packingLibraryEntity.setMatchingRange(p.getMatchingRange());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setMatchingRange(p.getMatchingRange()));
                deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setMatchingRange(p.getMatchingRange()));
                deviceLibraryList.forEach(deviceLibrary -> deviceLibrary.setMatchingRange(p.getMatchingRange()));
            }
            if (p.getModel() != null) {
                packingLibraryEntity.setModel(p.getModel());
                deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setModel(p.getModel()));
            }
            if (p.getName() != null) {
                packingLibraryEntity.setName(p.getName());
                deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setName(p.getName()));
            }
            if (p.getNature() != null) {
                packingLibraryEntity.setNature(p.getNature());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setNature(p.getNature()));
            }
            if (p.getPrice() != null) {
                packingLibraryEntity.setPrice(p.getPrice());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setPrice(p.getPrice()));
            }
            if (p.getProdUnit() != null) {
                packingLibraryEntity.setProdUnit(p.getProdUnit());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setProdUnit(p.getProdUnit()));
            }
            if (p.getSecretLevel() != null) {
                packingLibraryEntity.setSecretLevel(p.getSecretLevel());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setSecretLevel(p.getSecretLevel()));
                deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setSecretLevel(p.getSecretLevel()));
                deviceLibraryList.forEach(deviceLibrary -> deviceLibrary.setSecretLevel(p.getSecretLevel()));
            }
            if (p.getStatus() != null) {
                packingLibraryEntity.setStatus(p.getStatus());
                packingLibraries.forEach(packingLibrary -> packingLibrary.setStatus(p.getStatus()));
            }
            if (p.getType() != null) {
                packingLibraryEntity.setType(p.getType());
                deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setType(p.getType()));
            }
            packingLibraryService.update(packingLibraryEntity);
            packingLibraries.forEach(packingLibrary -> packingLibraryService.update(packingLibrary));
            deviceLibraries.forEach(deviceLibrary -> deviceLibraryService.update(deviceLibrary));
            deviceLibraryList.forEach(deviceLibrary -> deviceLibraryService.update(deviceLibrary));
        }
        //更新配件信息
        if (packingEditVo.getPartUpdateVoList()!=null){
            packingEditVo.getPartUpdateVoList().forEach(packingLibraryUpdateVo -> {
                if (packingLibraryUpdateVo.getPackingId() > 0){
                    PackingLibrary packingLibrary = packingLibraryService.getOne(packingLibraryUpdateVo.getPackingId());
                    //获取该配件所有装备
                    List<DeviceLibrary> deviceLibraries = deviceLibraryDao.getAllByPackingId(packingLibraryUpdateVo.getPackingId());
                    if (packingLibraryUpdateVo.getModel()!=null){
                        packingLibrary.setModel(packingLibraryUpdateVo.getModel());
                        deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setModel(packingLibraryUpdateVo.getModel()));
                    }
                    if (packingLibraryUpdateVo.getName()!=null){
                        packingLibrary.setName(packingLibraryUpdateVo.getName());
                        deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setName(packingLibraryUpdateVo.getName()));
                    }
                    if (packingLibraryUpdateVo.getType()!=null){
                        packingLibrary.setType(packingLibraryUpdateVo.getType());
                        deviceLibraries.forEach(deviceLibrary -> deviceLibrary.setType(packingLibraryUpdateVo.getType()));
                    }
                    deviceLibraries.forEach(deviceLibrary -> deviceLibraryService.update(deviceLibrary));
                    packingLibraryService.update(packingLibrary);
                }
            });
        }
        //添加新增配件
        if (packingEditVo.getPartAddList() != null) {
            for (PartSaveVo p : packingEditVo.getPartAddList()) {
                PackingLibrary packingLibraryEntity = packingLibraryService.getOne(packingEditVo.getPackingId());
                if (packingLibraryEntity.getIsPart() == 0 && packingLibraryEntity.getPartParentId() == null) {
                    PackingLibrary p2 = new PackingLibrary();
                    BeanUtils.copyProperties(packingLibraryEntity, p2);
                    BeanUtils.copyProperties(p, p2);
                    p2.setId(null);
                    p2.setIsPart(1);
                    p2.setPartParentId(packingLibraryEntity.getId());
                    packingLibraryService.addEntity(p2);
                }
            }
        }
        //删除绑定的配件
        if (packingEditVo.getPartIdDeleteList() != null) {
            for (Integer id : packingEditVo.getPartIdDeleteList()) {
                if (id > 0) {
                    PackingLibrary packingLibraryEntity = packingLibraryService.getOne(id);
                    if (packingLibraryEntity.getIsPart() == 1 && packingLibraryEntity.getPartParentId().equals(packingEditVo.getPackingId())) {
                        packingLibraryEntity.setPartParentId(null);
                        packingLibraryService.update(packingLibraryEntity);
                        packingLibraryService.delete(packingLibraryEntity.getId());
                    }
                }
            }
        }
        return ResultUtil.success("更新成功");
    }

    @ApiOperation(value = "查询存在的型号", notes = "可以通过这个接口查询存在的型号")
    @GetMapping("/selectAllMode")
    public ResponseEntity selectAllMode() {
        return ResultUtil.success(packingLibraryService.getModelList());
    }

    @ApiOperation(value = "查询存在的类型", notes = "可以通过这个接口查询存在的类型")
    @GetMapping("/selectAllType")
    public ResponseEntity selectAllType() {
        return ResultUtil.success(packingLibraryService.getTypeList());
    }

    @ApiOperation(value = "查询列装库详情页", notes = "可以通过这个接口查询存在的类型")
    @GetMapping("/serve/detail/{id}")
    public ResponseEntity selectPackingDetail(@PathVariable("id") @Min(value = 1,message = "id不能小于1") int id) {
        return ResultUtil.success(packingLibraryService.getPackingDetail(id));
    }

    @ApiOperation(value = "查询多个列装详情", notes = "可以通过这个接口查询多个列装详情")
    @PostMapping("/selectMoreDetail")
    public ResponseEntity selectMorePackingDetail(@RequestBody List<Integer> ids) {
        List<PackingLibrary> packingLibraries = new ArrayList<>();
        ids.forEach(integer -> packingLibraries.add(packingLibraryService.getOne(integer).setConfigName()));
        return ResultUtil.success(packingLibraries);
    }

    @ApiOperation(value = "查询退装详情页", notes = "可以通过这个接口查询存在的类型")
    @GetMapping("/retired/detail/{id}")
    public ResponseEntity selectInvalidDetail(@PathVariable("id") @Min(value = 1,message = "id不能小于1") int id) {
        return ResultUtil.success(packingLibraryService.getInvalidDetail(id));
    }

    @ApiOperation(value = "查询父子结构列装")
    @PostMapping("/selectList")
    public ResponseEntity selectPack(@RequestBody SelectPack selectPack){
        return ResultUtil.success(packingLibraryService.getInsertList(selectPack));
    }

    public List<PackingLibrary> getContext1(Map<String,List<PackingLibrary>> map){

        List<PackingLibrary> context = new ArrayList<>();

        for (List<PackingLibrary> value : map.values()) {
            PackingLibrary context2 = getContext2(value);
            context.add(context2);
        }
        return context;

    }

    public PackingLibrary getContext2(List<PackingLibrary> packingLibraries) {
        //判断集合的长度  801 802 803 804   只操作804 或者803
        //取出目录
        PackingLibrary packingLibrary = packingLibraries.get(0);
        packingLibraries.remove(packingLibrary);
        List<PackingLibrary> finalPackingList = new ArrayList<>();
        for (int i = 0; i < packingLibraries.size(); i++) {
            //会造成覆盖
            if (packingLibrary.getChilds() != null){
                List<PackingLibrary> childs = packingLibrary.getChilds();
                finalPackingList.addAll(childs);
                finalPackingList.addAll(packingLibraries);
                packingLibrary.setChilds(finalPackingList);
            }else {
                //直接赋值
                packingLibrary.setChilds(packingLibraries);
            }

        }
        return packingLibrary;
    }

//    public PackingLibrary getContext4(List<PackingLibrary> packingLibraries){ //12 6
//        //判断集合的长度  801 802 803 804   只操作804 或者803
//        //取出目录
//        PackingLibrary root = packingLibraries.get(0);
//        packingLibraries.removeIf(e -> Objects.equals(e,root));
//        List<PackingLibrary> finalPackingList = new ArrayList<>();
//        for (int i = 0; i < packingLibraries.size(); i++) {
//            //会造成覆盖
//            if (root.getChilds() != null){
//                List<PackingLibrary> childs = root.getChilds();
//                finalPackingList.addAll(childs);
//                finalPackingList.addAll(packingLibraries);
//                root.setChilds(finalPackingList);
//            }else {
//                //直接赋值
//                root.setChilds(packingLibraries);
//            }
//
//        }
//        return root;
//    }

//    /**
//     *
//     * @param packingLibraries 有父子结构集合
//     * @return
//     */
//    public List<PackingLibrary> getAllChilds(List<PackingLibrary> packingLibraries){
//        List<PackingLibrary> packingLibraryList = new ArrayList<>();
//        for (PackingLibrary packingLibrary : packingLibraries) {
//            List<PackingLibrary> allChilds2 = getAllChilds2(packingLibrary);
//            packingLibraryList.addAll(allChilds2);
//        }
//        return packingLibraryList;
//    }
//
//    //取出所有的子
//    public List<PackingLibrary> getAllChilds2(PackingLibrary packingLibrary){
//        List<PackingLibrary> list = new ArrayList<>();
//        if (packingLibrary.getChilds().size()>0){
//            List<PackingLibrary> childs = packingLibrary.getChilds();
//            for (PackingLibrary child : childs) {
//                list.add(packingLibrary);
//                list.add(child);
//                return getAllChilds2(child);
//            }
//        }else {
//            list.add(packingLibrary);
//        }
//        return list;
//    }

    /**
     * 通过列装id查询装备是否存在  过滤出装备为0的
     */
     
    public List<PackingLibrary> filterDevices(List<PackingLibrary> packingLibraryList){

        //获取列装id
        List<Integer> packingIds = packingLibraryList.stream().map(PackingLibrary::getId).collect(Collectors.toList());
        //通过列装id 查询装备数量
//        long l = System.currentTimeMillis();
//        List<DeviceLibrary> allByPackingId2 = deviceLibraryService.findAllByPackingId2(packingIds);
//        System.out.println("查询时间"+(System.currentTimeMillis()-l));
//        Map<Integer, List<DeviceLibrary>> map = allByPackingId2.stream().collect(groupingBy(DeviceLibrary::getPackingId));
        //key为列装id
        Map<Integer, List<DeviceLibrary>> map = deviceLibraryService.findAllByPackingId3();
//        if (map.size()>0){
//            map.forEach(
//                    (k,v)->{
//                        if (map.get(k).size() == 0){
//                            Optional<PackingLibrary> byId = packingLibraryDao.findById(k);
//                            PackingLibrary packingLibrary = new PackingLibrary();
//                            if (byId.isPresent()){
//                                packingLibrary = byId.get();
//                            }
//                            packingLibraryList.remove(packingLibrary);
//                        }
//                    }
//            );
//        }
        List<Integer> notInPackingIds = new ArrayList<>();
//        List<PackingLibrary> notInPackingLibraries = new ArrayList<>();
        packingIds.forEach(
                integer -> {
                    if (!map.containsKey(integer)){
                        //加入不在集合中的
                        notInPackingIds.add(integer);
                    }
                }
        );
        //查询出不在集合中的列装
//        notInPackingLibraries = packingLibraryDao.findAllByIdIn(notInPackingIds);
        //进行移除
//        list.removeAll(notInPackingLibraries);
//        packingLibraryList.forEach(
//                packingLibrary -> {
//                    if (notInPackingIds.contains(packingLibrary.getId())){
//                        packingLibraryList.remove(packingLibrary);
//                    }
//                }
//        );
        packingIds.removeAll(notInPackingIds);
        return packingLibraryDao.findAllByIdIn(packingIds);
    }
}
