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

import com.fasterxml.jackson.core.type.TypeReference;
import com.tykj.dev.config.GlobalMap;
import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.file.service.FilesUtil;
import com.tykj.dev.device.library.repository.DeviceLibraryDao;
import com.tykj.dev.device.library.service.DeviceChangeService;
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.DeviceChange;
import com.tykj.dev.device.library.subject.domin.DeviceLibrary;
import com.tykj.dev.device.library.subject.vo.DeviceLibraryUpdateVo;
import com.tykj.dev.device.library.subject.vo.FileVo;
import com.tykj.dev.device.library.subject.vo.ScriptSaveVo;
import com.tykj.dev.device.repair.repository.RepairBackBillDao;
import com.tykj.dev.device.repair.repository.RepairDetailDao;
import com.tykj.dev.device.repair.repository.RepairSendBillDao;
import com.tykj.dev.device.repair.service.RepairBackBillService;
import com.tykj.dev.device.repair.service.RepairBillService;
import com.tykj.dev.device.repair.service.RepairDetailService;
import com.tykj.dev.device.repair.service.RepairSendBillService;
import com.tykj.dev.device.repair.subject.domin.RepairBackBill;
import com.tykj.dev.device.repair.subject.domin.RepairBill;
import com.tykj.dev.device.repair.subject.domin.RepairDetail;
import com.tykj.dev.device.repair.subject.domin.RepairSendBill;
import com.tykj.dev.device.repair.subject.vo.*;
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.Units;
import com.tykj.dev.device.user.subject.entity.User;
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.BusinessEnum;
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 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 = "/repair")
@AutoDocument
@Api(tags = "维修模块", description = "维修模块")
public class RepairController {

    @Autowired
    private RepairBillService deviceRepairBillService;

    @Autowired
    private RepairSendBillService deviceRepairSendBillService;

    @Autowired
    private UserPublicService userPublicService;

    @Autowired
    private DeviceLibraryService deviceLibraryService;

    @Autowired
    private RepairDetailService deviceRepairDetailService;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private TaskService taskService;

    @Autowired
    private DeviceLogService deviceLogService;

    @Autowired
    private RepairSendBillDao deviceRepairSendBillDao;

    @Autowired
    private RepairBackBillService deviceRepairBackBillService;

    @Autowired
    private MyWebSocket myWebSocket;

    @Autowired
    private TaskLogService taskLogService;

    @Autowired
    private RepairDetailDao repairDetailDao;

    @Autowired
    private RepairBackBillDao repairBackBillDao;

    @Autowired
    private DeviceChangeService deviceChangeService;

    @Autowired
    private Snowflake snowflake;

    @Autowired
    private InputOutputDeviceService inputOutputDeviceService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MessageService messageService;

    @Autowired
    private UnitsService unitsService;

    @Autowired
    private DeviceLibraryDao deviceLibraryDao;

    @ApiOperation(value = "判断维修装备是否同一个送修单位", notes = "可以通过这个接口判断维修装备是否同一个送修单位")
    @PostMapping(value = "/judge")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity judge(@RequestBody List<Integer> ids) {
        //存放所有维修记录的发件单位
        Set<String> sendUnits = new HashSet<>();
        ids.forEach(integer -> {
            RepairDetail repairDetail = deviceRepairDetailService.getOne(integer);
            RepairBill repairBill = deviceRepairBillService.getOne(repairDetail.getDeviceRepairBillId());
            sendUnits.add(repairBill.getSendUnit());
        });
        //如果是同一单位返回单位名称，否则返error
        if (sendUnits.size()==1){
            return ResponseEntity.ok(sendUnits.iterator().next());
        }
        else {
            return ResponseEntity.ok("error");
        }
    }

    @ApiOperation(value = "保存维修操作", notes = "可以通过这个接口保存维修操作")
    @PostMapping(value = "/saveRepairBill")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity saveRepairBill(@RequestBody RepairBillSaveVo repairBillSaveVo) {
        //判断装备的状态是否在库或维修中
        deviceLibraryService.isInStockOrRepairing(StringSplitUtil.split(repairBillSaveVo.getRepairDeviceCheckDetail()));
        //第一次保存
        if (repairBillSaveVo.getTaskId()==null){
            Integer userId = userUtils.getCurrentUserId();
            //保存入库单
            List<Integer> userIds = new ArrayList<>();
            userIds.add(userId);
            //添加维修单和送修单
            RepairBill repairBill = new RepairBill();
            RepairSendBill deviceRepairSendBillEntity = new RepairSendBill();
            //相同字段直接拷贝
            BeanUtils.copyProperties(repairBillSaveVo, repairBill);
            BeanUtils.copyProperties(repairBillSaveVo, deviceRepairSendBillEntity);
            //维修状态为草稿
            repairBill.setRepairStatus(0);
            deviceRepairSendBillEntity.setRepairStatus(0);
            //set不相同的字段
            if (repairBillSaveVo.getScriptSaveVos()!=null){
                deviceRepairSendBillEntity.setScriptJson(JacksonUtil.toJSon(repairBillSaveVo.getScriptSaveVos()));
            }
            if (repairBillSaveVo.getRepairUseraId() != null) {
                repairBill.setRepairUserA(userPublicService.getOne(repairBillSaveVo.getRepairUseraId()).getName());
            }
            repairBill.setStartUserB(repairBillSaveVo.getAgent());
            repairBill.setStartUserA(userPublicService.getOne(repairBillSaveVo.getStartUseraId()).getName());
            RepairBill repairBill1 = deviceRepairBillService.addEntity(repairBill);
            //生成单据号
            Calendar calendar = Calendar.getInstance();
            String s1 = "NO:第" + calendar.get(Calendar.YEAR) + "WX" + repairBill1.getId() + "号";
            repairBill1.setDocNum(s1);
            deviceRepairBillService.update(repairBill1);
            //set 关联id
            deviceRepairSendBillEntity.setDeviceRepairBillId(repairBill1.getId());
            deviceRepairSendBillService.addEntity(deviceRepairSendBillEntity);
            //发起任务
            TaskBto taskBto = new TaskBto(StatusEnum.REPAIR_SEND_DRAFT.id, "维修业务", null, ".", repairBill1.getId(), 5, userUtils.getCurrentUnitId(), 0, null, userIds);
            TaskBto taskBto1 = taskService.start(taskBto);
            Integer id = taskBto1.getId();
            myWebSocket.sendMessage1();
            return ResponseEntity.ok("保存成功"+id+"&"+s1);
        }
        else {
            //更新账单
            TaskBto taskBto = taskService.get(repairBillSaveVo.getTaskId());
            RepairBill repairBill1 = deviceRepairBillService.getOne(taskBto.getBillId());
            RepairSendBill repairSendBill = deviceRepairSendBillDao.findByDeviceRepairBillId(repairBill1.getId());
            RepairBill repairBill = new RepairBill();
            RepairSendBill deviceRepairSendBillEntity = new RepairSendBill();
            //复制到新的二个对象
            BeanUtils.copyProperties(repairBillSaveVo, repairBill);
            BeanUtils.copyProperties(repairBillSaveVo, deviceRepairSendBillEntity);
            repairBill.setRepairStatus(0);
            deviceRepairSendBillEntity.setRepairStatus(0);
            if (repairBillSaveVo.getScriptSaveVos()!=null){
                deviceRepairSendBillEntity.setScriptJson(JacksonUtil.toJSon(repairBillSaveVo.getScriptSaveVos()));
            }
            if (repairBillSaveVo.getRepairUseraId() != null) {
                repairBill.setRepairUserA(userPublicService.getOne(repairBillSaveVo.getRepairUseraId()).getName());
            }
            repairBill.setStartUserB(repairBillSaveVo.getAgent());
            repairBill.setStartUserA(userPublicService.getOne(repairBillSaveVo.getStartUseraId()).getName());
            //将新对象不为null的值拷贝到真实对象
            MapperUtils.copyNoNullProperties(repairBill,repairBill1);
            MapperUtils.copyNoNullProperties(deviceRepairSendBillEntity,repairSendBill);
            deviceRepairBillService.update(repairBill1);
            deviceRepairSendBillService.update(repairSendBill);
            return ResponseEntity.ok("更新成功"+taskBto.getId());
        }
    }

    @ApiOperation(value = "添加维修装备", notes = "可以通过这个接口发起维修")
    @PostMapping(value = "/add")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity addRepairDevice(@RequestBody List<Integer> ids) {
        //判断是否在库
        deviceLibraryService.isInStock(ids);
        //存放详情id
        List<Integer> detailIds = new ArrayList<>();
        for (Integer integer:ids) {
            DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(integer);
            //装备状态改成维修中
            deviceLibraryEntity.setLifeStatus(4);
            deviceLibraryService.update(deviceLibraryEntity);
            //创建新的维修详情
            RepairDetail repairDetail = new RepairDetail();
            repairDetail.setDeviceId(integer);
            repairDetail.setLocationUnit(userUtils.getCurrentUserUnitName());
            repairDetail.setModel(deviceLibraryEntity.getModel());
            repairDetail.setName(deviceLibraryEntity.getName());
            repairDetail.setOwnUnit(deviceLibraryEntity.getOwnUnit());
            repairDetail.setRepairStatus(9);
            repairDetail.setRfidSurfaceId(deviceLibraryEntity.getRfidSurfaceId());
            repairDetail.setSeqNumber(deviceLibraryEntity.getSeqNumber());
            repairDetail.setType(deviceLibraryEntity.getType());
            repairDetail.setDeviceRepairBillId(0);
            RepairDetail repairDetail1 = deviceRepairDetailService.save(repairDetail);
            detailIds.add(repairDetail1.getId());
            //存装备日志
            DeviceLogDto deviceLogDto = new DeviceLogDto(integer, "将装备添加到待维修列表", null);
            deviceLogService.addLog(deviceLogDto);
        }
        //发送阅知信息
        List<Integer> userIds = userPublicService.findOtherUser(userUtils.getCurrentUserId());
        MessageBto messageBto = new MessageBto(0,5,"添加维修装备",userIds,1);
        //阅知记录存放detailIds
        messageBto.setRecord(StringSplitUtil.idListToString(detailIds));
        messageService.add(messageBto);
        return ResponseEntity.ok("添加成功");
    }

    @ApiOperation(value = "发起维修", notes = "可以通过这个接口发起维修")
    @PostMapping(value = "/form")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity createRepair(@RequestBody @Validated RepairBillSaveVo repairBillSaveVo) {
        //判断装备状态是不是在库和维修中
        deviceLibraryService.isInStockOrRepairing(StringSplitUtil.split(repairBillSaveVo.getRepairDeviceCheckDetail()));
        //存放详情id
        List<Integer> detailIds = new ArrayList<>();
        repairBillSaveVo.getDeviceList().forEach(deviceDetailVo -> {
            if (deviceDetailVo.getId()!=null){
                detailIds.add(deviceDetailVo.getId());
            }
        });
        //判断维修详情的状态
        if (detailIds.size()>0){
            detailIds.forEach(integer -> {
                RepairDetail repairDetail = deviceRepairDetailService.getOne(integer);
                if ((repairDetail.getRepairStatus()!=1&&repairDetail.getRepairStatus()!=9)||repairDetailDao.findAllByPid(repairDetail.getId()).size()>0){
                    throw new ApiException(ResponseEntity.status(303).body("序列号"+repairDetail.getSeqNumber()+"的装备已被其他专管员操作"));
                }
            });
        }
        Integer userId = userUtils.getCurrentUserId();
        Integer level = userUtils.getCurrentUnitLevel();
        //添加维修单和送修单
        RepairBill repairBill;
        RepairSendBill deviceRepairSendBillEntity;
        //草稿发起的
        if (repairBillSaveVo.getTaskId()!=null){
            repairBill = deviceRepairBillService.getOne(taskService.get(repairBillSaveVo.getTaskId()).getBillId());
            deviceRepairSendBillEntity = deviceRepairSendBillDao.findByDeviceRepairBillId(repairBill.getId());
            MapperUtils.copyNoNullProperties(repairBillSaveVo,repairBill);
            MapperUtils.copyNoNullProperties(repairBillSaveVo,deviceRepairSendBillEntity);
        }
        else {
            RepairBill repairBill1 = new RepairBill();
            RepairSendBill deviceRepairSendBillEntity1 = new RepairSendBill();
            BeanUtils.copyProperties(repairBillSaveVo, repairBill1);
            BeanUtils.copyProperties(repairBillSaveVo, deviceRepairSendBillEntity1);
            repairBill = deviceRepairBillService.addEntity(repairBill1);
            deviceRepairSendBillEntity1.setDeviceRepairBillId(repairBill.getId());
            deviceRepairSendBillEntity = deviceRepairSendBillService.addEntity(deviceRepairSendBillEntity1);
        }
        if (repairBillSaveVo.getScriptSaveVos() != null) {
            deviceRepairSendBillEntity.setScriptJson(JacksonUtil.toJSon(repairBillSaveVo.getScriptSaveVos()));
        }
        //如果当前为省向国家发起的
        if (level == 1) {
            repairBill.setRepairStatus(4);
            deviceRepairSendBillEntity.setRepairStatus(5);
        } else {
            repairBill.setRepairStatus(2);
            deviceRepairSendBillEntity.setRepairStatus(2);
        }
        if (repairBillSaveVo.getRepairUseraId() != null) {
            repairBill.setRepairUserA(userPublicService.getOne(repairBillSaveVo.getRepairUseraId()).getName());
        }
        repairBill.setStartUserB(repairBillSaveVo.getAgent());
        repairBill.setStartUserA(userPublicService.getOne(repairBillSaveVo.getStartUseraId()).getName());
        //生成单位电子签章id
        Long signId2 = snowflake.creatNextId();
        if (repairBillSaveVo.getLeftSignatureId()!=null) {
            repairBill.setLeftSignatureId(repairBillSaveVo.getLeftSignatureId());
        }
        repairBill.setRightSignatureId(signId2.toString());
        RepairBill repairBill1 = deviceRepairBillService.update(repairBill);
        //生成单据号
        Calendar calendar = Calendar.getInstance();
        String s1 = "NO:第" + calendar.get(Calendar.YEAR) + "WX" + repairBill1.getId() + "号";
        repairBill1.setDocNum(s1);
        RepairBill repairBill2 = deviceRepairBillService.update(repairBill1);
        //发起维修业务
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        userIds.add(0);
        //发送时间
        deviceRepairSendBillEntity.setSendTime(new Date());
        //存放维修装备id和维修原因的组合字段
        StringBuffer stringBuffer = new StringBuffer();
        //存维修详情单
        for (DeviceDetailVo d : repairBillSaveVo.getDeviceList()) {
            //存放旧详情
            RepairDetail oldRepairDetail = null;
            //从待维修列表发起维修的
            if (d.getId()!=null) {
                oldRepairDetail =deviceRepairDetailService.getOne(d.getId());
            }
            stringBuffer.append(d.getDeviceId());
            stringBuffer.append("Ǵ");
            stringBuffer.append(d.getRemark());
            stringBuffer.append("Ǵ");
            //获取装备信息
            DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(d.getDeviceId());
            //待维修列表当前单位自己添加的维修记录
            if (oldRepairDetail!=null&&oldRepairDetail.getDeviceRepairBillId()==0) {
                oldRepairDetail.setRemark(d.getRemark());
                oldRepairDetail.setDeviceRepairBillId(repairBill1.getId());
                oldRepairDetail.setRepairStatus(0);
                deviceRepairDetailService.update(oldRepairDetail);
            }
            else {
                RepairDetail repairDetail = new RepairDetail();
                //如果是下级待维修装备继续发起维修
                if (d.getId() != null) {
                    //set父id
                    repairDetail.setPid(d.getId());
                    RepairDetail repairDetail1 = deviceRepairDetailService.getOne(d.getId());
                    repairDetail1.setRepairStatus(8);
                    deviceRepairDetailService.update(repairDetail1);
                }
                repairDetail.setDeviceId(d.getDeviceId());
                repairDetail.setLocationUnit(userUtils.getCurrentUserUnitName());
                repairDetail.setModel(deviceLibraryEntity.getModel());
                repairDetail.setName(deviceLibraryEntity.getName());
                repairDetail.setOwnUnit(deviceLibraryEntity.getOwnUnit());
                repairDetail.setRemark(d.getRemark());
                repairDetail.setRepairStatus(0);
                repairDetail.setRfidSurfaceId(deviceLibraryEntity.getRfidSurfaceId());
                repairDetail.setSeqNumber(deviceLibraryEntity.getSeqNumber());
                repairDetail.setType(deviceLibraryEntity.getType());
                repairDetail.setDeviceRepairBillId(repairBill1.getId());
                deviceRepairDetailService.save(repairDetail);
            }
            //如果当前为省像国家发起的
            if (level == 1) {
                deviceLibraryEntity.setLifeStatus(4);
                deviceLibraryEntity.setLocationUnit(repairBillSaveVo.getReceiveUnit());
            } else {
                deviceLibraryEntity.setLifeStatus(4);
            }
            deviceLibraryEntity.setManageStatus(0);
            deviceLibraryService.update(deviceLibraryEntity);
            //存装备日志
            DeviceLogDto deviceLogDto = new DeviceLogDto(d.getDeviceId(), "向" + repairBillSaveVo.getReceiveUnit() + "发起装备维修", null);
            deviceLogService.addLog(deviceLogDto);
        }
        //存送修单
        deviceRepairSendBillEntity.setRepairDeviceDetail(stringBuffer.toString());
        deviceRepairSendBillEntity.setDeviceRepairBillId(repairBill1.getId());
        deviceRepairSendBillEntity.setAgent(repairBillSaveVo.getAgent());
        deviceRepairSendBillEntity.setTitle("维修业务");
        if (repairBillSaveVo.getSendFileList()!=null&&repairBillSaveVo.getSendFileList().size()>0) {
            deviceRepairSendBillEntity.setSendFiles(FilesUtil.stringFileToList(repairBillSaveVo.getSendFileList()));
        }
        RepairSendBill repairSendBill = deviceRepairSendBillService.update(deviceRepairSendBillEntity);
        //业务的待办所属单位
        Integer ownUnit;
        //保存后的taskBto
        TaskBto saveEntity;
        //当前单位其他专管员id集合
        List<Integer> ids = userPublicService.findOtherUser(userUtils.getCurrentUserId());
        //省向国家发起的
        if (level == 1) {
            ownUnit = userUtils.getCurrentUnitId();
            //直接发起的
            if (repairBillSaveVo.getTaskId()==null) {
                TaskBto taskBto = new TaskBto(StatusEnum.WAIT_UPLOAD_FILE.id, "维修业务", null, ".", repairBill1.getId(), 5, ownUnit, 1, "country", userIds);
                saveEntity = taskService.start(taskBto);
            }
            //从草稿发起的
            else {
                TaskBto taskBto1 = taskService.get(repairBillSaveVo.getTaskId());
                taskBto1.setCustomInfo("country");
                saveEntity = taskService.moveToSpecial(taskBto1,StatusEnum.WAIT_UPLOAD_FILE);
            }
        } else {
            ownUnit = userPublicService.findUnitIdByName(repairBill.getReceiveUnit());
            //直接发起的
            if (repairBillSaveVo.getTaskId()==null) {
                TaskBto taskBto = new TaskBto(StatusEnum.WAIT_RECEIVE.id, "维修业务", null, ".", repairBill1.getId(), 5, ownUnit, 1, null, userIds);
                saveEntity = taskService.start(taskBto);
            }
            //从草稿发起的
            else {
                TaskBto taskBto1 = taskService.get(repairBillSaveVo.getTaskId());
                taskBto1.setOwnUnit(ownUnit);
                saveEntity = taskService.moveToSpecial(taskBto1,StatusEnum.WAIT_RECEIVE);
            }
            //阅知集合加上收件单位所有专管员
            ids.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(repairBill.getReceiveUnit())).stream()
                    .map(User::getUserId)
                    .collect(Collectors.toList()));
            //生成子任务（发件方上传回执单）
            TaskBto taskBto2 = new TaskBto(StatusEnum.WAIT_UPLOAD_SEND_FILE.id, "维修业务", saveEntity.getId(), saveEntity.getNodeIdDetail() + saveEntity.getId() + ".", saveEntity.getBillId(), 5, userPublicService.findUnitIdByName(repairSendBill.getSendUnit()), 0, null, Collections.singletonList(0));
            taskService.start(taskBto2);
        }
        //获取装备id集合
        String deviceIdDetail = deviceRepairSendBillEntity.getRepairDeviceCheckDetail();
        List<Integer> idList = StringSplitUtil.split(deviceIdDetail);
        //如果当前为省，改变装备的所在为中办
        if (level == 1) {
            //获取当前业务维修详情
            List<RepairDetail> repairDetailEntities = deviceRepairDetailService.findByBillId(repairBill.getId());
            //改变维修详情装备所在单位为中办,状态为维修中
            repairDetailEntities.forEach(repairDetail -> {
                repairDetail.setLocationUnit(repairBillSaveVo.getReceiveUnit());
                repairDetail.setRepairStatus(1);
                deviceRepairDetailService.update(repairDetail);
                //同时改变所有父节点的所在单位
                if (repairDetail.getPid()!=null){
                    RepairDetail repairDetail1 = deviceRepairDetailService.getOne(repairDetail.getPid());
                    repairDetail1.setLocationUnit(repairBill.getReceiveUnit());
                    deviceRepairDetailService.update(repairDetail1);
                    if (repairDetail1.getPid()!=null){
                        RepairDetail repairDetail2 = deviceRepairDetailService.getOne(repairDetail.getPid());
                        repairDetail2.setLocationUnit(repairBill.getReceiveUnit());
                        deviceRepairDetailService.update(repairDetail2);
                    }
                }
            });
        }
        //添加出库白名单
        inputOutputDeviceService.addWhiteDevices(idList,userUtils.getCurrentUnitId(),1);
        //发送阅知信息
        if (repairBillSaveVo.getStartUserbId()!=null) {
            List<Integer> idList1 = new ArrayList<>();
            idList1.add(repairBillSaveVo.getStartUserbId());
            MessageBto messageBto = new MessageBto(saveEntity.getId(), saveEntity.getBusinessType(), "被选为签发人", idList1, 1);
            messageService.add(messageBto);
        }
        MessageBto messageBto = new MessageBto(saveEntity.getId(),saveEntity.getBusinessType(),"向"+userPublicService.getAreaNameByUnitName(repairBill.getReceiveUnit())+"发起装备维修",ids,1);
        messageService.add(messageBto);
        myWebSocket.sendMessage1();
        return ResultUtil.success(repairBill2);
    }

    @ApiOperation(value = "继续向上发起维修", notes = "可以通过这个接口继续向上发起维修")
    @PostMapping(value = "/continue/form")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity continueCreateRepair(@RequestBody @Validated RepairBillSaveVo deviceRepairBillSaveVo) {
        return createRepair(deviceRepairBillSaveVo);
    }

    @ApiOperation(value = "接收维修装备", notes = "可以通过这个接口接收维修装备")
    @PostMapping(value = "/receive")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity receiveDevice(@RequestBody @Validated RepairReceiveVo repairReceiveVo) {
        //获取当前任务
        TaskBto taskBto = taskService.get(repairReceiveVo.getTaskId());
        //判断业务当前状态
        List<StatusEnum> statusEnums = new ArrayList<>();
        statusEnums.add(StatusEnum.WAIT_RECEIVE);
        statusEnums.add(StatusEnum.REPAIR_SEND_WAIT_SIGN);
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),statusEnums);
        Integer userId = userUtils.getCurrentUserId();
        //获取维修单，送修单，装备详情，维修装备详情
        RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
        RepairSendBill repairSendBill = deviceRepairSendBillDao.findByDeviceRepairBillId(repairBill.getId());
        String deviceIdDetail = repairReceiveVo.getReceiveCheckDetail();
        List<RepairDetail> repairDetailEntities = deviceRepairDetailService.findByBillId(repairBill.getId());
        //如果盖章了set接收方签章id
        if (repairReceiveVo.getRightSignatureId()!=null&&!"".equals(repairReceiveVo.getRightSignatureId())){
            repairBill.setRightSignatureId(repairReceiveVo.getRightSignatureId());
        }
        if (repairSendBill.getRepairUseraId() == null) {
            repairBill.setRepairUserA(userUtils.getCurrentName());
            repairSendBill.setRepairUseraId(userId);
            taskService.addInvolveUser(taskBto, userId);
        }
        //阅知人员id集合
        List<Integer> ids = userPublicService.findOtherUser(userUtils.getCurrentUserId());
        ids.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(repairBill.getSendUnit())).stream()
                .map(User::getUserId)
                .collect(Collectors.toList()));
        //存业务日志
        List<FileVo> fileVoList = new ArrayList<>();
        //更新维修单和送修单
        repairBill.setRepairStatus(4);
        if (repairReceiveVo.getReceiveUserbId()!=null) {
            repairBill.setRepairUserB(userPublicService.getOne(repairReceiveVo.getReceiveUserbId()).getName());
        }
        if (repairReceiveVo.getStartUserbId()!=null){
            repairSendBill.setStartUserbId(repairReceiveVo.getStartUserbId());
            repairSendBill.setAgent(userPublicService.getOne(repairReceiveVo.getStartUserbId()).getName());
            repairBill.setStartUserB(repairSendBill.getAgent());
        }
        deviceRepairBillService.update(repairBill);
        repairSendBill.setRepairStatus(5);
        repairSendBill.setBillFileName(repairReceiveVo.getBillFileName());
        repairSendBill.setBillFileUrl(repairReceiveVo.getBillFileUrl());
        repairSendBill.setReceiveTime(new Date());
        repairSendBill.setReceiveCount(repairReceiveVo.getReceiveCount());
        repairSendBill.setReceiveFileName(repairReceiveVo.getReceiveFileName());
        repairSendBill.setReceiveFileUrl(repairReceiveVo.getReceiveFileUrl());
        repairSendBill.setRepairReciveCheckDetail(repairReceiveVo.getReceiveCheckDetail());
        repairSendBill.setRepairReciveCheckResult(repairReceiveVo.getReceiveCheckResult());
        repairSendBill.setRepairUserbId(repairReceiveVo.getReceiveUserbId());
        //单据不缺少，直接办结
        if (repairReceiveVo.getStatus()==0) {
            if (repairReceiveVo.getReceiveFiles()!=null&&repairReceiveVo.getReceiveFiles().size()>0){
                repairReceiveVo.getReceiveFiles().forEach(fileRet -> {
                    fileVoList.add(new FileVo("维修单", fileRet.getName(), fileRet.getPreviewPath()));
                });
                repairSendBill.setReceiveFiles(FilesUtil.stringFileToList(repairReceiveVo.getReceiveFiles()));
            }
            taskService.moveToEnd(taskBto);
            //子任务完结
            taskService.moveAllSonNodeToEnd(taskBto.getId());
            //阅知
            MessageBto messageBto = new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"业务办结",ids,1);
            messageService.add(messageBto);
        }
        else {
            //推到待上传签收单状态
            taskService.moveToSpecial(taskBto,StatusEnum.WAIT_UPLOAD_FILE);
        }
        deviceRepairSendBillService.update(repairSendBill);
        //分隔装备id
        String[] strings = deviceIdDetail.split("x");
        //存接收无误的装备id
        List<Integer> idList = new ArrayList<>();
        for (String s : strings) {
            if (s.length() >= 2) {
                //接收无误
                if ("1".equals(s.substring(s.length() - 1))) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    idList.add(id);
                    //更新装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(4);
                    deviceLibraryEntity.setLocationUnit(repairBill.getReceiveUnit());
                    deviceLibraryEntity.setManageStatus(1);
                    //存装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id, "接收并发起入库", fileVoList);
                    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);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
        }
        //改变维修详情装备所在单位为当前单位
        repairDetailEntities.forEach(repairDetail -> {
            repairDetail.setLocationUnit(repairBill.getReceiveUnit());
            repairDetail.setRepairStatus(1);
            deviceRepairDetailService.update(repairDetail);
            //改变父详情的所在
            if (repairDetail.getPid()!=null){
                RepairDetail repairDetail1 = deviceRepairDetailService.getOne(repairDetail.getPid());
                repairDetail1.setLocationUnit(repairBill.getReceiveUnit());
                deviceRepairDetailService.update(repairDetail1);
            }
        });
        //发送阅知信息
//        if (repairReceiveVo.getReceiveUserbId()!=null) {
//            List<Integer> idList1 = new ArrayList<>();
//            idList1.add(repairReceiveVo.getReceiveUserbId());
//            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", idList1, 1);
//            messageService.add(messageBto);
//        }
        if (repairReceiveVo.getStartUserbId()!=null) {
            List<Integer> idList1 = new ArrayList<>();
            idList1.add(repairReceiveVo.getStartUserbId());
            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为签发人", idList1, 1);
            messageService.add(messageBto);
        }
        MessageBto messageBto = new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"接收维修装备",ids,1);
        messageService.add(messageBto);
        myWebSocket.sendMessage1();
        return ResultUtil.success("维修装备接收入库");
    }

    @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);
        RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
        //如果是接收方申请盖章
        if (repairBill.getRepairStatus()!=0){
            RepairSendBill repairSendBill = deviceRepairSendBillDao.findByDeviceRepairBillId(repairBill.getId());
            repairSendBill.setRepairUseraId(userUtils.getCurrentUserId());
            repairBill.setRepairUserA(userUtils.getCurrentName());
            deviceRepairBillService.update(repairBill);
            deviceRepairSendBillService.update(repairSendBill);
        }
        if (taskBto.getBillStatus().equals(StatusEnum.WAIT_RECEIVE.id)) {
            taskBto.setRemark("入库盖章");
        }
        else {
            taskBto.setRemark("出库盖章");
        }
        //推动任务
        taskService.moveToSpecial(taskBto,StatusEnum.REPAIR_SEND_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);
        RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
        RepairSendBill repairSendBill = deviceRepairSendBillDao.findByDeviceRepairBillId(repairBill.getId());
        //审核通过
        if (status==1){
            taskService.moveToSpecial(taskBto,StatusEnum.REPAIR_SEND_WAIT_SIGN);
            //发件方盖章
            if (repairBill.getRepairStatus()==0) {
                repairSendBill.setStartUserbId(userUtils.getCurrentUserId());
                repairSendBill.setAgent(userUtils.getCurrentName());
                repairBill.setStartUserB(repairSendBill.getAgent());
            }
            //收件方盖章
            else {
                repairSendBill.setRepairUserbId(userUtils.getCurrentUserId());
                repairBill.setRepairUserB(userUtils.getCurrentName());
            }
            deviceRepairBillService.update(repairBill);
            deviceRepairSendBillService.update(repairSendBill);
        }
        else {
            //发件方盖章
            if (repairBill.getRepairStatus()==0) {
                //推到草稿状态
                taskService.moveToSpecial(taskBto, StatusEnum.REPAIR_SEND_DRAFT, taskBto.getCreateUserId());
            }
            //收件方盖章
            else {
                //推到待接收状态
                taskService.moveToSpecial(taskBto, StatusEnum.WAIT_RECEIVE, repairSendBill.getRepairUseraId());
            }
        }
        myWebSocket.sendMessage1();
        return ResponseEntity.ok("申请成功");
    }

    @ApiOperation(value = "上传接收方送修单", notes = "可以通过这个接口上传送修单")
    @PostMapping(value = "/uploadRepairBill")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity uploadRepairBill(@RequestBody @Validated FileUploadVo fileUploadVo){
        TaskBto taskBto = taskService.get(fileUploadVo.getTaskId());
        //判断业务状态
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),StatusEnum.WAIT_UPLOAD_FILE);
        Integer userId = userUtils.getCurrentUserId();
        taskService.addInvolveUser(taskBto,userId);
        //获取账单
        RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
        RepairSendBill repairSendBill = deviceRepairSendBillDao.findByDeviceRepairBillId(taskBto.getBillId());
        //阅知人员
        List<Integer> ids = userPublicService.findOtherUser(userId);
        ids.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(repairSendBill.getSendUnit())).stream()
                .map(User::getUserId)
                .collect(Collectors.toList()));
        //当前业务和子业务办结
        taskService.moveToEnd(taskBto);
        taskService.moveAllSonNodeToEnd(taskBto.getId());
        //阅知
        MessageBto messageBto = new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"业务办结",ids,1);
        messageService.add(messageBto);
        repairSendBill.setBillFileName(fileUploadVo.getBillFileName());
        repairSendBill.setBillFileUrl(fileUploadVo.getBillFileUrl());
        List<FileVo> fileVoList = new ArrayList<>();
        if (fileUploadVo.getReceiveFiles()!=null&&fileUploadVo.getReceiveFiles().size()>0){
            fileUploadVo.getReceiveFiles().forEach(fileRet -> {
                fileVoList.add(new FileVo("维修单", fileRet.getName(), fileRet.getPreviewPath()));
            });
            repairSendBill.setReceiveFiles(FilesUtil.stringFileToList(fileUploadVo.getReceiveFiles()));
        }
        //签发人
        if (fileUploadVo.getStartUserbId()!=null){
            String s = userPublicService.getOne(fileUploadVo.getStartUserbId()).getName();
            repairBill.setStartUserB(s);
            repairSendBill.setStartUserbId(fileUploadVo.getStartUserbId());
            repairSendBill.setAgent(s);
            MessageBto messageBto1 = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为签发人", Collections.singletonList(fileUploadVo.getStartUserbId()), 1);
            messageService.add(messageBto1);
        }
        //收件方经办人
//        if (fileUploadVo.getRepairUserbId()!=null){
//            repairSendBill.setRepairUserbId(fileUploadVo.getRepairUserbId());
//            repairBill.setRepairUserB(userPublicService.getOne(fileUploadVo.getRepairUserbId()).getName());
//            MessageBto messageBto2 = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", Collections.singletonList(fileUploadVo.getRepairUserbId()), 1);
//            messageService.add(messageBto2);
//        }
        if (fileUploadVo.getRepairUseraId()!=null){
            repairSendBill.setRepairUseraId(fileUploadVo.getRepairUseraId());
            repairBill.setRepairUserA(userPublicService.getOne(fileUploadVo.getRepairUseraId()).getName());
        }
        deviceRepairBillService.update(repairBill);
        deviceRepairSendBillService.update(repairSendBill);
        //添加装备日志
        List<Integer> deviceIds = StringSplitUtil.split(repairSendBill.getRepairDeviceCheckDetail());
        deviceIds.forEach(integer -> {
            //存装备日志
            DeviceLogDto deviceLogDto = new DeviceLogDto(integer, "上传送修单据", fileVoList);
            deviceLogService.addLog(deviceLogDto);
        });
        return ResponseEntity.ok("上传成功");
    }

    @ApiOperation(value = "保存维修退回操作（草稿）", notes = "可以通过这个接口保存维修退回操作")
    @PostMapping(value = "/saveRepairBackBill")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity saveRepairBackBill(@RequestBody RepairBackBillSaveVo repairBackBillSaveVo) {
        //第一次保存
        if (repairBackBillSaveVo.getTaskId()==null){
            Integer userId = userUtils.getCurrentUserId();
            //保存入库单
            List<Integer> userIds = new ArrayList<>();
            userIds.add(userId);
            //添加维修单和送修单
            RepairBackBill repairBackBill = new RepairBackBill();
            BeanUtils.copyProperties(repairBackBillSaveVo, repairBackBill);
            repairBackBill.setBackStatus(0);
            if (repairBackBillSaveVo.getScriptSaveVos()!=null){
                repairBackBill.setScriptJson(JacksonUtil.toJSon(repairBackBillSaveVo.getScriptSaveVos()));
            }
            RepairBackBill repairBackBill1 = deviceRepairBackBillService.save(repairBackBill);
            Calendar calendar = Calendar.getInstance();
            String s1 = "NO:第" + calendar.get(Calendar.YEAR) + "LQ" + repairBackBill.getId() + "号";
            repairBackBill1.setDocNum(s1);
            deviceRepairBackBillService.update(repairBackBill1);
            //发起任务
            TaskBto taskBto = new TaskBto(StatusEnum.REPAIR_BACK_DRAFT.id, "维修退回", null,  ".", repairBackBill1.getId(), BusinessEnum.REPAIR_BACK.id,userUtils.getCurrentUnitId(), 0, null, userIds);
            TaskBto taskBto1 = taskService.start(taskBto);
            Integer id = taskBto1.getId();
            myWebSocket.sendMessage1();
            return ResponseEntity.ok("保存成功"+id+"&"+s1);
        }
        else {
            //更新账单
            TaskBto taskBto = taskService.get(repairBackBillSaveVo.getTaskId());
            RepairBackBill repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
            MapperUtils.copyNoNullProperties(repairBackBillSaveVo,repairBackBill);
            deviceRepairBackBillService.update(repairBackBill);
            return ResponseEntity.ok("更新成功"+taskBto.getId());
        }
    }

    @ApiOperation(value = "修好装备出库", notes = "可以通过这个接口修好装备出库")
    @PostMapping(value = "/back")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity repairBack(@RequestBody @Validated RepairBackBillSaveVo repairBackBillSaveVo) {
        //存放详情id
        List<Integer> detailIds = new ArrayList<>();
        repairBackBillSaveVo.getDeviceList().forEach(deviceDetailVo -> {
            if (deviceDetailVo.getId()!=null){
                detailIds.add(deviceDetailVo.getId());
            }
        });
        //判断维修记录的状态
        if (detailIds.size()>0){
            detailIds.forEach(integer -> {
                RepairDetail repairDetail = deviceRepairDetailService.getOne(integer);
                if (repairDetail.getRepairStatus()!=2){
                    throw new ApiException(ResponseEntity.status(303).body("序列号"+repairDetail.getSeqNumber()+"的装备已被其他专管员操作"));
                }
            });
        }
        //获取当前维修业务，维修单
        Integer userId = userUtils.getCurrentUserId();
        //生成维修退回单
        RepairBackBill repairBackBill;
        //草稿发起
        if (repairBackBillSaveVo.getTaskId()!=null){
            repairBackBill = deviceRepairBackBillService.getOne(taskService.get(repairBackBillSaveVo.getTaskId()).getBillId());
            MapperUtils.copyNoNullProperties(repairBackBillSaveVo,repairBackBill);
        }
        else {
            RepairBackBill repairBackBill1 =new RepairBackBill();
            BeanUtils.copyProperties(repairBackBillSaveVo, repairBackBill1);
            repairBackBill = deviceRepairBackBillService.save(repairBackBill1);
        }
        repairBackBill.setBackStatus(2);
        repairBackBill.setSendTime(new Date());
        repairBackBill.setTitle("维修退回业务");
        repairBackBill.setAgent(repairBackBillSaveVo.getAgent());
        //生成单位签章id
        Long signId2 = snowflake.creatNextId();
        if (repairBackBillSaveVo.getLeftSignatureId()!=null) {
            repairBackBill.setLeftSignatureId(repairBackBillSaveVo.getLeftSignatureId());
        }
        repairBackBill.setRightSignatureId(signId2.toString());
        if (repairBackBillSaveVo.getScriptSaveVos()!=null){
            repairBackBill.setScriptJson(JacksonUtil.toJSon(repairBackBillSaveVo.getScriptSaveVos()));
        }
        RepairBackBill deviceRepairBackBillEntity1 = deviceRepairBackBillService.update(repairBackBill);
        Calendar calendar = Calendar.getInstance();
        String s1 = "NO:第" + calendar.get(Calendar.YEAR) + "LQ" + repairBackBill.getId() + "号";
        deviceRepairBackBillEntity1.setDocNum(s1);
        RepairBackBill repairBackBill1 = deviceRepairBackBillService.update(deviceRepairBackBillEntity1);
        //发起维修退回子业务
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        userIds.add(0);
        TaskBto task;
        //草稿发起
        if (repairBackBillSaveVo.getTaskId()==null) {
            TaskBto taskBto1 = new TaskBto(StatusEnum.WAIT_BACK_RECEIVE.id, "维修退回", null, ".", deviceRepairBackBillEntity1.getId(), BusinessEnum.REPAIR_BACK.id, userPublicService.findUnitIdByName(repairBackBill.getReceiveUnit()), 1, null, userIds);
            task = taskService.start(taskBto1);
        }
        else {
            TaskBto taskBto1 = taskService.get(repairBackBillSaveVo.getTaskId());
            taskBto1.setOwnUnit(userPublicService.findUnitIdByName(repairBackBill.getReceiveUnit()));
            task = taskService.moveToSpecial(taskBto1,StatusEnum.WAIT_BACK_RECEIVE);
        }
        TaskBto taskBto2 = new TaskBto(StatusEnum.WAIT_UPLOAD_BACK_SEND_FILE.id, "维修退回", task.getId(), task.getNodeIdDetail() + task.getId() + ".", task.getBillId(), BusinessEnum.REPAIR_BACK.id, userPublicService.findUnitIdByName(repairBackBill.getSendUnit()), 0, null, Collections.singletonList(0));
        taskService.start(taskBto2);
        //添加业务日志
        List<FileVo> fileVoList = new ArrayList<>();
        //更新装备和详情的状态，添加装备日志
        for (DeviceDetailVo d : repairBackBillSaveVo.getDeviceList()) {
            RepairDetail repairDetail = deviceRepairDetailService.getOne(d.getId());
            repairDetail.setRepairBackBillId(deviceRepairBackBillEntity1.getId());
            repairDetail.setRepairStatus(7);
            repairDetail.setBackRemark(d.getRemark());
            deviceRepairDetailService.update(repairDetail);
            DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(d.getDeviceId());
            deviceLibraryEntity.setLifeStatus(4);
            deviceLibraryEntity.setManageStatus(0);
            DeviceLogDto deviceLogDto = new DeviceLogDto(d.getDeviceId(), "向" + repairBackBillSaveVo.getReceiveUnit() + "退还维修装备", fileVoList);
            deviceLogService.addLog(deviceLogDto);
        }
        String deviceIdDetail = repairBackBill.getBackCheckDetail();
        List<Integer> idList = StringSplitUtil.split(deviceIdDetail);
        //添加出库白名单
        inputOutputDeviceService.addWhiteDevices(idList,userUtils.getCurrentUnitId(),1);
        //发送阅知信息
        List<Integer> ids = userPublicService.findOtherUser(userUtils.getCurrentUserId());
        ids.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(repairBackBill.getReceiveUnit())).stream()
                .map(User::getUserId)
                .collect(Collectors.toList()));
        if (repairBackBillSaveVo.getStartUserbId()!=null) {
            List<Integer> idList1 = new ArrayList<>();
            idList1.add(repairBackBillSaveVo.getStartUserbId());
            MessageBto messageBto = new MessageBto(task.getId(), task.getBusinessType(), "被选为签发人", idList1, 1);
            messageService.add(messageBto);
        }
        MessageBto messageBto = new MessageBto(task.getId(),task.getBusinessType(),"向"+userPublicService.getAreaNameByUnitName(repairBackBill.getReceiveUnit())+"退回维修装备",ids,1);
        messageService.add(messageBto);
        myWebSocket.sendMessage1();
        return ResultUtil.success(repairBackBill1);
    }

    @ApiOperation(value = "修好装备送回接收入库", notes = "可以通过这个接口修好装备送回接收")
    @PostMapping(value = "/back/receive")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity backReceive(@RequestBody @Validated RepairReceiveVo repairReceiveVo) {
        //获取当前任务
        TaskBto taskBto;
        Integer userId = userUtils.getCurrentUserId();
        //获取退回单和装备id
        RepairBackBill repairBackBill;
        //正常退回接收
        if (repairReceiveVo.getTaskId()!=null) {
            taskBto = taskService.get(repairReceiveVo.getTaskId());
            List<StatusEnum> statusEnums = new ArrayList<>();
            statusEnums.add(StatusEnum.WAIT_BACK_RECEIVE);
            statusEnums.add(StatusEnum.REPAIR_BACK_WAIT_SIGN);
            TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),statusEnums);
            taskService.addInvolveUser(taskBto,userId);
            repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
        }
        //中办维修完成接收入库
        else {
            //新生成业务和账单
            taskBto = new TaskBto();
            repairBackBill = new RepairBackBill();
            repairBackBill.setSendUnit(deviceLibraryService.getOne(repairReceiveVo.getDeviceList().get(0).getDeviceId()).getLocationUnit());
            repairBackBill.setReceiveUnit(userUtils.getCurrentUserUnitName());
            repairBackBill.setBackCheckDetail(repairReceiveVo.getReceiveCheckDetail());
            repairBackBill.setStartUseraId(repairReceiveVo.getStartUseraId());
            repairBackBill.setStartUserbId(repairReceiveVo.getStartUserbId());
            repairBackBill.setReceiveUserbId(repairReceiveVo.getReceiveUserbId());
            if (repairReceiveVo.getScriptSaveVos()!=null){
                repairBackBill.setScriptJson(JacksonUtil.toJSon(repairReceiveVo.getScriptSaveVos()));
            }
        }
        String deviceIdDetail = repairReceiveVo.getReceiveCheckDetail();
        if (repairBackBill.getReceiveUseraId() == null) {
            repairBackBill.setReceiveUseraId(userId);
        }
        if (repairReceiveVo.getRightSignatureId()!=null&&!"".equals(repairReceiveVo.getRightSignatureId())){
            repairBackBill.setRightSignatureId(repairReceiveVo.getRightSignatureId());
        }
        if (repairReceiveVo.getStartUserbId()!=null){
            repairBackBill.setStartUserbId(repairReceiveVo.getStartUserbId());
            repairBackBill.setAgent(userPublicService.getOne(repairReceiveVo.getStartUserbId()).getName());
        }
        //更新退回单
        repairBackBill.setBackStatus(5);
        repairBackBill.setBillFileName(repairReceiveVo.getBillFileName());
        repairBackBill.setBillFileUrl(repairReceiveVo.getBillFileUrl());
        repairBackBill.setReceiveTime(new Date());
        repairBackBill.setReceiveCount(repairReceiveVo.getReceiveCount());
        repairBackBill.setReceiveFileName(repairReceiveVo.getReceiveFileName());
        repairBackBill.setReceiveFileUrl(repairReceiveVo.getReceiveFileUrl());
        repairBackBill.setBackReciveCheckDetail(repairReceiveVo.getReceiveCheckDetail());
        repairBackBill.setBackReciveCheckResult(repairReceiveVo.getReceiveCheckResult());
        repairBackBill.setReceiveUserbId(repairReceiveVo.getReceiveUserbId());
        List<FileVo> fileVoList = new ArrayList<>();
        if (repairReceiveVo.getReceiveFiles()!=null&&repairReceiveVo.getReceiveFiles().size()>0){
            repairReceiveVo.getReceiveFiles().forEach(fileRet -> {
                fileVoList.add(new FileVo("回执单", fileRet.getName(), fileRet.getPreviewPath()));
            });
            repairBackBill.setReceiveFiles(FilesUtil.stringFileToList(repairReceiveVo.getReceiveFiles()));
        }
        RepairBackBill repairBackBill1 = deviceRepairBackBillService.update(repairBackBill);
        Calendar calendar = Calendar.getInstance();
        String s1 = "NO:第" + calendar.get(Calendar.YEAR) + "LQ" + repairBackBill.getId() + "号";
        repairBackBill1.setDocNum(s1);
        deviceRepairBackBillService.save(repairBackBill1);
        //保存后的taskBto
        TaskBto taskBto2;
        //key为单位id,value为该单位维修完成的装备维修详情id的用来发阅知的map
        Map<Integer,List<Integer>> messageMap = new HashMap<>();
        //中办维修完成接收入库
        if (repairReceiveVo.getTaskId()==null) {
            List<Integer> userIds = new ArrayList<>();
            //不缺少单据直接办结
            if (repairReceiveVo.getStatus()==0) {
                userIds.add(userId);
                TaskBto taskBto1 = new TaskBto(StatusEnum.END.id, "维修退回", null, ".", repairBackBill1.getId(), BusinessEnum.REPAIR_BACK.id, userUtils.getCurrentUnitId(), 0, "country", userIds);
                taskBto2 = taskService.start(taskBto1);
            }
            else {
                userIds.add(0);
                TaskBto taskBto1 = new TaskBto(StatusEnum.WAIT_UPLOAD_BACK_FILE.id, "维修退回", null, ".", repairBackBill1.getId(), BusinessEnum.REPAIR_BACK.id, userUtils.getCurrentUnitId(), 0, "country", userIds);
                taskBto2 = taskService.start(taskBto1);
            }
            //遍历改变维修详情
            for (DeviceDetailVo d : repairReceiveVo.getDeviceList()) {
                RepairDetail repairDetail = deviceRepairDetailService.getOne(d.getId());
                //set领取单id
                repairDetail.setRepairBackBillId(repairBackBill1.getId());
                repairDetail.setRepairStatus(5);
                repairDetail.setLocationUnit(repairBackBill.getReceiveUnit());
                //同时改变所有父节点的维修状态和所在单位
                if (repairDetail.getPid()!=null) {
                    RepairDetail repairDetail1 = deviceRepairDetailService.getOne(repairDetail.getPid());
                    repairDetail1.setRepairStatus(2);
                    repairDetail1.setLocationUnit(repairBackBill.getReceiveUnit());
                    deviceRepairDetailService.update(repairDetail1);
                    //该维修记录发件单位
                    Integer unitId = userPublicService.getOne(repairDetail1.getCreateUserId()).getUnitsId();
                    //如果map不存在该单位id,直接put
                    if (messageMap.get(unitId)==null) {
                        messageMap.put(unitId, Collections.singletonList(repairDetail1.getId()));
                    }
                    else {
                        //get添加后再重新set
                        List<Integer> ids = new ArrayList<>(messageMap.getOrDefault(unitId, new ArrayList<>()));
                        ids.add(repairDetail1.getId());
                        messageMap.put(unitId,ids);
                    }
                    if (repairDetail1.getPid()!=null){
                        RepairDetail repairDetail2 = deviceRepairDetailService.getOne(repairDetail1.getPid());
                        repairDetail2.setLocationUnit(repairBackBill.getReceiveUnit());
                        deviceRepairDetailService.update(repairDetail2);
                    }
                }
                deviceRepairDetailService.update(repairDetail);
            }
        } else {
            //不缺少单据
            if (repairReceiveVo.getStatus()==0) {
                taskBto2 = taskService.moveToEnd(taskBto);
                //子任务完结
                taskService.moveAllSonNodeToEnd(taskBto2.getId());
            }
            else {
                taskBto2 = taskService.moveToSpecial(taskBto,StatusEnum.WAIT_UPLOAD_BACK_FILE);
            }
            //获取维修详情
            List<RepairDetail> repairDetailList = repairDetailDao.findByRepairBackBillId(repairBackBill.getId());
            //改变该维修详情及所有父详情
            repairDetailList.forEach(repairDetail -> {
                repairDetail.setRepairStatus(5);
                repairDetail.setLocationUnit(repairBackBill.getReceiveUnit());
                if (repairDetail.getPid()!=null) {
                    RepairDetail repairDetail1 = deviceRepairDetailService.getOne(repairDetail.getPid());
                    repairDetail1.setRepairStatus(2);
                    repairDetail1.setLocationUnit(repairBackBill.getReceiveUnit());
                    deviceRepairDetailService.update(repairDetail1);
                    Integer unitId = userPublicService.getOne(repairDetail1.getCreateUserId()).getUnitsId();
                    if (messageMap.get(unitId)==null) {
                        messageMap.put(unitId, Collections.singletonList(repairDetail1.getId()));
                    }
                    else {
                        List<Integer> ids = new ArrayList<>(messageMap.getOrDefault(unitId, new ArrayList<>()));
                        ids.add(repairDetail1.getId());
                        messageMap.put(unitId,ids);
                    }
                    if (repairDetail1.getPid()!=null){
                        RepairDetail repairDetail2 = deviceRepairDetailService.getOne(repairDetail1.getPid());
                        repairDetail2.setLocationUnit(repairBackBill.getReceiveUnit());
                        deviceRepairDetailService.update(repairDetail2);
                    }
                }
                deviceRepairDetailService.update(repairDetail);
            });
        }
        String[] strings = deviceIdDetail.split("x");
        for (String s : strings) {
            if (s.length() > 1) {
                //接收无误的装备
                if ("1".equals(s.substring(s.length() - 1))) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    //更改装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLocationUnit(repairBackBill.getReceiveUnit());
                    //如果所属和所在一致，状态改为在库
                    if (deviceLibraryEntity.getOwnUnit().equals(deviceLibraryEntity.getLocationUnit())) {
                        deviceLibraryEntity.setLifeStatus(2);
                    }
                    deviceLibraryEntity.setManageStatus(1);
                    //添加装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id, "维修退回装备接收并发起入库", fileVoList);
                    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);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
        }
        //发送阅知信息
        List<Integer> ids = userPublicService.findOtherUser(userUtils.getCurrentUserId());
        if (repairReceiveVo.getTaskId()!=null) {
            ids.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(repairBackBill.getSendUnit())).stream()
                    .map(User::getUserId)
                    .collect(Collectors.toList()));
        }
//        if (repairReceiveVo.getReceiveUserbId()!=null) {
//            List<Integer> idList1 = new ArrayList<>();
//            idList1.add(repairReceiveVo.getReceiveUserbId());
//            MessageBto messageBto = new MessageBto(taskBto2.getId(), taskBto2.getBusinessType(), "被选为经办人", idList1, 1);
//            messageService.add(messageBto);
//        }
        if (repairReceiveVo.getStartUserbId()!=null) {
            List<Integer> idList1 = new ArrayList<>();
            idList1.add(repairReceiveVo.getStartUserbId());
            MessageBto messageBto = new MessageBto(taskBto2.getId(), taskBto2.getBusinessType(), "被选为签发人", idList1, 1);
            messageService.add(messageBto);
        }
        String message = repairReceiveVo.getStatus()==0?"业务办结":"接收维修领取装备";
        MessageBto messageBto = new MessageBto(taskBto2.getId(),taskBto2.getBusinessType(),message,ids,1);
        messageService.add(messageBto);
        //遍历map依次发送阅知
        messageMap.keySet().forEach(integer -> {
            List<Integer> integerList = new ArrayList<>();
            integerList.addAll(userDao.findAllByUnitsId(integer).stream()
                    .map(User::getUserId)
                    .collect(Collectors.toList()));
            MessageBto messageBto2 = new MessageBto(0, 5, "待领取送修装备", integerList);
            //存放详情id集合
            messageBto2.setRecord(StringSplitUtil.idListToString(messageMap.get(integer)));
            messageService.add(messageBto2);
        });
        myWebSocket.sendMessage1();
        return ResultUtil.success("维修成功退回装备接收入库");
    }

    @ApiOperation(value = "维修退回申请电子签章", notes = "可以通过这个接口申请电子签章")
    @PostMapping(value = "/backApplySign/{taskId}/{userId}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity backApplySign(@PathVariable("taskId") int taskId,@PathVariable("userId") int userId) {
        //获取业务和账单
        TaskBto taskBto = taskService.get(taskId);
        RepairBackBill repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
        //接收方申请盖章
        if (repairBackBill.getBackStatus()!=0){
            repairBackBill.setReceiveUseraId(userUtils.getCurrentUserId());
            deviceRepairBackBillService.update(repairBackBill);
        }
        if (taskBto.getBillStatus().equals(StatusEnum.WAIT_BACK_RECEIVE.id)) {
            taskBto.setRemark("入库盖章");
        }
        else {
            taskBto.setRemark("出库盖章");
        }
        //推动任务
        taskService.moveToSpecial(taskBto,StatusEnum.REPAIR_BACK_SIGN_WAIT_CONFIRM,userId);
        myWebSocket.sendMessage1();
        return ResponseEntity.ok("申请成功");
    }

    @ApiOperation(value = "维修退回申请电子签章审核", notes = "可以通过这个接口申请电子签章审核")
    @PostMapping(value = "/backApplySignConfirm/{taskId}/{status}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity backApplySignConfirm(@PathVariable("taskId") int taskId,@PathVariable("status") int status) {
        //获取业务和账单
        TaskBto taskBto = taskService.get(taskId);
        RepairBackBill repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
        //同意盖章
        if (status==1){
            taskService.moveToSpecial(taskBto,StatusEnum.REPAIR_BACK_WAIT_SIGN);
            //发件方盖章
            if (repairBackBill.getBackStatus()==0) {
                repairBackBill.setStartUserbId(userUtils.getCurrentUserId());
                repairBackBill.setAgent(userUtils.getCurrentName());
            }
            //收件方
            else {
                repairBackBill.setReceiveUserbId(userUtils.getCurrentUserId());
            }
            deviceRepairBackBillService.update(repairBackBill);
        }
        //不同意
        else {
            //出库推至草稿状态
            if (repairBackBill.getBackStatus()==0) {
                taskService.moveToSpecial(taskBto, StatusEnum.REPAIR_BACK_DRAFT, taskBto.getCreateUserId());
            }
            //入库推至待接收装备状态
            else {
                taskService.moveToSpecial(taskBto, StatusEnum.WAIT_BACK_RECEIVE, repairBackBill.getReceiveUseraId());
            }
        }
        myWebSocket.sendMessage1();
        return ResponseEntity.ok("申请成功");
    }

    @ApiOperation(value = "接收方上传领取单", notes = "可以通过这个接口上传领取单")
    @PostMapping(value = "/uploadRepairBackBill")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity uploadRepairBackBill(@RequestBody @Validated FileUploadVo fileUploadVo){
        //获取业务
        TaskBto taskBto = taskService.get(fileUploadVo.getTaskId());
        //判断业务状态
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),StatusEnum.WAIT_UPLOAD_BACK_FILE);
        Integer userId = userUtils.getCurrentUserId();
        taskService.addInvolveUser(taskBto,userId);
        RepairBackBill repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
        //阅知人员集合
        List<Integer> ids = userPublicService.findOtherUser(userId);
        ids.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(repairBackBill.getSendUnit())).stream()
                .map(User::getUserId)
                .collect(Collectors.toList()));
        //该业务和子业务办结
        taskService.moveToEnd(taskBto);
        taskService.moveAllSonNodeToEnd(taskBto.getId());
        //阅知
        MessageBto messageBto = new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"业务办结",ids,1);
        messageService.add(messageBto);
        repairBackBill.setBillFileName(fileUploadVo.getBillFileName());
        repairBackBill.setBillFileUrl(fileUploadVo.getBillFileUrl());
        //签发人阅知
        if (fileUploadVo.getStartUserbId()!=null){
            repairBackBill.setStartUserbId(fileUploadVo.getStartUserbId());
            repairBackBill.setAgent(userPublicService.getOne(fileUploadVo.getStartUserbId()).getName());
            MessageBto messageBto1 = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为签发人", Collections.singletonList(fileUploadVo.getStartUserbId()), 1);
            messageService.add(messageBto1);
        }
        //经办人阅知
//        if (fileUploadVo.getReceiveUserbId()!=null){
//            repairBackBill.setReceiveUserbId(fileUploadVo.getReceiveUserbId());
//            MessageBto messageBto2 = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", Collections.singletonList(fileUploadVo.getReceiveUserbId()), 1);
//            messageService.add(messageBto2);
//        }
        List<FileVo> fileVoList = new ArrayList<>();
        if (fileUploadVo.getReceiveFiles()!=null&&fileUploadVo.getReceiveFiles().size()>0){
            fileUploadVo.getReceiveFiles().forEach(fileRet -> {
                fileVoList.add(new FileVo("回执单", fileRet.getName(), fileRet.getPreviewPath()));
            });
            repairBackBill.setReceiveFiles(FilesUtil.stringFileToList(fileUploadVo.getReceiveFiles()));
        }
        deviceRepairBackBillService.update(repairBackBill);
        //添加装备日志
        List<Integer> deviceIds = StringSplitUtil.split(repairBackBill.getBackReciveCheckDetail());
        deviceIds.forEach(integer -> {
            //存装备日志
            DeviceLogDto deviceLogDto = new DeviceLogDto(integer, "上传回执单据", fileVoList);
            deviceLogService.addLog(deviceLogDto);
        });
        return ResponseEntity.ok("上传成功");
    }

    @ApiOperation(value = "更改维修装备状态", notes = "可以通过这个接口更改维修装备状态")
    @PostMapping(value = "/change")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity changeRepairDeviceStatus(@RequestBody @Validated RepairStatusChangeVo repairStatusChangeVo) {
        //判断维修记录的维修状态
        repairStatusChangeVo.getId().forEach(integer -> {
            RepairDetail repairDetail = deviceRepairDetailService.getOne(integer);
            if (repairDetail.getRepairStatus()!=1&&repairDetail.getRepairStatus()!=9){
                throw new ApiException(ResponseEntity.status(303).body("序列号"+repairDetail.getSeqNumber()+"的装备已被其他专管员操作"));
            }
        });
        //各单位阅知map
        Map<Integer,List<Integer>> messageMap = new HashMap<>();
        for (Integer id : repairStatusChangeVo.getId()) {
            //获取维修详情单
            RepairDetail repairDetail1 = deviceRepairDetailService.getOne(id);
            if (repairDetail1.getDeviceRepairBillId()==0){
                repairDetail1.setRepairStatus(5);
                deviceRepairDetailService.update(repairDetail1);
                DeviceLibrary deviceLibrary = deviceLibraryService.getOne(repairDetail1.getDeviceId());
                deviceLibrary.setLifeStatus(2);
                deviceLibraryService.update(deviceLibrary);
                //存装备日志
                DeviceLogDto deviceLogDto = new DeviceLogDto(deviceLibrary.getId(), "维修完成，装备状态改为在库", null);
                deviceLogService.addLog(deviceLogDto);
            }
            else {
                //获取旧状态
                Integer oldStatus = repairDetail1.getRepairStatus();
                if (repairStatusChangeVo.getNewStatus()==2&&repairDetail1.getOwnUnit().equals(userUtils.getCurrentUserUnitName())){
                    repairDetail1.setRepairStatus(5);
                }
                else {
                    //修改当前任务维修详情单该装备状态
                    repairDetail1.setRepairStatus(repairStatusChangeVo.getNewStatus());
                }
                //如果修改为已报废，更改新装备详情id为0,,更新装备状态
                if (repairStatusChangeVo.getNewStatus() == 4) {
                    repairDetail1.setNewDeviceDetailId(0);
                    DeviceLibrary deviceLibrary = deviceLibraryService.getOne(repairDetail1.getDeviceId());
                    deviceLibrary.setLifeStatus(5);
                    deviceLibraryService.update(deviceLibrary);
                }
                deviceRepairDetailService.update(repairDetail1);
                //获取装备名称
                String deviceName = deviceLibraryService.getOne(repairDetail1.getDeviceId()).getName();
                //添加业务日志
                List<FileVo> fileVos = new ArrayList<>();
                if (repairStatusChangeVo.getFileName() != null && repairStatusChangeVo.getFileUrl() != null) {
                    FileVo fileVo = new FileVo("报废单", repairStatusChangeVo.getFileName(), repairStatusChangeVo.getFileUrl());
                    fileVos.add(fileVo);
                }
                String remark = "将装备" + deviceName + "状态由" + GlobalMap.getRepairStatusMap().get(oldStatus).name + "改为" + GlobalMap.getRepairStatusMap().get(repairStatusChangeVo.getNewStatus()).name;
                //装备日志
                DeviceLogDto deviceLogDto = new DeviceLogDto(repairDetail1.getDeviceId(), remark, fileVos);
                deviceLogService.addLog(deviceLogDto);
                //如果状态改为了待领取
                if (repairStatusChangeVo.getNewStatus() == 2) {
                    Integer unitId = userPublicService.getOne(repairDetail1.getCreateUserId()).getUnitsId();
                    //存在父节点
                    if (repairDetail1.getPid() != null) {
                        RepairDetail repairDetail = deviceRepairDetailService.getOne(repairDetail1.getPid());
                        //往map里插入该单位的维修详情id
                        if (messageMap.get(unitId) == null) {
                            messageMap.put(unitId, Collections.singletonList(repairDetail.getId()));
                        } else {
                            List<Integer> ids = new ArrayList<Integer>(messageMap.getOrDefault(unitId, new ArrayList<>()));
                            ids.add(repairDetail.getId());
                            messageMap.put(unitId, ids);
                        }
                    } else {
                        if (messageMap.get(unitId) == null) {
                            messageMap.put(unitId, Collections.singletonList(repairDetail1.getId()));
                        } else {
                            List<Integer> ids = new ArrayList<Integer>(messageMap.getOrDefault(unitId, new ArrayList<>()));
                            ids.add(repairDetail1.getId());
                            messageMap.put(unitId, ids);
                        }
                    }
                }
            }
        }
        //根据map每个单位发阅知
        messageMap.keySet().forEach(integer -> {
            List<Integer> ids2 = new ArrayList<>();
            ids2.addAll(userDao.findAllByUnitsId(integer).stream()
                    .map(User::getUserId)
                    .collect(Collectors.toList()));
            MessageBto messageBto2 = new MessageBto(0, 5, "待领取送修装备", ids2);
            messageBto2.setRecord(StringSplitUtil.idListToString(messageMap.get(integer)));
            messageService.add(messageBto2);
        });
        return ResultUtil.success("修改成功");
    }

    @ApiOperation(value = "查询维修详情", notes = "可以通过这个接口查询维修详情")
    @GetMapping(value = "/detail/{id}")
    public ResponseEntity getDetail(@PathVariable("id") int id) {
        Map<Integer,DeviceLibrary> deviceLibraryMap = deviceLibraryService.getAllDeviceMap();
        //获取task
        TaskBto taskBto = taskService.get(id);
        RepairBillDetailVo repairBillDetailVo = new RepairBillDetailVo();
        //判断维修业务类型
        switch (taskBto.getBusinessType()) {
            //送修业务
            case 5:
                //获取维修单
                RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
                repairBillDetailVo.setRepairBill(repairBill);
                //获取装备列表
                RepairSendBill repairSendBill = deviceRepairSendBillDao.findByDeviceRepairBillId(repairBill.getId());
                //set需要转换的字段
                repairSendBill.setSendFileList(FilesUtil.stringFileToList(repairSendBill.getSendFiles()));
                repairSendBill.setReceiveFileList(FilesUtil.stringFileToList(repairSendBill.getReceiveFiles()));
                if (repairSendBill.getStartUseraId() != null) {
                    repairSendBill.setStartUserA(userPublicService.getOne(repairSendBill.getStartUseraId()).getName());
                }
                repairSendBill.setStartUserB(repairSendBill.getAgent());
                if (repairSendBill.getRepairUseraId() != null) {
                    repairSendBill.setRepairUserA(userPublicService.getOne(repairSendBill.getRepairUseraId()).getName());
                }
                if (repairSendBill.getRepairUserbId() != null) {
                    repairSendBill.setRepairUserB(userPublicService.getOne(repairSendBill.getRepairUserbId()).getName());
                }
                if (repairSendBill.getScriptJson()!=null){
                    repairSendBill.setScripts(JacksonUtil.readValue(repairSendBill.getScriptJson(),new TypeReference<List<ScriptSaveVo>>() {}));
                }
                repairBillDetailVo.setRepairSendBill(repairSendBill);
                List<DeviceLibrary> deviceLibraries = new ArrayList<>();
                if (repairSendBill.getRepairDeviceCheckDetail() != null) {
                    //获取发送装备信息
                    String[] strings1 = repairSendBill.getRepairDeviceCheckDetail().split("x");
                    for (String s : strings1) {
                        if (s.length() >= 2 && "1".equals(s.substring(s.length() - 1))) {
                            Integer deviceId = Integer.parseInt(s.substring(0, s.length() - 1));
                            Integer checkResult = Integer.parseInt(s.substring(s.length() - 1));
                            DeviceLibrary deviceLibraryEntity = deviceLibraryMap.get(deviceId);
                            deviceLibraryEntity.setCheckResult(checkResult);
                            deviceLibraries.add(deviceLibraryEntity);
                        }
                    }
                }
                //获取维修详情
                List<RepairDetail> repairDetails = getRepairDetail(repairBill.getId());
                repairDetails.forEach(repairDetail -> repairDetail.setLocationUnit(deviceLibraryMap.get(repairDetail.getDeviceId()).getLocationUnit()));
                repairBillDetailVo.setRepairDetails(repairDetails);
                //设置装备备注
                deviceLibraries.forEach(deviceLibrary -> {
                    for (RepairDetail r : repairDetails) {
                        if (r.getDeviceId().equals(deviceLibrary.getId())) {
                            deviceLibrary.setRemark(r.getRemark());
                            deviceLibrary.setRepairStatus(r.getRepairStatus());
                        }
                    }
                });
                if (repairSendBill.getRepairReciveCheckDetail() != null) {
                    //获取接收装备信息
                    List<DeviceLibrary> deviceLibraries1 = new ArrayList<>();
                    String[] strings = repairSendBill.getRepairReciveCheckDetail().split("x");
                    for (String s : strings) {
                        if (s.length() >= 2 && "1".equals(s.substring(s.length() - 1))) {
                            Integer deviceId = Integer.parseInt(s.substring(0, s.length() - 1));
                            Integer checkResult = Integer.parseInt(s.substring(s.length() - 1));
                            DeviceLibrary deviceLibraryEntity = deviceLibraryMap.get(deviceId);
                            deviceLibraryEntity.setCheckResult(checkResult);
                            deviceLibraries1.add(deviceLibraryEntity);
                        }
                    }
                    //set维修原因
                    deviceLibraries1.forEach(deviceLibrary -> {
                        for (RepairDetail r : repairDetails) {
                            if (r.getDeviceId().equals(deviceLibrary.getId())) {
                                deviceLibrary.setRemark(r.getRemark());
                            }
                        }
                    });
                    repairBillDetailVo.setReceiveDevices(deviceLibraries1);
                }
                repairBillDetailVo.setDeviceLibraries(deviceLibraries);
                break;
            case 10:
                //获取维修退回单
                RepairBackBill repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
                //set需要转换的字段
                repairBackBill.setSendFileList(FilesUtil.stringFileToList(repairBackBill.getSendFiles()));
                repairBackBill.setReceiveFileList(FilesUtil.stringFileToList(repairBackBill.getReceiveFiles()));
                if (repairBackBill.getScriptJson()!=null){
                    repairBackBill.setScripts(JacksonUtil.readValue(repairBackBill.getScriptJson(),new TypeReference<List<ScriptSaveVo>>() {}));
                }
                repairBillDetailVo.setRepairBackBill(repairBackBill);
                if (repairBackBill.getStartUseraId() != null) {
                    repairBackBill.setStartUserA(userPublicService.getOne(repairBackBill.getStartUseraId()).getName());
                }
                repairBackBill.setStartUserB(repairBackBill.getAgent());
                if (repairBackBill.getReceiveUseraId() != null) {
                    repairBackBill.setReceiveUserA(userPublicService.getOne(repairBackBill.getReceiveUseraId()).getName());
                }
                if (repairBackBill.getReceiveUserbId() != null) {
                    repairBackBill.setReceiveUserB(userPublicService.getOne(repairBackBill.getReceiveUserbId()).getName());
                }
                List<DeviceLibrary> deviceLibraryList = new ArrayList<>();
                List<DeviceLibrary> deviceLibraryList2 = new ArrayList<>();
                String[] strings1;
                if (repairBackBill.getBackReciveCheckDetail() != null) {
                    //接收的装备
                    strings1 = repairBackBill.getBackReciveCheckDetail().split("x");
                    for (String s : strings1) {
                        if (s.length() >= 2 && "1".equals(s.substring(s.length() - 1))) {
                            Integer deviceId = Integer.parseInt(s.substring(0, s.length() - 1));
                            Integer checkResult = Integer.parseInt(s.substring(s.length() - 1));
                            DeviceLibrary deviceLibraryEntity = deviceLibraryMap.get(deviceId);
                            deviceLibraryEntity.setCheckResult(checkResult);
                            deviceLibraryList.add(deviceLibraryEntity);
                        }
                    }
                }
                if (repairBackBill.getBackCheckDetail() != null) {
                    //发送的装备
                    strings1 = repairBackBill.getBackCheckDetail().split("x");
                    for (String s : strings1) {
                        if (s.length() >= 2 && "1".equals(s.substring(s.length() - 1))) {
                            Integer deviceId = Integer.parseInt(s.substring(0, s.length() - 1));
                            Integer checkResult = Integer.parseInt(s.substring(s.length() - 1));
                            DeviceLibrary deviceLibraryEntity = deviceLibraryMap.get(deviceId);
                            deviceLibraryEntity.setCheckResult(checkResult);
                            deviceLibraryList2.add(deviceLibraryEntity);
                        }
                    }
                }
                //获取维修详情
                List<RepairDetail> repairDetailList = repairDetailDao.findByRepairBackBillId(repairBackBill.getId());
                repairDetailList.forEach(repairDetail -> {
                    repairDetail.setConfigName();
                });
                repairBillDetailVo.setRepairDetails(repairDetailList);
                //设置装备备注和维修状态
                deviceLibraryList.forEach(deviceLibrary -> {
                    for (RepairDetail r : repairDetailList) {
                        if (r.getDeviceId().equals(deviceLibrary.getId())) {
                            deviceLibrary.setRemark(r.getBackRemark());
                            if (r.getPid()!=null) {
                                deviceLibrary.setRepairStatus(deviceRepairDetailService.getOne(r.getPid()).getRepairStatus());
                            }
                            else {
                                deviceLibrary.setRepairStatus(r.getRepairStatus());
                            }
                        }
                    }
                });
                deviceLibraryList2.forEach(deviceLibrary -> {
                    for (RepairDetail r : repairDetailList) {
                        if (r.getDeviceId().equals(deviceLibrary.getId())) {
                            deviceLibrary.setRemark(r.getBackRemark());
                            if (r.getPid()!=null) {
                                deviceLibrary.setRepairStatus(deviceRepairDetailService.getOne(r.getPid()).getRepairStatus());
                            }
                            else {
                                deviceLibrary.setRepairStatus(r.getRepairStatus());
                            }
                        }
                    }
                });
                repairBillDetailVo.setDeviceLibraries(deviceLibraryList2);
                repairBillDetailVo.setReceiveDevices(deviceLibraryList);
                break;
            default:
                break;
        }
        return ResultUtil.success(repairBillDetailVo);
    }

    @ApiOperation(value = "查询维修管理列表", notes = "可以通过这个接口查询维修管理列表")
    @PostMapping(value = "/repairList")
    public ResponseEntity getRepairList(@RequestBody RepairTaskSelectVo repairTaskSelectVo) {
        Integer type = repairTaskSelectVo.getType();
        String unitName = userUtils.getCurrentUserUnitName();
        //是否有年份筛选
        Integer year = repairTaskSelectVo.getYear();
        Boolean hasYear = year!=null&&year>0;
        //待维修装备
        if (type==1){
            List<Integer> integerList = new ArrayList<>();
            integerList.add(1);
            integerList.add(9);
            //筛选维修状态为1，9的
            List<RepairDetail> repairDetails = repairDetailDao.findAllByRepairStatusIn(integerList,repairTaskSelectVo.getPageable().getSort());
            repairDetails.forEach(repairDetail -> {
                repairDetail.setConfigName();
            });
            //所在为当前单位
            List<RepairDetail> repairDetails1 = repairDetails.stream().filter(repairDetail -> repairDetail.getLocationUnit().equals(unitName)).collect(Collectors.toList());
            return ResponseEntity.ok(PageUtil.getPerPage(repairTaskSelectVo.getPage(),repairTaskSelectVo.getSize(),repairDetails1,repairTaskSelectVo.getPageable()));
        }
        //送修装备
        else if(type==2){
            List<Integer> integerList = new ArrayList<>();
            integerList.add(5);
            integerList.add(9);
            integerList.add(4);
            //过滤掉状态4，5，9
            List<RepairDetail> repairDetails1 = repairDetailDao.findAllByRepairStatusNotIn(integerList,repairTaskSelectVo.getPageable().getSort());
            repairDetails1.forEach(repairDetail -> {
                repairDetail.setConfigName();
            });
            //发起送修的单位为当前单位
            List<RepairDetail> repairDetails2 = repairDetails1.stream().filter(repairDetail -> userPublicService.findUnitsNameByUserId(repairDetail.getCreateUserId()).equals(unitName)).collect(Collectors.toList());
            return ResponseEntity.ok(PageUtil.getPerPage(repairTaskSelectVo.getPage(),repairTaskSelectVo.getSize(),repairDetails2,repairTaskSelectVo.getPageable()));
        }
        //待领取装备
        else if(type==3){
            //筛选出维修状态为2的
            List<RepairDetail> repairDetails = repairDetailDao.findAllByRepairStatus(2,repairTaskSelectVo.getPageable().getSort());
            repairDetails.forEach(repairDetail -> {
                repairDetail.setConfigName();
            });
            //所在在当前单位的
            List<RepairDetail> repairDetails2 = repairDetails.stream().filter(repairDetail -> repairDetail.getLocationUnit().equals(unitName)).collect(Collectors.toList());
            return ResponseEntity.ok(PageUtil.getPerPage(repairTaskSelectVo.getPage(),repairTaskSelectVo.getSize(),repairDetails2,repairTaskSelectVo.getPageable()));
        }
        //已领取装备
        else if(type==4){
            Integer level = userUtils.getCurrentUnitLevel();
            List<RepairDetail> repairDetails;
            if (level==1) {
                repairDetails = repairDetailDao.findAllByRepairStatus(5, repairTaskSelectVo.getPageable().getSort());
            }
            else if (level==2) {
                repairDetails = repairDetailDao.findAllByRepairStatus(5, repairTaskSelectVo.getPageable().getSort());
            }
            else {
                throw new ApiException("区县没有维修完成列表");
            }
            repairDetails.forEach(repairDetail -> {
                repairDetail.setConfigName();
            });
            List<String> units = unitsService.findSuperiorUnitsList().stream().map(Units::getName).collect(Collectors.toList());
            units.addAll(unitsService.findBySubordinateNotOneself(userUtils.getCurrentUnitId()).stream().map(Units::getName).collect(Collectors.toList()));
            //所在单位在当前单位下级的
            List<RepairDetail> repairDetails2 = repairDetails.stream().filter(repairDetail -> units.contains(repairDetail.getLocationUnit())&&(!hasYear||repairDetail.getUpdateTime().getYear()==year-1900)).collect(Collectors.toList());
            return ResponseEntity.ok(PageUtil.getPerPage(repairTaskSelectVo.getPage(),repairTaskSelectVo.getSize(),repairDetails2,repairTaskSelectVo.getPageable()));
        }
        //已报废装备
        else if(type==5){
            Integer level = userUtils.getCurrentUnitLevel();
            List<RepairDetail> repairDetails;
            if (level==1) {
                repairDetails = repairDetailDao.findAllByRepairStatus(4, repairTaskSelectVo.getPageable().getSort());
            }
            else {
                throw new ApiException("区县没有维修完成列表");
            }
            repairDetails.forEach(repairDetail -> {
                repairDetail.setConfigName();
            });
            List<RepairDetail> repairDetails2 = repairDetails.stream().filter(repairDetail -> !hasYear||repairDetail.getUpdateTime().getYear()==year-1900).collect(Collectors.toList());
            return ResponseEntity.ok(PageUtil.getPerPage(repairTaskSelectVo.getPage(),repairTaskSelectVo.getSize(),repairDetails2,repairTaskSelectVo.getPageable()));
        }
        else {
            throw new ApiException("type只能为1，2，3，4，5");
        }
    }

    @ApiOperation(value = "上传维修记录备注", notes = "可以通过这个接口上传维修记录备注")
    @PostMapping(value = "/uploadRecord")
    public ResponseEntity uploadRecord(@RequestBody RepairRecord repairRecord) {
        Integer level = userUtils.getCurrentUnitLevel();
        RepairDetail repairDetail = deviceRepairDetailService.getOne(repairRecord.getId());
        //省市县三种备注
        if (level==1) {
            repairDetail.setRecord(repairRecord.getRecord());
        }
        else if (level==2) {
            repairDetail.setRecord2(repairRecord.getRecord());
        }
        else if (level==3) {
            repairDetail.setRecord3(repairRecord.getRecord());
        }
        deviceRepairDetailService.update(repairDetail);
        return ResponseEntity.ok("更新成功");
    }

    @ApiOperation(value = "查询待领取装备阅知详情", notes = "可以通过这个接口查询待领取装备阅知详情")
    @GetMapping(value = "/read/detail/{string}")
    public ResponseEntity getDetail(@PathVariable("string") String string) {
        List<RepairDetail> repairDetails = new ArrayList<>();
        List<Integer> ids = StringSplitUtil.userIdSplit(string);
        ids.forEach(integer -> {
            RepairDetail repairDetail = deviceRepairDetailService.getOne(integer);
            repairDetails.add(repairDetail);
        });
        return ResponseEntity.ok(repairDetails);
    }

    @ApiOperation(value = "维修换新", notes = "可以通过这个接口维修换新")
    @PostMapping(value = "/changeNew")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity change(@RequestBody DeviceEditVo deviceEditVo){
        //获取维修详情和装备信息
        RepairDetail repairDetail = deviceRepairDetailService.getOne(deviceEditVo.getId());
        DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(deviceEditVo.getDeviceId());
        //创建新装备
        DeviceLibrary newDevice = new DeviceLibrary();
        BeanUtils.copyProperties(deviceLibraryEntity,newDevice);
        newDevice.setId(null);
        newDevice.setLocationUnit(userUtils.getCurrentUserUnitName());
        //如果所属和所在相同，装备直接入库，状态为在库
        if (newDevice.getOwnUnit().equals(newDevice.getLocationUnit())) {
            newDevice.setLifeStatus(2);
        }
        DeviceLibrary deviceLibrary = deviceLibraryService.addEntity(newDevice);
        //改变旧装备绑定的子装备的父id
        List<DeviceLibrary> deviceLibraries = deviceLibraryDao.getAllByPartParentId(deviceLibraryEntity.getId());
        deviceLibraries.forEach(deviceLibrary1 -> {
            deviceLibrary1.setPartParentId(deviceLibrary.getId());
            deviceLibraryService.update(deviceLibrary1);
        });
        //添加新的维修换新装备记录
        RepairDetail newRepairDetail = new RepairDetail();
        BeanUtils.copyProperties(repairDetail,newRepairDetail);
        newRepairDetail.setId(null);
        newRepairDetail.setDeviceId(deviceLibrary.getId());
        newRepairDetail.setLocationUnit(userUtils.getCurrentUserUnitName());
        newRepairDetail.setRepairStatus(5);
        //如果该维修记录有父id
        if (newRepairDetail.getPid()!=null) {
            //获取父记录，改变维修状态和所在
            RepairDetail repairDetail1 = deviceRepairDetailService.getOne(repairDetail.getPid());
            repairDetail1.setRepairStatus(2);
            repairDetail1.setLocationUnit(userUtils.getCurrentUserUnitName());
            deviceRepairDetailService.update(repairDetail1);
            //给下级单位发送阅知
            Integer unitId = userPublicService.getOne(repairDetail1.getCreateUserId()).getUnitsId();
            List<Integer> integerList = new ArrayList<>();
            integerList.addAll(userDao.findAllByUnitsId(unitId).stream()
                    .map(User::getUserId)
                    .collect(Collectors.toList()));
            MessageBto messageBto2 = new MessageBto(0, 5, "待领取送修装备", integerList);
            messageBto2.setRecord(String.valueOf(repairDetail1.getId()));
            messageService.add(messageBto2);
        }
        //旧的维修记录改为已报废
        repairDetail.setRepairStatus(4);
        repairDetail.setLocationUnit(deviceLibraryEntity.getLocationUnit());
        repairDetail.setOwnUnit(deviceLibraryEntity.getLocationUnit());
        //装备改为已报废
        deviceLibraryEntity.setOwnUnit(deviceLibraryEntity.getLocationUnit());
        deviceLibraryEntity.setLifeStatus(5);
        deviceLibraryService.update(deviceLibraryEntity);
        if (deviceEditVo.getUpdateVoList() != null) {
            DeviceLibraryUpdateVo libraryUpdateVo = deviceEditVo.getUpdateVoList();
            //生产号修改
            if (libraryUpdateVo.getProdNumber() != null && !libraryUpdateVo.getProdNumber().equals(deviceLibraryEntity.getProdNumber())) {
                //添加装备日志
                String remark = "装备换新:将装备生产序列号由" + deviceLibraryEntity.getProdNumber() + "换为" + libraryUpdateVo.getProdNumber();
                DeviceLogDto deviceLogDto = new DeviceLogDto(deviceEditVo.getDeviceId(), remark, null);
                deviceLogService.addLog(deviceLogDto);
                deviceLibrary.setProdNumber(libraryUpdateVo.getProdNumber());
            }
            //序列号修改
            if (libraryUpdateVo.getSeqNumber() != null && !libraryUpdateVo.getSeqNumber().equals(deviceLibraryEntity.getSeqNumber())) {
                if (deviceLibraryDao.getAllBySeqNumber(libraryUpdateVo.getSeqNumber()).size()>0){
                    throw new ApiException("序列号"+libraryUpdateVo.getSeqNumber()+"已存在");
                }
                else {
                    //添加装备日志
                    String remark = "装备换新:将装备序列号由" + deviceLibraryEntity.getSeqNumber() + "换为" + libraryUpdateVo.getSeqNumber();
                    DeviceLogDto deviceLogDto = new DeviceLogDto(deviceEditVo.getDeviceId(), remark, null);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibrary.setSeqNumber(libraryUpdateVo.getSeqNumber());
                    newRepairDetail.setSeqNumber(libraryUpdateVo.getSeqNumber());
                }
            }
        }
        deviceLibraryService.update(deviceLibrary);
        RepairDetail repairDetail3 = deviceRepairDetailService.save(newRepairDetail);
        //set换新后记录的id
        repairDetail.setNewDeviceDetailId(repairDetail3.getId());
        deviceRepairDetailService.update(repairDetail);
        //修改所有父维修记录序列号、装备序列号、所在单位
        if (repairDetail3.getPid()!=null){
            RepairDetail repairDetail1 = deviceRepairDetailService.getOne(repairDetail3.getPid());
            repairDetail1.setSeqNumber(repairDetail3.getSeqNumber());
            repairDetail1.setDeviceId(repairDetail3.getDeviceId());
            repairDetail1.setLocationUnit(userUtils.getCurrentUserUnitName());
            deviceRepairDetailService.update(repairDetail1);
            if (repairDetail1.getPid() != null) {
                RepairDetail repairDetail2 = deviceRepairDetailService.getOne(repairDetail1.getPid());
                repairDetail2.setSeqNumber(repairDetail3.getSeqNumber());
                repairDetail2.setDeviceId(repairDetail3.getDeviceId());
                repairDetail2.setLocationUnit(userUtils.getCurrentUserUnitName());
                deviceRepairDetailService.update(repairDetail2);
            }
        }
        //添加装备换新记录
        DeviceChange deviceChange = new DeviceChange();
        deviceChange.setNewDeviceId(deviceLibrary.getId());
        deviceChange.setOldDeviceId(deviceLibraryEntity.getId());
        //换新文件
        if (deviceEditVo.getSendFiles()!=null&&deviceEditVo.getSendFiles().size()>0) {
            deviceChange.setChangeFiles(FilesUtil.stringFileToList(deviceEditVo.getSendFiles()));
        }
        deviceChangeService.add(deviceChange);
        return ResultUtil.success("更新成功");
    }

    @ApiOperation(value = "验证装备序列号是否存在", notes = "验证装备序列号是否存在")
    @GetMapping(value = "/validation/seq/{seqNumber}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity validation(@PathVariable String seqNumber){
        return ResponseEntity.ok(deviceLibraryDao.existsBySeqNumber(seqNumber));
    }


    @ApiOperation(value = "发件方上传领取单", notes = "上传领取单")
    @PostMapping(value = "/uploadFile")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity uploadFile(@RequestBody @Validated com.tykj.dev.device.repair.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_BACK_SEND_FILE);
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),statusEnums);
        RepairBackBill repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
        //保存账单
        repairBackBill.setSendFiles(FilesUtil.stringFileToList(fileVo.getSendFiles()));
        List<Integer> idList = new ArrayList<>();
        if (fileVo.getReceiveUseraId()!=null) {
            repairBackBill.setReceiveUseraId(fileVo.getReceiveUseraId());
            idList.add(fileVo.getReceiveUseraId());
        }
        if (fileVo.getReceiveUserbId()!=null) {
            repairBackBill.setReceiveUserbId(fileVo.getReceiveUserbId());
            idList.add(fileVo.getReceiveUserbId());
        }
        //签发人阅知
        if (fileVo.getStartUserbId()!=null){
            repairBackBill.setStartUserbId(fileVo.getStartUserbId());
            repairBackBill.setAgent(userPublicService.getOne(fileVo.getStartUserbId()).getName());
            MessageBto messageBto1 = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为签发人", Collections.singletonList(fileVo.getStartUserbId()), 1);
            messageService.add(messageBto1);
        }
        repairBackBill.setBackStatus(5);
        repairBackBill.setReceiveTime(new Date());
        deviceRepairBackBillService.update(repairBackBill);
        List<Integer> ids = StringSplitUtil.split(repairBackBill.getBackCheckDetail());
        //业务完结
        taskService.moveToEnd(taskBto);
        //主业务完结
        taskService.moveToEnd(taskService.get(taskBto.getParentTaskId()));
        List<Integer> userIds = userPublicService.findOtherUser(userUtils.getCurrentUserId());
        userIds.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(repairBackBill.getReceiveUnit())).stream()
                .map(User::getUserId)
                .collect(Collectors.toList()));
        //阅知
        MessageBto messageBto1 = new MessageBto(taskBto.getParentTaskId(),taskBto.getBusinessType(),"业务办结",userIds,1);
        messageService.add(messageBto1);
        //装备日志
        List<FileVo> fileVoList = new ArrayList<>();
        fileVo.getSendFiles().forEach(fileRet -> fileVoList.add(new FileVo("领取单", fileRet.getName(), fileRet.getPreviewPath())));
        ids.forEach(integer -> {
            DeviceLogDto deviceLogDto = new DeviceLogDto(integer, "上传领取单", fileVoList);
            deviceLogService.addLog(deviceLogDto);
            DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(integer);
            deviceLibraryEntity.setLocationUnit(repairBackBill.getReceiveUnit());
            deviceLibraryEntity.setLifeStatus(2);
            deviceLibraryEntity.setManageStatus(1);
            deviceLibraryService.update(deviceLibraryEntity);
        });
        //获取维修详情
        List<RepairDetail> repairDetailList = repairDetailDao.findByRepairBackBillId(repairBackBill.getId());
        //单位阅知map
        Map<Integer,List<Integer>> messageMap = new HashMap<>();
        //改变维修详情的维修状态、所在单位
        repairDetailList.forEach(repairDetail -> {
            repairDetail.setRepairStatus(5);
            repairDetail.setLocationUnit(repairBackBill.getReceiveUnit());
            if (repairDetail.getPid()!=null) {
                RepairDetail repairDetail1 = deviceRepairDetailService.getOne(repairDetail.getPid());
                repairDetail1.setRepairStatus(2);
                repairDetail1.setLocationUnit(repairBackBill.getReceiveUnit());
                deviceRepairDetailService.update(repairDetail1);
                Integer unitId = userPublicService.getOne(repairDetail1.getCreateUserId()).getUnitsId();
                if (messageMap.get(unitId)==null) {
                    messageMap.put(unitId, Collections.singletonList(repairDetail1.getId()));
                }
                else {
                    List<Integer> integers = new ArrayList<>(messageMap.getOrDefault(unitId, new ArrayList<>()));
                    integers.add(repairDetail1.getId());
                    messageMap.put(unitId,integers);
                }
                if (repairDetail1.getPid()!=null){
                    RepairDetail repairDetail2 = deviceRepairDetailService.getOne(repairDetail1.getPid());
                    repairDetail2.setLocationUnit(repairBackBill.getReceiveUnit());
                    deviceRepairDetailService.update(repairDetail2);
                }
            }
            deviceRepairDetailService.update(repairDetail);
        });
        //经办人阅知
//        if (idList.size()>0) {
//            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", idList, 1);
//            messageService.add(messageBto);
//        }
        //按map中各个单位发送阅知
        messageMap.keySet().forEach(integer -> {
            List<Integer> integerList = new ArrayList<>();
            integerList.addAll(userDao.findAllByUnitsId(integer).stream()
                    .map(User::getUserId)
                    .collect(Collectors.toList()));
            MessageBto messageBto2 = new MessageBto(0, 5, "待领取送修装备", integerList);
            //阅知记录id拼接
            messageBto2.setRecord(StringSplitUtil.idListToString(messageMap.get(integer)));
            messageService.add(messageBto2);
        });
        return ResponseEntity.ok("OK");
    }

    @ApiOperation(value = "市县上传发送方送修单", notes = "市县上传维修单")
    @PostMapping(value = "/uploadRepairFile")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity uploadRepairFile(@RequestBody @Validated com.tykj.dev.device.repair.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_SEND_FILE);
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),statusEnums);
        //获取账单
        RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
        RepairSendBill repairSendBill = deviceRepairSendBillDao.findByDeviceRepairBillId(repairBill.getId());
        List<RepairDetail> repairDetailEntities = deviceRepairDetailService.findByBillId(repairBill.getId());
        //保存账单
        repairSendBill.setSendFiles(FilesUtil.stringFileToList(fileVo.getSendFiles()));
        List<Integer> idList = new ArrayList<>();
        //签发人阅知
        if (fileVo.getStartUserbId()!=null){
            String startUserB = userPublicService.getOne(fileVo.getStartUserbId()).getName();
            repairBill.setStartUserB(startUserB);
            repairSendBill.setStartUserbId(fileVo.getStartUserbId());
            repairSendBill.setAgent(startUserB);
            MessageBto messageBto1 = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为签发人", Collections.singletonList(fileVo.getStartUserbId()), 1);
            messageService.add(messageBto1);
        }
        if (fileVo.getReceiveUseraId()!=null) {
            repairBill.setRepairUserA(userPublicService.getOne(fileVo.getReceiveUseraId()).getName());
            repairSendBill.setRepairUseraId(fileVo.getReceiveUseraId());
            idList.add(fileVo.getReceiveUseraId());
        }
        if (fileVo.getReceiveUserbId()!=null) {
            repairBill.setRepairUserB(userPublicService.getOne(fileVo.getReceiveUserbId()).getName());
            repairSendBill.setRepairUserbId(fileVo.getReceiveUserbId());
            idList.add(fileVo.getReceiveUserbId());
        }
        repairBill.setRepairStatus(4);
        repairSendBill.setRepairStatus(5);
        deviceRepairBillService.update(repairBill);
        deviceRepairSendBillService.update(repairSendBill);
        List<Integer> ids = StringSplitUtil.split(repairSendBill.getRepairDeviceCheckDetail());
        //业务完结
        taskService.moveToEnd(taskBto);
        //主业务完结
        taskService.moveToEnd(taskService.get(taskBto.getParentTaskId()));
        List<Integer> userIds = userPublicService.findOtherUser(userUtils.getCurrentUserId());
        userIds.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(repairSendBill.getReceiveUnit())).stream()
                .map(User::getUserId)
                .collect(Collectors.toList()));
        //业务办结阅知
        MessageBto messageBto1 = new MessageBto(taskBto.getParentTaskId(),taskBto.getBusinessType(),"业务办结",userIds,1);
        messageService.add(messageBto1);
        //装备日志
        List<FileVo> fileVoList = new ArrayList<>();
        fileVo.getSendFiles().forEach(fileRet -> fileVoList.add(new FileVo("维修单", fileRet.getName(), fileRet.getPreviewPath())));
        ids.forEach(integer -> {
            DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(integer);
            deviceLibraryEntity.setLifeStatus(4);
            deviceLibraryEntity.setLocationUnit(repairBill.getReceiveUnit());
            deviceLibraryEntity.setManageStatus(1);
            deviceLibraryService.update(deviceLibraryEntity);
            DeviceLogDto deviceLogDto = new DeviceLogDto(integer, "上传维修单", fileVoList);
            deviceLogService.addLog(deviceLogDto);
        });
        //改变维修详情装备所在单位为当前单位
        repairDetailEntities.forEach(repairDetail -> {
            repairDetail.setLocationUnit(repairBill.getReceiveUnit());
            repairDetail.setRepairStatus(1);
            deviceRepairDetailService.update(repairDetail);
            //同时改变父详情
            if (repairDetail.getPid()!=null){
                RepairDetail repairDetail1 = deviceRepairDetailService.getOne(repairDetail.getPid());
                repairDetail1.setLocationUnit(repairBill.getReceiveUnit());
                deviceRepairDetailService.update(repairDetail1);
            }
        });
        //经办人阅知
//        if (idList.size()>0) {
//            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", idList, 1);
//            messageService.add(messageBto);
//        }
        return ResponseEntity.ok("OK");
    }

    /**
     * @param repairBillId 维修单id
     * @return 维修详情列表
     * 根据维修单Id查询维修详情
     */
    private List<RepairDetail> getRepairDetail(int repairBillId) {
        List<RepairDetail> repairDetails = deviceRepairDetailService.findByBillId(repairBillId);
        return repairDetails;
    }

    @ApiOperation(value = "上传送修发送方签发人", notes = "上传发送方签发人")
    @PostMapping(value = "/updateSendAgent")
    public ResponseEntity updateSendAgent(@RequestBody AgentBackVo agentBackVo){
        TaskBto taskBto = taskService.get(agentBackVo.getId());
        List<Integer> idList = new ArrayList<>();
        idList.add(agentBackVo.getStartUserbId());
        //签发人阅知
        MessageBto messageBto = new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"被选为签发人",idList,1);
        messageService.add(messageBto);
        RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
        repairBill.setStartUserB(agentBackVo.getName());
        RepairSendBill repairSendBill = deviceRepairSendBillDao.findByDeviceRepairBillId(repairBill.getId());
        repairSendBill.setStartUserbId(agentBackVo.getStartUserbId());
        deviceRepairSendBillService.update(repairSendBill);
        return ResponseEntity.ok(deviceRepairBillService.update(repairBill));
    }

    @ApiOperation(value = "上传领取发送方签发人", notes = "上传发送方签发人")
    @PostMapping(value = "/updateBackAgent")
    public ResponseEntity updateBackAgent(@RequestBody AgentBackVo agentBackVo){
        TaskBto taskBto = taskService.get(agentBackVo.getId());
        List<Integer> idList = new ArrayList<>();
        idList.add(agentBackVo.getStartUserbId());
        //签发人阅知
        MessageBto messageBto = new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"被选为签发人",idList,1);
        messageService.add(messageBto);
        RepairBackBill repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
        repairBackBill.setAgent(agentBackVo.getName());
        repairBackBill.setStartUserbId(agentBackVo.getStartUserbId());
        return ResponseEntity.ok(deviceRepairBackBillService.update(repairBackBill));
    }
}
