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

import com.fasterxml.jackson.core.type.TypeReference;
import com.tykj.dev.config.cache.ConfigCache;
import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.allot.service.AllotBackBillService;
import com.tykj.dev.device.allot.service.AllotBillService;
import com.tykj.dev.device.allot.subject.domin.AllotBill;
import com.tykj.dev.device.allot.subject.vo.*;
import com.tykj.dev.device.file.service.FilesUtil;
import com.tykj.dev.device.library.repository.DeviceLibraryDao;
import com.tykj.dev.device.library.service.DeviceLibraryService;
import com.tykj.dev.device.library.service.DeviceLogService;
import com.tykj.dev.device.library.subject.Dto.DeviceLogDto;
import com.tykj.dev.device.library.subject.domin.DeviceLibrary;
import com.tykj.dev.device.library.subject.vo.FileVo;
import com.tykj.dev.device.library.subject.vo.ScriptSaveVo;
import com.tykj.dev.device.packing.controller.PackingController;
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.task.repository.TaskDao;
import com.tykj.dev.device.task.service.TaskLogService;
import com.tykj.dev.device.task.service.TaskService;
import com.tykj.dev.device.task.subject.bto.TaskBto;
import com.tykj.dev.device.user.read.service.MessageService;
import com.tykj.dev.device.user.read.subject.bto.MessageBto;
import com.tykj.dev.device.user.subject.dao.UserDao;
import com.tykj.dev.device.user.subject.entity.User;
import com.tykj.dev.device.user.subject.service.AreaService;
import com.tykj.dev.device.user.subject.service.UnitsService;
import com.tykj.dev.device.user.subject.service.UserPublicService;
import com.tykj.dev.device.user.util.UserUtils;
import com.tykj.dev.misc.base.ResultObj;
import com.tykj.dev.misc.base.StatusEnum;
import com.tykj.dev.misc.exception.ApiException;
import com.tykj.dev.misc.utils.*;
import com.tykj.dev.rfid.service.InputOutputDeviceService;
import com.tykj.dev.socket.MyWebSocket;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author dengdiyi
 */
@RestController
@RequestMapping(value = "/allot")
@AutoDocument
@Api(tags = "装备配发模块", description = "装备配发接口")
@Slf4j
public class AllotBillController {

    @Autowired
    private AllotBillService allotBillService;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private TaskService taskService;

    @Autowired
    private DeviceLibraryService deviceLibraryService;

    @Autowired
    private DeviceLogService deviceLogService;

    @Autowired
    private TaskLogService taskLogService;

    @Autowired
    private UserPublicService userPublicService;

    @Autowired
    private MyWebSocket myWebSocket;

    @Autowired
    private Snowflake snowflake;

    @Autowired
    private InputOutputDeviceService inputOutputDeviceService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private AllotBackBillService allotBackBillService;

    @Autowired
    private DeviceLibraryDao deviceLibraryDao;

    @Autowired
    private UnitsService unitsService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private UserPublicService userService;

    @Autowired
    private ConfigCache configCache;

    @Autowired
    private TaskDao taskDao;

    @Autowired
    private PackingLibraryDao packingLibraryDao;

    @Autowired
    private PackingLibraryService packingLibraryService;

    @Autowired
    private PackingController packingController;

    @ApiOperation(value = "导入二维码获取配发装备", notes = "可以通过这个接口导入二维码获取配发装备")
    @PostMapping(value = "/load")
    public ResponseEntity loadDevice(@RequestBody RfidVo rfidVo) {
        String unit = userUtils.getCurrentUserUnitName();
        List<DeviceLibrary> deviceLibraries = new ArrayList<>();
        rfidVo.getRfidResultList().forEach(s -> {
            List<DeviceLibrary> deviceLibraries1 = deviceLibraryDao.getAllByRfidCardId(s);
            if (deviceLibraries1.isEmpty()) {
                throw new ApiException("系统中不存在rfid为" + s + "的装备");
            } else {
                if (!deviceLibraries1.get(0).getOwnUnit().equals(unit)) {
                    throw new ApiException("rfid为" + s + "的装备不属于本单位");
                } else if (deviceLibraries1.get(0).getLifeStatus() != 2) {
                    throw new ApiException("rfid为" + s + "的装备不在库");
                } else {
                    deviceLibraries.add(deviceLibraries1.get(0));
                }
            }
        });
        return ResponseEntity.ok(deviceLibraries);
    }

    @ApiOperation(value = "发起配发业务", notes = "可以通过这个接口发起配发任务")
    @PostMapping(value = "/addAllotBill")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity addAllotBill(@RequestBody @Validated AllotBillSaveVo allotBillSaveVo) {
        //判断发起配发的装备的生命状态
        if (allotBillSaveVo.getAllotCheckDetail() != null && allotBillSaveVo.getAllotCheckDetail().length() > 0) {
            deviceLibraryService.isInStockOrWaitRetired(StringSplitUtil.split(allotBillSaveVo.getAllotCheckDetail()));
        }
        //1.添加配发单
        AllotBill a = allotBillSaveVo.toDo();
        //保存后的实体
        AllotBill allotBillEntity;
        //如果是直接发起（不是草稿，没有taskId）,当前操作人为发件方A岗,添加账单
        if (allotBillSaveVo.getTaskId() == null) {
            a.setSendUseraId(userUtils.getCurrentUserId());
            allotBillEntity = allotBillService.addEntity(a);
        }
        //从草稿发起
        else {
            //获取草稿账单
            AllotBill allotBill = allotBillService.getOne(taskService.get(allotBillSaveVo.getTaskId()).getBillId());
            //copy非null相同字段值
            MapperUtils.copyNoNullProperties(a, allotBill);
            //判断是否取消上传申请单和批复单据
            if (a.getApplyFiles() == null || "".equals(a.getApplyFiles())) {
                allotBill.setApplyFiles(null);
            }
            if (a.getReplyFiles() == null || "".equals(a.getReplyFiles())) {
                allotBill.setReplyFiles(null);
            }
            allotBillEntity = allotBillService.update(allotBill);
        }
        //按照当前时间和保存账单的id拼接生成配发单号并保存
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int year = calendar.get(Calendar.YEAR);
        String num = "NO:第" + year + "PF" + allotBillEntity.getId() + "号";
        allotBillEntity.setNum(num);
        //生成接收方电子签章id
        Long signId2 = snowflake.creatNextId();
        //判断是否上传了发送方签章id
        if (allotBillSaveVo.getLeftSignatureId() != null) {
            allotBillEntity.setLeftSignatureId(allotBillSaveVo.getLeftSignatureId());
        }
        allotBillEntity.setRightSignatureId(signId2.toString());
        //判断是否提交签发人
        if (allotBillSaveVo.getSendUserbId() != null) {
            allotBillEntity.setSendUserbId(allotBillSaveVo.getSendUserbId());
            allotBillEntity.setAgent(userPublicService.getOne(allotBillSaveVo.getSendUserbId()).getName());
        }
        AllotBill allotBill = allotBillService.update(allotBillEntity);
        Integer billId = allotBillEntity.getId();
        Integer userId = userUtils.getCurrentUserId();
        String deviceIdDetail = allotBillEntity.getAllotCheckDetail();
        //2.发起任务
        //构建task涉及人员集合
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        userIds.add(0);
        //保存后的taskBto
        TaskBto saveEntity;
        //纵向配发
        if (allotBillSaveVo.getAllotType() == 1) {
            //直接发起
            if (allotBillSaveVo.getTaskId() == null) {
//                TaskBto taskBto = new TaskBto(StatusEnum.ALLOTING.id, allotBillSaveVo.getSendUnit() + "配发型号" + StringSplitUtil.stringListToString(allotBillSaveVo.getScriptSaveVos().stream().map(ScriptSaveVo::getModel).distinct().collect(Collectors.toList())) + "的装备共" + allotBillSaveVo.getAllotCount() + "件至" + allotBillSaveVo.getReceiveUnit(), null, ".", billId, 3, userPublicService.findUnitIdByName(allotBillSaveVo.getReceiveUnit()), 1, null, userIds);
                TaskBto taskBto = new TaskBto(StatusEnum.ALLOTING.id, "["+allotBillSaveVo.getReceiveUnit().substring(0,3)+"]型号" + StringSplitUtil.stringListToString(allotBillSaveVo.getScriptSaveVos().stream().map(ScriptSaveVo::getModel).distinct().collect(Collectors.toList())) + "的装备共" + allotBillSaveVo.getAllotCount() + "件" , null, ".", billId, 3, userPublicService.findUnitIdByName(allotBillSaveVo.getReceiveUnit()), 1, null, userIds);
                saveEntity = taskService.start(taskBto);
            }
            //从草稿发起
            else {
                TaskBto taskBto = taskService.get(allotBillSaveVo.getTaskId());
                taskBto.setTitle("["+allotBillSaveVo.getReceiveUnit().substring(0,3) + "]型号" + StringSplitUtil.stringListToString(allotBillSaveVo.getScriptSaveVos().stream().map(ScriptSaveVo::getModel).distinct().collect(Collectors.toList())) + "的装备共" + allotBillSaveVo.getAllotCount() + "件");
                //添加当前操作人为涉及人员
                TaskBto taskBto1 = taskService.addInvolveUser(taskBto, userId);
                //任务所属单位改为收件单位
                taskBto1.setOwnUnit(userPublicService.findUnitIdByName(allotBillSaveVo.getReceiveUnit()));
                //推动任务到配发中状态
                saveEntity = taskService.moveToSpecial(taskBto1, StatusEnum.ALLOTING, 0);
            }
            //生成发件方上传配发单的子任务
            TaskBto taskBto2 = new TaskBto(StatusEnum.WAIT_UPLOAD_ALLOT_FILE.id, "["+allotBillSaveVo.getReceiveUnit().substring(0,3) + "]型号" + StringSplitUtil.stringListToString(allotBillSaveVo.getScriptSaveVos().stream().map(ScriptSaveVo::getModel).distinct().collect(Collectors.toList())) + "的装备共" + allotBillSaveVo.getAllotCount() + "件", saveEntity.getId(), saveEntity.getNodeIdDetail() + saveEntity.getId() + ".", saveEntity.getBillId(), 3, userPublicService.findUnitIdByName(allotBillEntity.getSendUnit()), 0, null, Collections.singletonList(0));
            taskService.start(taskBto2);
        }
        //横向配发
        else {
            //直接发起
            if (allotBillSaveVo.getTaskId() == null) {
                TaskBto taskBto2 = new TaskBto(StatusEnum.WAIT_UPLOAD_CROSS_FILE.id,  "["+allotBillSaveVo.getReceiveUnit().substring(0,3) + "]型号" + StringSplitUtil.stringListToString(allotBillSaveVo.getScriptSaveVos().stream().map(ScriptSaveVo::getModel).distinct().collect(Collectors.toList())) + "的装备共" + allotBillSaveVo.getAllotCount() + "件", null, ".", billId, 3, userPublicService.findUnitIdByName(allotBillEntity.getSendUnit()), 1, "country", userIds);
                saveEntity = taskService.start(taskBto2);
            }
            //从草稿发起
            else {
                TaskBto taskBto = taskService.get(allotBillSaveVo.getTaskId());
                taskBto.setTitle("["+allotBillSaveVo.getReceiveUnit().substring(0,3) + "]型号" + StringSplitUtil.stringListToString(allotBillSaveVo.getScriptSaveVos().stream().map(ScriptSaveVo::getModel).distinct().collect(Collectors.toList())) + "的装备共" + allotBillSaveVo.getAllotCount() + "件");
                taskBto.setCustomInfo("country");
                //添加当前操作人为涉及人员
                TaskBto taskBto1 = taskService.addInvolveUser(taskBto, userId);
                //推动任务到配发中状态
                saveEntity = taskService.moveToSpecial(taskBto1, StatusEnum.WAIT_UPLOAD_CROSS_FILE, userId);
            }
        }
        List<FileVo> fileVoList = new ArrayList<>();
        //分解装备id字符串
        String[] strings = deviceIdDetail.split("x");
        //存放所有出库装备id
        List<Integer> ids = new ArrayList<>();
        //横纵向列装转换map（key:转换前列装id,value:转换后列装id）,减少数据库查询
        Map<Integer, Integer> changeMap = new HashMap<>();

        Map<String, PackingLibrary> packingLibraryHashMap = new HashMap<>();
        if (unitsService.findbyName(allotBillSaveVo.getSendUnit()).getLevel() == 1) {
            createPacking(strings, allotBillSaveVo, packingLibraryHashMap);
        }

        for (String s : strings) {
            //最后一位原来为装备扫码结果，已弃用
            if (s.length() >= 2) {
                //去掉最后一位得到装备id
                Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                ids.add(id);
                //改变装备状态
                DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                //纵向配发
                Integer matchingRange = allotBillSaveVo.getMatchingRange();
                Integer matchingRange1 = deviceLibraryEntity.getMatchingRange();

                if (matchingRange == 1 || matchingRange == 2 || matchingRange == 3) {
                    allotmentEquipment(id, changeMap, deviceLibraryEntity, packingLibraryHashMap, matchingRange, fileVoList, saveEntity);
                }
                //横向配发
//                else if (matchingRange == 3) {
//                    //如果当前装备的配用范围不是省以下横向
//                    if (deviceLibraryEntity.getMatchingRange() != 3) {
//                        //判断changeMap是否存在该列装的转换信息
//                        PackingLibrary packingLibrary1 = packingLibraryHashMap.get(deviceLibraryEntity.getModel() + deviceLibraryEntity.getName() + 3);
//                        //不存在直接抛出异常
//                        if (packingLibrary1 != null) {
//                            changeMap.put(deviceLibraryEntity.getPackingId(), packingLibrary1.getId());
//                            deviceLibraryEntity.setPackingId(packingLibrary1.getId());
//                            deviceLibraryEntity.setMatchingRange(3);
//                        } else {
//                            log.info("[配发] 没有在packingLibraryHashMap找到key:{}的列装", deviceLibraryEntity.getModel() + deviceLibraryEntity.getName() + 3);
//                        }
//                    }
//                    //存装备日志
//                    DeviceLogDto deviceLogDto = new DeviceLogDto(id, "横向配发将所属列装由" + deviceLibraryEntity.getMatchingRangeName() + "的列装改为" + configCache.getMatchingRangeMap().get(3) + "的列装", fileVoList, saveEntity.getId(), null);
//                    deviceLogService.addLog(deviceLogDto);
//
//                    //横向直接改变装备所属所在
//                    deviceLibraryEntity.setLocationUnit(allotBillSaveVo.getReceiveUnit());
//                    deviceLibraryEntity.setOwnUnit(allotBillSaveVo.getReceiveUnit());
//                }

                deviceLibraryEntity.setLifeStatus(3);
                //改变装备管理状态为不在本单位
                deviceLibraryEntity.setManageStatus(0);
                deviceLibraryService.update(deviceLibraryEntity);
                //存装备日志
//                DeviceLogDto deviceLogDto = new DeviceLogDto(id, "对" + allotBillEntity.getReceiveUnit() + "发起配发", fileVoList, saveEntity.getId(), null);
                DeviceLogDto deviceLogDto = new DeviceLogDto(id, "对" + allotBillEntity.getReceiveUnit() + "发起配发", fileVoList, saveEntity.getId(), saveEntity.getId());
                deviceLogService.addLog(deviceLogDto);
            }
        }

        //添加出库白名单
        inputOutputDeviceService.addWhiteDevices(ids, userUtils.getCurrentUnitId(), 1);
        //发送阅知信息
        List<Integer> idList = userPublicService.findOtherUser(userId);
        //纵向配发阅知要发给收件单位的人
        if (allotBillSaveVo.getAllotType() == 1) {
            idList.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(allotBillEntity.getReceiveUnit())).stream()
                    .map(User::getUserId)
                    .collect(Collectors.toList()));
        }
        //给被选签发人推阅知
//        if (allotBillSaveVo.getSendUserbId() != null) {
//            List<Integer> idList1 = new ArrayList<>();
//            idList1.add(allotBillSaveVo.getSendUserbId());
//            MessageBto messageBto = new MessageBto(saveEntity.getId(), saveEntity.getBusinessType(), "被选为签发人", idList1, 1);
//            messageService.add(messageBto);
//        }
        //给同单位专管员和收件单位专管员推阅知
        MessageBto messageBto = new MessageBto(saveEntity.getId(), saveEntity.getBusinessType(), "对" + userPublicService.getAreaNameByUnitName(allotBillEntity.getReceiveUnit()) + "发起配发", idList, 1);
        messageService.add(messageBto);
        log.info("[配发模块]:" + allotBillEntity.getSendUnit() + "对" + allotBillEntity.getReceiveUnit() + "发起配发");
        myWebSocket.sendMessage1();
        //set配发单四个人中文名
        allotBill.setSenderUserA(userService.getOne(allotBill.getSendUseraId()).getName());
        allotBill.setSenderUserB(allotBill.getAgent());
        if (allotBill.getReceiveUseraId() != null) {
            allotBill.setReceiveUserA(userService.getOne(allotBill.getReceiveUseraId()).getName());
        }
        if (allotBill.getReceiveUserbId() != null) {
            allotBill.setReceiveUserB(userService.getOne(allotBill.getReceiveUserbId()).getName());
        }
        //set单据集合
        allotBill.setSendFileList(FilesUtil.stringFileToList(allotBill.getSendFiles()));
        allotBill.setReplyFileList(FilesUtil.stringFileToList(allotBill.getReplyFiles()));
        //
        allotBill.setTaskId(saveEntity.getId());
        //输出配发单给前端
        return ResponseEntity.ok(new ResultObj(allotBill, "发起成功"));
    }

    @ApiOperation(value = "接收配发装备", notes = "可以通过这个接口接收配发装备")
    @PostMapping(value = "/receiveDevice")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity receiveDevice(@RequestBody @Validated AllotReceiveVo allotReceiveVo) {
        //当前操作人id
        Integer userId = userUtils.getCurrentUserId();
        //获取当前任务
        TaskBto taskBto = taskService.get(allotReceiveVo.getTaskId());
        //判断当前任务状态是否已经被操作
        List<StatusEnum> statusEnums = Arrays.asList(StatusEnum.ALLOTING, StatusEnum.WAIT_SIGN);
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(), statusEnums);
        //配发单
        AllotBill allotBillEntity = allotBillService.getOne(taskBto.getBillId());
        //签发人是否上传
        boolean sendbIsExist = allotBillEntity.getSendUserbId() != null;
        //上传文件存储集合
        List<FileVo> fileVoList = new ArrayList<>();
        if (allotReceiveVo.getReceiveFileList() != null && allotReceiveVo.getReceiveFileList().size() > 0) {
            allotReceiveVo.getReceiveFileList().forEach(fileRet -> {
                fileVoList.add(new FileVo("配发单", fileRet.getName(), fileRet.getPreviewPath()));
            });
            allotBillEntity.setReceiveFiles(FilesUtil.stringFileToList(allotReceiveVo.getReceiveFileList()));
        }
        //是否上传了收件单位签章id
        if (allotReceiveVo.getRightSignatureId() != null && !"".equals(allotReceiveVo.getRightSignatureId())) {
            allotBillEntity.setRightSignatureId(allotReceiveVo.getRightSignatureId());
        }
        //更新账单状态为配发完成
        allotBillEntity.setAllotStatus(5);
        //复制非空相同字段
        MapperUtils.copyNoNullProperties(allotReceiveVo, allotBillEntity);
        //set接收时间
        allotBillEntity.setReceiveTime(TimestampUtil.getCurrentTimestamp());
        //如果收件方A岗未上传，默认为当前操作人
        if (allotBillEntity.getReceiveUseraId() == null) {
            allotBillEntity.setReceiveUseraId(userId);
        }
        //判断是否上传发件方签发人
        if (allotReceiveVo.getSendUserbId() != null) {
            allotBillEntity.setSendUserbId(allotReceiveVo.getSendUserbId());
            allotBillEntity.setAgent(userPublicService.getOne(allotReceiveVo.getSendUserbId()).getName());
        }
        allotBillService.update(allotBillEntity);
        //添加当前用户为涉及人员
        taskService.addInvolveUser(taskBto, userId);
        //如果上传了单据或双方都盖章，该业务和子业务都办结
        if (allotReceiveVo.getStatus() == 0) {
            taskService.moveToEnd(taskBto);
            //子任务完结
            taskService.moveAllSonNodeToEnd(taskBto.getId());
        } else {
            //推至待上传签收单的状态
            taskService.moveToSpecial(taskBto, StatusEnum.WAIT_UPLOAD_ALLOT_RECEIVE_FILE, 0);
        }
        //分隔装备id信息
        String deviceIdDetail = allotReceiveVo.getReceiveCheckDetail();
        String[] strings = deviceIdDetail.split("x");
        for (String s : strings) {
            if (s.length() >= 2) {
                //接收无误
                if ("1".equals(s.substring(s.length() - 1))) {
                    //装备id
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    //改变装备状态、所属所在
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLocationUnit(userUtils.getCurrentUserUnitName());
                    deviceLibraryEntity.setLifeStatus(2);
                    deviceLibraryEntity.setOwnUnit(userUtils.getCurrentUserUnitName());
                    deviceLibraryEntity.setManageStatus(1);
                    //如果接收时填写了生产号
                    if (allotReceiveVo.getMap().get(id) != null) {
                        deviceLibraryEntity.setProdNumber(allotReceiveVo.getMap().get(id));
                    }
                    //存装备日志
//                    DeviceLogDto deviceLogDto = new DeviceLogDto(id, "接收并发起入库", fileVoList, taskBto.getId(), null);
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id, "接收并发起入库", fileVoList, taskBto.getId(), taskBto.getId());
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
                //接收缺失
                if ("0".equals(s.substring(s.length() - 1))) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    //改变装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(11);
                    //存装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id, "接收入库丢失", fileVoList, taskBto.getId(), taskBto.getId());
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
        }
        //发送阅知信息
        List<Integer> ids = userPublicService.findOtherUser(userId);
        ids.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(allotBillEntity.getSendUnit())).stream()
                .map(User::getUserId)
                .collect(Collectors.toList()));
        //经办人阅知
//        if (allotReceiveVo.getReceiveUserbId()!=null) {
//            List<Integer> idList1 = new ArrayList<>();
//            idList1.add(allotReceiveVo.getReceiveUserbId());
//            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", idList1, 1);
//            messageService.add(messageBto);
//        }
        //签发人阅知
        if (allotReceiveVo.getSendUserbId() != null && sendbIsExist) {
            List<Integer> idList1 = new ArrayList<>();
            idList1.add(allotReceiveVo.getSendUserbId());
            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为签发人", idList1, 1);
            messageService.add(messageBto);
        }
        //根据status判断是否业务完结，发送不同的阅知message
        String message = allotReceiveVo.getStatus() == 0 ? "业务办结" : "接收配发装备";
        MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), message, ids, 1);
        messageService.add(messageBto);
        log.info("[配发模块]:接收并发起入库");
        myWebSocket.sendMessage1();
        return ResponseEntity.ok("配发接收入库");
    }

    @ApiOperation(value = "保存配发操作(草稿)", notes = "可以通过这个接口保存配发操作")
    @PostMapping(value = "/saveAllotBill")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity saveAllotBill(@RequestBody AllotBillSaveVo allotBillSaveVo) {
        //判断装备的生命状态是否能配发
        if (allotBillSaveVo.getAllotCheckDetail() != null && allotBillSaveVo.getAllotCheckDetail().length() > 0) {
            deviceLibraryService.isInStockOrWaitRetired(StringSplitUtil.split(allotBillSaveVo.getAllotCheckDetail()));
        }
        //第一次保存（没有taskId）
        if (allotBillSaveVo.getTaskId() == null) {
            Integer userId = userUtils.getCurrentUserId();
            //保存入库单
            List<Integer> userIds = new ArrayList<>();
            userIds.add(userId);
            //转Do
            AllotBill allotBill1 = allotBillSaveVo.toDo();
            //状态设为草稿
            allotBill1.setAllotStatus(0);
            //发件A岗设为当前操作人
            allotBill1.setSendUseraId(userId);
            AllotBill allotBill = allotBillService.addEntity(allotBill1);
            //发起草稿任务
            TaskBto taskBto = new TaskBto(StatusEnum.ALLOT_DRAFT.id, "["+allotBillSaveVo.getReceiveUnit().substring(0,3)+ "]型号" + StringSplitUtil.stringListToString(allotBillSaveVo.getScriptSaveVos().stream().map(ScriptSaveVo::getModel).distinct().collect(Collectors.toList())) + "的装备共" + allotBillSaveVo.getAllotCount() + "件", null, ".", allotBill.getId(), 3, userUtils.getCurrentUnitId(), 0, null, userIds);
            TaskBto taskBto1 = taskService.start(taskBto);
            //返回保存成功的id
            Integer id = taskBto1.getId();
            myWebSocket.sendMessage1();
            return ResponseEntity.ok("保存成功" + id);
        } else {
            //更新账单
            TaskBto taskBto = taskService.get(allotBillSaveVo.getTaskId());
            AllotBill allotBill = allotBillService.getOne(taskBto.getBillId());
            AllotBill allotBill1 = allotBillSaveVo.toDo();
            //状态设为草稿
            allotBill1.setAllotStatus(0);
            MapperUtils.copyNoNullProperties(allotBill1, allotBill);
            allotBillService.update(allotBill);
            return ResponseEntity.ok("更新成功" + taskBto.getId());
        }
    }

    @ApiOperation(value = "删除配发单草稿", notes = "可以通过这个接口删除配发单草稿")
    @PostMapping(value = "/deleteAllotBill/{taskId}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity deleteAllotBill(@PathVariable("taskId") int taskId) {
        //任务封存
        TaskBto taskBto = taskService.get(taskId);
        TaskBto taskBto1 = taskService.addInvolveUser(taskBto, userUtils.getCurrentUserId());
        taskService.moveToArchive(taskBto1);
        myWebSocket.sendMessage1();
        return ResponseEntity.ok("删除成功");
    }

    @ApiOperation(value = "申请电子签章", notes = "可以通过这个接口申请电子签章")
    @PostMapping(value = "/applySign/{taskId}/{userId}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity applySign(@PathVariable("taskId") int taskId, @PathVariable("userId") int userId) {
        //获取任务和账单
        TaskBto taskBto = taskService.get(taskId);
        AllotBill allotBill = allotBillService.getOne(taskBto.getBillId());
        //如果是收件方申请电子签章
        if (allotBill.getAllotStatus() != 0) {
            //当前用户设为接收A岗
            allotBill.setReceiveUseraId(userUtils.getCurrentUserId());
            allotBillService.update(allotBill);
        }
        //推动任务到盖章待审核状态
        taskService.moveToSpecial(taskBto, StatusEnum.SIGN_WAIT_CONFIRM, userId);
        myWebSocket.sendMessage1();
        return ResponseEntity.ok("申请成功");
    }

    @ApiOperation(value = "申请电子签章审核", notes = "可以通过这个接口申请电子签章审核")
    @PostMapping(value = "/applySignConfirm/{taskId}/{status}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity applySignConfirm(@PathVariable("taskId") int taskId, @PathVariable("status") int status) {
        //获取任务和单据
        TaskBto taskBto = taskService.get(taskId);
        AllotBill allotBill = allotBillService.getOne(taskBto.getBillId());
        //如果同意
        if (status == 1) {
            //推动任务到等待盖章状态
            taskService.moveToSpecial(taskBto, StatusEnum.WAIT_SIGN);
            //发件方盖章
            if (allotBill.getAllotStatus() == 0) {
                //当前用户设为签发人
                allotBill.setSendUserbId(userUtils.getCurrentUserId());
                allotBill.setAgent(userUtils.getCurrentName());
            }
            //收件方盖章
            else {
                //当前用户设为接收方B岗
                allotBill.setReceiveUserbId(userUtils.getCurrentUserId());
            }
            allotBillService.update(allotBill);
        } else {
            //发件方盖章不同意任务返回草稿状态
            if (allotBill.getAllotStatus() == 0) {
                taskService.moveToSpecial(taskBto, StatusEnum.ALLOT_DRAFT, taskBto.getCreateUserId());
            }
            //收件方返回到待入库状态
            else {
                taskService.moveToSpecial(taskBto, StatusEnum.ALLOTING, allotBill.getReceiveUseraId());
            }
        }
        myWebSocket.sendMessage1();
        return ResponseEntity.ok("申请成功");
    }

    @ApiOperation(value = "查询配发草稿详情", notes = "可以通过这个接口查询配发草稿详情")
    @PostMapping(value = "/selectAllotDetail/{taskId}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity selectAllotDetail(@PathVariable("taskId") int taskId) {
        //获取业务和账单
        TaskBto taskBto = taskService.get(taskId);
        AllotBill allotBillEntity = allotBillService.getOne(taskBto.getBillId());
        //将用户id转为名字
        if (allotBillEntity.getSendUseraId() != null) {
            allotBillEntity.setSenderUserA(userPublicService.getOne(allotBillEntity.getSendUseraId()).getName());
        }
        if (allotBillEntity.getSendUserbId() != null) {
            allotBillEntity.setSenderUserB(userPublicService.getOne(allotBillEntity.getSendUserbId()).getName());
        }
        if (allotBillEntity.getReceiveUseraId() != null) {
            allotBillEntity.setReceiveUserA(userPublicService.getOne(allotBillEntity.getReceiveUseraId()).getName());
        }
        if (allotBillEntity.getReceiveUserbId() != null) {
            allotBillEntity.setReceiveUserB(userPublicService.getOne(allotBillEntity.getReceiveUserbId()).getName());
        }
        //分隔装备id得到装备信息
        if (allotBillEntity.getAllotCheckDetail() != null) {
            List<Integer> ids = StringSplitUtil.split(allotBillEntity.getAllotCheckDetail());
            List<DeviceLibrary> deviceLibraryList = new ArrayList<>();
            ids.forEach(integer -> deviceLibraryList.add(deviceLibraryService.getOne(integer)));
            allotBillEntity.setDeviceLibraries(deviceLibraryList);
        }
        //设置申请和批复文件列表
        allotBillEntity.setReplyFileList(FilesUtil.stringFileToList(allotBillEntity.getReplyFiles()));
        allotBillEntity.setApplyFileList(FilesUtil.stringFileToList(allotBillEntity.getApplyFiles()));
        //返回前端单据json详情
        if (allotBillEntity.getScriptJson() != null) {
            allotBillEntity.setScripts(JacksonUtil.readValue(allotBillEntity.getScriptJson(), new TypeReference<List<ScriptSaveVo>>() {
            }));
        }
        return ResponseEntity.ok(allotBillEntity);
    }

    @ApiOperation(value = "上传接收方配发单", notes = "可以通过这个接口上传送修单")
    @PostMapping(value = "/uploadAllotBill")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity uploadAllotBill(@RequestBody @Validated FileUploadVo fileUploadVo) {
        TaskBto taskBto = taskService.get(fileUploadVo.getTaskId());
        //判断业务状态是否被操作
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(), StatusEnum.WAIT_UPLOAD_ALLOT_RECEIVE_FILE);
        Integer userId = userUtils.getCurrentUserId();
        taskService.addInvolveUser(taskBto, userId);
        //业务和子业务办结
        taskService.moveToEnd(taskBto);
        taskService.moveAllSonNodeToEnd(taskBto.getId());
        AllotBill allotBill = allotBillService.getOne(taskBto.getBillId());
        //是否上传发件方签发人
        if (fileUploadVo.getSendUserbId() != null) {
            allotBill.setSendUserbId(fileUploadVo.getSendUserbId());
            allotBill.setAgent(userPublicService.getOne(fileUploadVo.getSendUserbId()).getName());
        }
        //是否上传接收方B岗
//        if (fileUploadVo.getReceiveUserbId()!=null){
//            allotBill.setReceiveUserbId(fileUploadVo.getReceiveUserbId());
//            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", Collections.singletonList(fileUploadVo.getReceiveUserbId()), 1);
//            messageService.add(messageBto);
//        }
        //文件列表
        List<FileVo> fileVoList = new ArrayList<>();
        if (fileUploadVo.getReceiveFileList() != null && fileUploadVo.getReceiveFileList().size() > 0) {
            fileUploadVo.getReceiveFileList().forEach(fileRet -> {
                fileVoList.add(new FileVo("配发单", fileRet.getName(), fileRet.getPreviewPath()));
            });
            allotBill.setReceiveFiles(FilesUtil.stringFileToList(fileUploadVo.getReceiveFileList()));
        }
        //是否上传接收方B岗
        if (fileUploadVo.getReceiveUserbId() != null) {
            allotBill.setReceiveUserbId(fileUploadVo.getReceiveUserbId());
        }
        allotBillService.update(allotBill);
        //添加装备日志
        List<Integer> deviceIds = StringSplitUtil.split(allotBill.getAllotCheckDetail());
        deviceIds.forEach(integer -> {
            //存装备日志
//            DeviceLogDto deviceLogDto = new DeviceLogDto(integer, "上传配发单据", fileVoList, taskBto.getId(), null);
            DeviceLogDto deviceLogDto = new DeviceLogDto(integer, "上传配发单据", fileVoList, taskBto.getId(), taskBto.getId());
            deviceLogService.addLog(deviceLogDto);
        });
        //签发人阅知
        if (fileUploadVo.getSendUserbId() != null) {
            List<Integer> idList1 = new ArrayList<>();
            idList1.add(fileUploadVo.getSendUserbId());
            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为签发人", idList1, 1);
            messageService.add(messageBto);
        }
        //发送阅知信息
        List<Integer> ids = userPublicService.findOtherUser(userId);
        ids.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(allotBill.getSendUnit())).stream()
                .map(User::getUserId)
                .collect(Collectors.toList()));
        MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "业务办结", ids, 1);
        messageService.add(messageBto);
        return ResponseEntity.ok("上传成功");
    }

    @ApiOperation(value = "上传发送方配发单", notes = "上传配发单")
    @PostMapping(value = "/uploadFile")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity uploadFile(@RequestBody @Validated com.tykj.dev.device.allot.subject.vo.FileVo fileVo) {
        //获取task
        TaskBto taskBto = taskService.get(fileVo.getTaskId());
        taskService.addInvolveUser(taskBto, userUtils.getCurrentUserId());
        //判断业务状态是否被操作
        List<StatusEnum> statusEnums = new ArrayList<>();
        statusEnums.add(StatusEnum.WAIT_UPLOAD_CROSS_FILE);//待上传横向配发单
        statusEnums.add(StatusEnum.WAIT_UPLOAD_ALLOT_FILE);//待上传纵向配发单
        statusEnums.add(StatusEnum.ALLOTING);
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(), statusEnums);
        //获取账单
        AllotBill allotBill = allotBillService.getOne(taskBto.getBillId());
        //存放接收方经办人id
        List<Integer> idList = new ArrayList<>();
        if (fileVo.getReceiveUseraId() != null) {
            allotBill.setReceiveUseraId(fileVo.getReceiveUseraId());
            idList.add(fileVo.getReceiveUseraId());
        }
        if (fileVo.getReceiveUserbId() != null) {
            allotBill.setReceiveUserbId(fileVo.getReceiveUserbId());
            idList.add(fileVo.getReceiveUserbId());
        }
        //签发人阅知
        if (fileVo.getSendUserbId() != null) {
            allotBill.setSendUserbId(fileVo.getSendUserbId());
            allotBill.setAgent(userPublicService.getOne(fileVo.getSendUserbId()).getName());
            List<Integer> idList1 = new ArrayList<>();
            idList1.add(fileVo.getSendUserbId());
            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为签发人", idList1, 1);
            messageService.add(messageBto);
        }
        //保存账单
        //回执单
        allotBill.setSendFiles(FilesUtil.stringFileToList(fileVo.getAllotFiles()));
        //状态配发完成
        allotBill.setAllotStatus(5);
        //接收时间
        allotBill.setReceiveTime(TimestampUtil.getCurrentTimestamp());
        allotBillService.update(allotBill);
        //装备Id集合
        List<Integer> ids = StringSplitUtil.split(allotBill.getAllotCheckDetail());
        //业务完结
        taskService.moveToEnd(taskBto);
        //主业务完结
        if (taskBto.getParentTaskId() != null) {
            taskService.moveToEnd(taskService.get(taskBto.getParentTaskId()));
        }
        //添加装备日志，改变装备状态
        List<FileVo> fileVoList = new ArrayList<>();
        fileVo.getAllotFiles().forEach(fileRet -> fileVoList.add(new FileVo("配发单", fileRet.getName(), fileRet.getPreviewPath())));
        ids.forEach(integer -> {
//            DeviceLogDto deviceLogDto = new DeviceLogDto(integer, "上传配发单", fileVoList, taskBto.getId(), null);
            DeviceLogDto deviceLogDto = new DeviceLogDto(integer, "上传配发单", fileVoList, taskBto.getId(), taskBto.getId());
            deviceLogService.addLog(deviceLogDto);
            DeviceLibrary deviceLibrary = deviceLibraryService.getOne(integer);
            deviceLibrary.setLocationUnit(allotBill.getReceiveUnit());
            deviceLibrary.setLifeStatus(2);
            deviceLibrary.setOwnUnit(allotBill.getReceiveUnit());
            deviceLibrary.setManageStatus(1);
            deviceLibraryService.update(deviceLibrary);
        });
        //经办人阅知
//        if (idList.size()>0) {
//            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", idList, 1);
//            messageService.add(messageBto);
//        }
        //发送阅知信息
        List<Integer> userIds = userPublicService.findOtherUser(userUtils.getCurrentUserId());
        userIds.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(allotBill.getReceiveUnit())).stream()
                .map(User::getUserId)
                .collect(Collectors.toList()));
        MessageBto messageBto = new MessageBto(taskBto.getParentTaskId(), taskBto.getBusinessType(), "业务办结", userIds, 1);
        messageService.add(messageBto);
        return ResponseEntity.ok("OK");
    }

    @ApiOperation(value = "上传发送方签发人", notes = "上传发送方签发人")
    @PostMapping(value = "/updateAgent")//不用了
    public ResponseEntity updateAgent(@RequestBody AgentVo agentVo) {
        //获取业务
        TaskBto taskBto = taskService.get(agentVo.getId());
        List<Integer> idList = new ArrayList<>();
        idList.add(agentVo.getSendUserbId());
        //签发人阅知
        MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为签发人", idList, 1);
        messageService.add(messageBto);
        //账单保存签发人
        AllotBill allotBill = allotBillService.getOne(taskBto.getBillId());
        allotBill.setAgent(agentVo.getName());
        allotBill.setSendUserbId(agentVo.getSendUserbId());
        return ResponseEntity.ok(allotBillService.update(allotBill));
    }


    @ApiOperation(value = "配发撤回", notes = "根据任务id撤回配发")
    @GetMapping("/revokeTask/taskId")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity revokeTask(Integer taskId) {

        //根据任务id查询子任务 发件方是子任务  收件方是主任务
        TaskBto taskBto = taskService.get(taskId);
        Integer parentTaskId = taskBto.getParentTaskId();

        TaskBto parentTask = taskService.get(parentTaskId);
        //父任务未被完成 可以被撤回
        Integer billId = taskBto.getBillId();
        String title = taskBto.getTitle();

        AllotBill allotBill = allotBillService.getOne(billId);
        Integer currentUserId = userUtils.getCurrentUserId();
        List<Integer> idList = userPublicService.findOtherUser(currentUserId);
        //找到收件方的阅知
        MessageBto messageBto1 = messageService.findByTaskId(parentTaskId).parse2Bto();
        //纵向配发阅知要发给收件单位的人
        if (allotBill.getAllotType() == 1) {
            idList.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(allotBill.getReceiveUnit())).stream()
                    .map(User::getUserId)
                    .collect(Collectors.toList()));
        }
        //给同单位专管员和收件单位专管员推阅知
//        messageBto1.setContent(title.substring(0,4)+"撤回"+title.substring(4));
        messageBto1.setContent("撤回任务:" + title);
        MessageBto messageBto = new MessageBto(-1, parentTask.getBusinessType(), messageBto1.getContent(), idList, 1);
        BeanUtils.copyProperties(messageBto1,messageBto);
        messageBto.setTaskId(-1);
        messageService.add(messageBto);
        myWebSocket.sendMessage1();
        //将任务都完结
        taskService.moveToRevoke(taskBto);
        taskService.moveToRevoke(parentTask);
        if (allotBill.getAllotCheckDetail() != null) {
            List<Integer> ids = StringSplitUtil.split(allotBill.getAllotCheckDetail());
            //所有的装备
            List<DeviceLibrary> deviceLibraryList;
            //所有的装备日志
            List<DeviceLogDto> deviceLogDtos = new ArrayList<>();

            ids.forEach(id -> {
                DeviceLibrary deviceLibrary = deviceLibraryService.getOne(id);
                //添加装备日志
                DeviceLogDto deviceLogDto = new DeviceLogDto(id, "对" + deviceLibrary.getName() + "配发撤回", null, null, null);
                deviceLogDtos.add(deviceLogDto);
            });

            //设置装备为在库
            deviceLibraryService.updateLifeStatus2(2,ids);
            deviceLibraryList = deviceLibraryService.findByIds(ids);

            //添加日志
            deviceLogService.addAllLog(deviceLogDtos);

            allotBill.setDeviceLibraries(deviceLibraryList);
            allotBillService.delete(allotBill.getId());

        }
        return ResponseEntity.ok(messageBto);

    }

    //递归取出最大目录
    public PackingLibrary getPackingLibrary(PackingLibrary packingLibrary) {
        Integer partParentId = packingLibrary.getPartParentId();
        PackingLibrary one = packingLibraryService.getOne(partParentId);
        if (one.getIsRoot() == 0) {
            PackingLibrary parentPackingLibrary = packingLibraryService.getOne(partParentId);
            return getPackingLibrary(parentPackingLibrary);
        } else {
            return packingLibrary;
        }
    }

    public void getPackingLibrary2(PackingLibrary packingLibrary, Integer newId, Integer matchingRange, Map<String, PackingLibrary> packingLibraryMap) {

        PackingLibrary newPackingLibrary = new PackingLibrary();
        BeanUtils.copyProperties(packingLibrary, newPackingLibrary);
        newPackingLibrary.setId(null);
        newPackingLibrary.setPartParentId(newId);
        newPackingLibrary.setMatchingRange(matchingRange);
        packingLibrary.setPackingStatus(2);
        packingLibraryService.addAllotPacking(newPackingLibrary);
        packingLibraryMap.put(newPackingLibrary.getModel() + newPackingLibrary.getName() + newPackingLibrary.getMatchingRange(), newPackingLibrary);
        List<PackingLibrary> packingLibraryList = packingLibraryService.getAllByPartPackingId(packingLibrary.getId());
        if (packingLibraryList != null || packingLibraryList.size() != 0) {
            packingLibraryList.forEach(packingLibrary1 -> {
                getPackingLibrary2(packingLibrary1, newPackingLibrary.getId(), matchingRange, packingLibraryMap);
            });
        }

    }


    public void createPacking(String[] strings, AllotBillSaveVo allotBillSaveVo, Map<String, PackingLibrary> packingLibraryHashMap) {
        for (String s : strings) {
            //最后一位原来为装备扫码结果，已弃用
            if (s.length() >= 2) {
                //去掉最后一位得到装备id
                Integer id = Integer.parseInt(s.substring(0, s.length() - 1));

                //改变装备状态
                DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);

                Integer matchingRange = allotBillSaveVo.getMatchingRange();
                //装备的配用范围
                Integer matchingRange1 = deviceLibraryEntity.getMatchingRange();

                if (matchingRange == 1) {
                    isMatching(1, matchingRange1, deviceLibraryEntity, packingLibraryHashMap);
                }
                if (matchingRange == 2) {
                    isMatching(2, matchingRange1, deviceLibraryEntity, packingLibraryHashMap);
                }
                if (matchingRange == 3) {
                    isMatching(3, matchingRange1, deviceLibraryEntity, packingLibraryHashMap);
                }
            }
        }
    }

    public void allotmentOfVariousRangeEquipment(DeviceLibrary deviceLibraryEntity, Map<String, PackingLibrary> packingLibraryHashMap, Integer matchingRange) {
        //判断是否存在省以下纵向的相同列装装备
        PackingLibrary packingLibrary = packingLibraryService.getOne(deviceLibraryEntity.getPackingId());
        PackingLibrary packingLibrary1 = null;
        if (packingLibrary.getIsPart() == 1) {
            //拿到装备目录
            PackingLibrary devLibrary = getPackingLibrary(packingLibrary);

            List<PackingLibrary> packingLibraries = packingLibraryService.findSamePacking1(devLibrary.getPartParentId(), matchingRange, devLibrary.getType(), packingLibrary.getStyle(), devLibrary.getName(), packingLibrary.getSecretLevel(), devLibrary.getInvisibleRange());
            if (packingLibraries != null) {
                List<PackingLibrary> collect = packingLibraries.stream().sorted(Comparator.comparing(PackingLibrary::getCreateTime).reversed()).collect(Collectors.toList());

                packingLibrary1 = collect.get(0);
            }
        } else {
            packingLibrary1 = packingLibraryService.findSamePackingInPackingStatus(packingLibrary.getPartParentId(), matchingRange, packingLibrary.getType(), packingLibrary.getStyle(), packingLibrary.getName(), packingLibrary.getSecretLevel(), packingLibrary.getInvisibleRange());
        }
        //不存在直接抛出异常
        if (packingLibrary1 == null) {
                PackingLibrary library = getPackingLibrary(packingLibrary);
                getPackingLibrary2(library, library.getPartParentId(), matchingRange, packingLibraryHashMap);
        } else {

            if (packingLibrary1.getPackingStatus() == 4 || packingLibrary1.getPackingStatus() == 3){
                //撤回列装
                List<Integer> ids =  new ArrayList<>();
                ids.add(packingLibrary1.getId());
                packingController.remove(ids);
            }
            packingLibraryHashMap.put(packingLibrary1.getModel() + packingLibrary1.getName() + matchingRange, packingLibrary1);
        }
    }

    public void isMatching(Integer matchingRange, Integer matchingRange1, DeviceLibrary deviceLibraryEntity, Map<String, PackingLibrary> packingLibraryHashMap) {
        //如果当前装备的配用范围不是省以下纵向
        if (matchingRange1 != matchingRange) {
            allotmentOfVariousRangeEquipment(deviceLibraryEntity, packingLibraryHashMap, matchingRange);
        }
    }

    public void allotmentEquipment(Integer id, Map<Integer, Integer> changeMap, DeviceLibrary deviceLibraryEntity, Map<String, PackingLibrary> packingLibraryHashMap, Integer matchingRange, List<FileVo> fileVoList, TaskBto saveEntity) {
        //如果当前装备的配用范围不是省以下纵向
        if (deviceLibraryEntity.getMatchingRange() != matchingRange) {
            //判断changeMap是否存在该列装的转换信息
            //判断是否存在省以下纵向的相同列装装备
            PackingLibrary packingLibrary1 = packingLibraryHashMap.get(deviceLibraryEntity.getModel() + deviceLibraryEntity.getName() + matchingRange);
            //不存在直接抛出异常
            if (packingLibrary1 != null) {
                changeMap.put(deviceLibraryEntity.getPackingId(), packingLibrary1.getId());
                deviceLibraryEntity.setPackingId(packingLibrary1.getId());
                deviceLibraryEntity.setMatchingRange(matchingRange);
            } else {
                log.info("[配发] 没有在packingLibraryHashMap找到key:{}的列装", deviceLibraryEntity.getModel() + deviceLibraryEntity.getName() + matchingRange);
            }
            //存装备日志
//            DeviceLogDto deviceLogDto = new DeviceLogDto(id, "配发将所属列装由" + deviceLibraryEntity.getMatchingRangeName() + "的列装改为" + configCache.getMatchingRangeMap().get(1) + "的列装", fileVoList, saveEntity.getId(), null);
            DeviceLogDto deviceLogDto = new DeviceLogDto(id, "配发将所属列装由" + deviceLibraryEntity.getMatchingRangeName() + "的列装改为" + configCache.getMatchingRangeMap().get(1) + "的列装", fileVoList, saveEntity.getId(), saveEntity.getId());
            deviceLogService.addLog(deviceLogDto);


        }
    }

    @GetMapping("getFileList")
    @ApiOperation("通过任务id查询账单中文件")
    public ResponseEntity getFileList(Integer taskId){
        return ResponseEntity.ok(allotBillService.getFileList(taskId));
    }


}
