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.DeviceEditVo;
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.task.subject.bto.TaskLogBto;
import com.tykj.dev.device.user.read.service.MessageService;
import com.tykj.dev.device.user.read.subject.bto.MessageBto;
import com.tykj.dev.device.user.subject.dao.UserDao;
import com.tykj.dev.device.user.subject.entity.User;
import com.tykj.dev.device.user.subject.service.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.RepairStatusEnum;
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 = "/saveRepairBill")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity saveRepairBill(@RequestBody RepairBillSaveVo repairBillSaveVo) {
        //第一次保存
        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);
            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);
            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);
        }
        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());
            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);
        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);
        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()));
        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){
                    throw new ApiException(ResponseEntity.status(303).body("序列号"+repairDetail.getSeqNumber()+"的装备已被其他专管员操作"));
                }
            });
        }
        Integer level = userUtils.getCurrentUnitLevel();
        //添加维修单和送修单
        RepairBill repairBill = new RepairBill();
        RepairSendBill deviceRepairSendBillEntity = new RepairSendBill();
        Integer userId = userUtils.getCurrentUserId();
        BeanUtils.copyProperties(repairBillSaveVo, repairBill);
        BeanUtils.copyProperties(repairBillSaveVo, deviceRepairSendBillEntity);
        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.addEntity(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.setRepairStatus(0);
        deviceRepairSendBillEntity.setSendTime(new Date());
        StringBuffer stringBuffer = new StringBuffer();
        List<RepairDetail> repairDetails = new ArrayList<>();
        if (repairBillSaveVo.getTaskId()!=null) {
            TaskBto parentTask = taskService.get(repairBillSaveVo.getTaskId());
            repairDetails = repairDetailDao.findByDeviceRepairBillId(parentTask.getBillId());
        }
        //存维修详情单
        for (DeviceDetailVo d : repairBillSaveVo.getDeviceList()) {
            RepairDetail 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.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) {
                    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());
                if (d.getRemark() == null) {
                    for (RepairDetail r : repairDetails) {
                        if (r.getDeviceId().equals(d.getDeviceId())) {
                            repairDetail.setRemark(r.getRemark());
                            break;
                        }
                    }
                } else {
                    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("维修业务");
        RepairSendBill repairSendBill = deviceRepairSendBillService.addEntity(deviceRepairSendBillEntity);
        Integer ownUnit;
        TaskBto saveEntity;
        List<Integer> ids = userPublicService.findOtherUser(userUtils.getCurrentUserId());
        if (level == 1) {
            ownUnit = userUtils.getCurrentUnitId();
            TaskBto taskBto = new TaskBto(StatusEnum.WAIT_UPLOAD_FILE.id, "维修业务", null, ".", repairBill1.getId(), 5, ownUnit, 1, "country", userIds);
            saveEntity = taskService.start(taskBto);
        } else {
            ownUnit = userPublicService.findUnitIdByName(repairBill.getReceiveUnit());
            TaskBto taskBto = new TaskBto(StatusEnum.WAIT_RECEIVE.id, "维修业务", null, ".", repairBill1.getId(), 5, ownUnit, 1, null, userIds);
            saveEntity = taskService.start(taskBto);
            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);
        }
        if (repairBillSaveVo.getTaskId()!=null) {
            TaskBto parentTask = taskService.get(repairBillSaveVo.getTaskId());
            saveEntity.setParentTaskId(parentTask.getId());
            saveEntity.setNodeIdDetail(parentTask.getNodeIdDetail() + repairBillSaveVo.getTaskId() + ".");
            taskService.update(saveEntity);
        }
        String deviceIdDetail = deviceRepairSendBillEntity.getRepairDeviceCheckDetail();
        List<Integer> idList = StringSplitUtil.split(deviceIdDetail);
        //如果当前为省，改变装备的所在为中办
        if (level == 1) {
            //获取当前业务维修详情
            List<RepairDetail> repairDetailEntities = deviceRepairDetailService.findByBillId(repairBill.getId());
            if (repairBillSaveVo.getTaskId()!=null) {
                TaskBto parentTask = taskService.get(repairBillSaveVo.getTaskId());
                //获取所有父业务id
                List<Integer> fathers = StringSplitUtil.taskIdSplit(parentTask.getNodeIdDetail()+ repairBillSaveVo.getTaskId() + ".");
                fathers.forEach(integer -> {
                    //筛选出父业务相同装备的维修详情
                    List<RepairDetail> repairDetails2 = repairDetailDao.findByDeviceRepairBillId(taskService.get(integer).getBillId()).stream()
                            .filter(repairDetail -> idList.contains(repairDetail.getDeviceId()))
                            .collect(Collectors.toList());
                    //添加维修详情
                    repairDetailEntities.addAll(repairDetails2);
                });
            }
            //改变维修详情装备所在单位为中办,状态为维修中
            repairDetailEntities.forEach(repairDetail -> {
                repairDetail.setLocationUnit(repairBillSaveVo.getReceiveUnit());
                repairDetail.setRepairStatus(1);
                deviceRepairDetailService.update(repairDetail);
            });
        }
        //添加出库白名单
        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());
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),StatusEnum.WAIT_RECEIVE);
        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());
        if (repairSendBill.getRepairUseraId() == null) {
            repairBill.setRepairUserA(userUtils.getCurrentUserName());
            repairSendBill.setRepairUseraId(userId);
            taskService.addInvolveUser(taskBto, userId);
        }
        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());
        }
        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(userUtils.getCurrentUserUnitName());
                    //存装备日志
                    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(userUtils.getCurrentUserUnitName());
            repairDetail.setRepairStatus(1);
            deviceRepairDetailService.update(repairDetail);
        });
        //发送阅知信息
        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 = "/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);
        //不上传单据
        if (fileUploadVo.getStatus()==0){
            taskService.moveToArchive(taskBto);
        }
        else {
            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());
//                MessageBto messageBto2 = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", Collections.singletonList(fileUploadVo.getRepairUserbId()), 1);
//                messageService.add(messageBto2);
            }
            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 = "/back")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity repairBack(@RequestBody @Validated RepairBackBillSaveVo repairBackBillSaveVo) {
        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 = new RepairBackBill();
        BeanUtils.copyProperties(repairBackBillSaveVo, repairBackBill);
        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.save(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 taskBto1 = new TaskBto(StatusEnum.WAIT_BACK_RECEIVE.id, "维修退回", null,  ".", deviceRepairBackBillEntity1.getId(), BusinessEnum.REPAIR_BACK.id,userPublicService.findUnitIdByName(repairBackBill.getReceiveUnit()), 1, null, userIds);
        TaskBto task = taskService.start(taskBto1);
        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();
        Integer level = userUtils.getCurrentUnitLevel();
        //获取退回单和装备id
        RepairBackBill repairBackBill;
        if (level == 2 || level == 3) {
            taskBto = taskService.get(repairReceiveVo.getTaskId());
            TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),StatusEnum.WAIT_BACK_RECEIVE);
            taskService.addInvolveUser(taskBto,userId);
            repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
            if (repairReceiveVo.getStartUserbId()!=null){
                repairBackBill.setStartUserbId(repairReceiveVo.getStartUserbId());
                repairBackBill.setAgent(userPublicService.getOne(repairReceiveVo.getStartUserbId()).getName());
            }
        } 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());
        }
        String deviceIdDetail = repairReceiveVo.getReceiveCheckDetail();
        if (repairBackBill.getReceiveUseraId() == null) {
            repairBackBill.setReceiveUseraId(userId);
        }
        //更新退回单
        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);
        TaskBto taskBto2;
        Map<Integer,List<Integer>> messageMap = new HashMap<>();
        if (level == 1) {
            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, null, 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());
                repairDetail.setRepairBackBillId(repairBackBill1.getId());
                repairDetail.setRepairStatus(5);
                if (repairDetail.getPid()!=null) {
                    RepairDetail repairDetail1 = deviceRepairDetailService.getOne(repairDetail.getPid());
                    repairDetail1.setRepairStatus(2);
                    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);
                    }
                }
                deviceRepairDetailService.update(repairDetail);
            }
        } else {
            if (repairReceiveVo.getStatus()==0) {
                taskBto2 = taskService.moveToEnd(taskBto);
                //子任务完结
                taskService.moveAllSonNodeToEnd(taskBto.getId());
            }
            else {
                taskBto2 = taskService.moveToSpecial(taskBto,StatusEnum.WAIT_UPLOAD_BACK_FILE);
            }
            //获取维修详情
            List<RepairDetail> repairDetailList = repairDetailDao.findByRepairBackBillId(repairBackBill.getId());
            repairDetailList.forEach(repairDetail -> {
                repairDetail.setRepairStatus(5);
                if (repairDetail.getPid()!=null) {
                    RepairDetail repairDetail1 = deviceRepairDetailService.getOne(repairDetail.getPid());
                    repairDetail1.setRepairStatus(2);
                    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);
                    }
                }
                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);
                    Integer unitId = userPublicService.findUnitIdByName(deviceLibraryEntity.getOwnUnit());
                    deviceLibraryEntity.setLocationUnit(userUtils.getCurrentUserUnitName());
                    if (deviceLibraryEntity.getOwnUnit().equals(deviceLibraryEntity.getLocationUnit())) {
                        deviceLibraryEntity.setLifeStatus(2);
                    }
                    //添加装备日志
                    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 (level>1) {
            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);
        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);
            messageBto2.setRecord(StringSplitUtil.idListToString(messageMap.get(integer)));
            messageService.add(messageBto2);
        });
        myWebSocket.sendMessage1();
        return ResultUtil.success("维修成功退回装备接收入库");
    }

    @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<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());
                        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);
                        }
                    }
                }
            }
        }
        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 = "可以通过这个接口维修换新设备")
    @PostMapping(value = "/change/new")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity changeNewDevice(@RequestBody @Validated ChangeNewDeviceVo changeNewDeviceVo) {
        //获取当前任务
        TaskBto taskBto = taskService.get(changeNewDeviceVo.getTaskId());
        //获取当前单位
        String unit = userUtils.getCurrentUserUnitName();
        //获取所有父任务id
        List<Integer> fathers = StringSplitUtil.taskIdSplit(taskBto.getNodeIdDetail());
        //获取维修详情单
        RepairDetail repairDetail1 = deviceRepairDetailService.getOne(changeNewDeviceVo.getId());
        //获取原装备
        DeviceLibrary originDevice = deviceLibraryService.getOne(repairDetail1.getDeviceId());
        //获取换新装备
        DeviceLibrary deviceLibrary = deviceLibraryService.getOne(changeNewDeviceVo.getDeviceId());
        //判断当前装备是否已报废
        if (repairDetail1.getNewDeviceDetailId() != null && repairDetail1.getNewDeviceDetailId() == 0) {
            //添加新的维修装备详情
            RepairDetail repairDetail = new RepairDetail();
            repairDetail.setModel(deviceLibrary.getModel());
            repairDetail.setName(deviceLibrary.getName());
            repairDetail.setType(deviceLibrary.getType());
            repairDetail.setDeviceRepairBillId(repairDetail1.getDeviceRepairBillId());
            repairDetail.setOwnUnit(repairDetail1.getOwnUnit());
            repairDetail.setLocationUnit(repairDetail1.getLocationUnit());
            if (changeNewDeviceVo.getType() == 0) {
                repairDetail.setRepairStatus(RepairStatusEnum.CHANGE_NEW.id);
            } else {
                repairDetail.setRepairStatus(RepairStatusEnum.CHANGE_NEW_DEVICE.id);
            }
            repairDetail.setDeviceId(changeNewDeviceVo.getDeviceId());
            repairDetail.setNewDeviceDetailId(null);
            repairDetail.setRfidSurfaceId(deviceLibrary.getRfidSurfaceId());
            repairDetail.setSeqNumber(deviceLibrary.getSeqNumber());
            //当前业务和父任务添加该详情
            RepairDetail repairDetail8 = deviceRepairDetailService.save(repairDetail);
            repairDetail1.setNewDeviceDetailId(repairDetail8.getId());
            deviceRepairDetailService.update(repairDetail1);
            fathers.forEach(integer -> {
                RepairBill repairBill = deviceRepairBillService.getOne(taskService.get(integer).getBillId());
                RepairDetail repairDetail2 = new RepairDetail();
                BeanUtils.copyProperties(repairDetail, repairDetail2);
                repairDetail2.setId(null);
                repairDetail2.setDeviceRepairBillId(repairBill.getId());
                deviceRepairDetailService.save(repairDetail2);
            });
            //改变装备的所属
            deviceLibrary.setOwnUnit(repairDetail.getOwnUnit());
            deviceLibraryService.update(deviceLibrary);
            //如果是新装备换新，添加换新记录
            if (changeNewDeviceVo.getType() == 1) {
                DeviceChange deviceChange = new DeviceChange();
                deviceChange.setNewDeviceId(deviceLibrary.getId());
                deviceChange.setOldDeviceId(originDevice.getId());
                deviceChangeService.add(deviceChange);
            }
            //添加业务日志
            String remark = "添加维修换新装备" + deviceLibrary.getName();
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(), remark, null);
            taskLogService.addLog(taskLogBto);
            //添加装备日志
            DeviceLogDto deviceLogDto = new DeviceLogDto(originDevice.getId(), remark, null);
            deviceLogService.addLog(deviceLogDto);
        }
        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());
                repairSendBill.setSendFileList(FilesUtil.stringFileToList(repairSendBill.getSendFiles()));
                repairSendBill.setReceiveFileList(FilesUtil.stringFileToList(repairSendBill.getReceiveFiles()));
                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);
                        }
                    }
                    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());
                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 -> {
                    DeviceLibrary deviceLibrary = deviceLibraryMap.get(repairDetail.getDeviceId());
                    repairDetail.setLocationUnit(deviceLibrary.getLocationUnit());
                    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) {
        Map<Integer,DeviceLibrary> deviceLibraryMap = deviceLibraryService.getAllDeviceMap();
        Integer type = repairTaskSelectVo.getType();
        Integer userId = userUtils.getCurrentUserId();
        String unitName = userUtils.getCurrentUserUnitName();
        //待维修装备
        if (type==1){
            List<Integer> integerList = new ArrayList<>();
            integerList.add(1);
            integerList.add(9);
            List<RepairDetail> repairDetails = repairDetailDao.findAllByRepairStatusIn(integerList,repairTaskSelectVo.getPageable().getSort());
            repairDetails.forEach(repairDetail -> {
                repairDetail.setLocationUnit(deviceLibraryMap.get(repairDetail.getDeviceId()).getLocationUnit());
                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);
            List<RepairDetail> repairDetails1 = repairDetailDao.findAllByRepairStatusNotIn(integerList,repairTaskSelectVo.getPageable().getSort());
            repairDetails1.forEach(repairDetail -> {
                repairDetail.setLocationUnit(deviceLibraryMap.get(repairDetail.getDeviceId()).getLocationUnit());
                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){
            List<RepairDetail> repairDetails = repairDetailDao.findAllByRepairStatus(2,repairTaskSelectVo.getPageable().getSort());
            repairDetails.forEach(repairDetail -> {
                repairDetail.setLocationUnit(deviceLibraryMap.get(repairDetail.getDeviceId()).getLocationUnit());
                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){
//            List<RepairDetail> repairDetails = repairDetailDao.findAllByRepairStatus(2,repairTaskSelectVo.getPageable().getSort());
//            repairDetails.forEach(repairDetail -> {
//                repairDetail.setLocationUnit(deviceLibraryMap.get(repairDetail.getDeviceId()).getLocationUnit());
//                repairDetail.setConfigName();
//            });
//            return ResponseEntity.ok(repairDetails.stream().filter(repairDetail -> repairDetail.getLocationUnit().equals(unitName)).collect(Collectors.toList()));
//        }
        else {
            throw new ApiException("type只能为1，2，3");
        }
    }

    @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);
//            if (repairDetail.getPid()==null){
                repairDetail.setLocationUnit(deviceLibraryService.getOne(repairDetail.getDeviceId()).getLocationUnit());
                repairDetails.add(repairDetail);
//            }
//            else {
//                RepairDetail repairDetail2 = deviceRepairDetailService.getOne(repairDetail.getPid());
//                repairDetail2.setLocationUnit(deviceLibraryService.getOne(repairDetail2.getDeviceId()).getLocationUnit());
//                repairDetails.add(repairDetail2);
//            }
        });
        return ResponseEntity.ok(repairDetails);
    }

    @ApiOperation(value = "维修换新", notes = "可以通过这个接口维修换新")
    @PostMapping(value = "/changeNew")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity change(@RequestBody DeviceEditVo deviceEditVo){
        DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(deviceEditVo.getDeviceId());
        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);
                deviceLibraryEntity.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);
                    deviceLibraryEntity.setSeqNumber(libraryUpdateVo.getSeqNumber());
                    //改变维修详情的序列号
                    repairDetailDao.findAllByDeviceId(deviceEditVo.getDeviceId()).forEach(repairDetail -> {
                        repairDetail.setSeqNumber(libraryUpdateVo.getSeqNumber());
                        deviceRepairDetailService.update(repairDetail);
                    });
                }
            }
        }
        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);
        //不上传单据
        if (fileVo.getStatus()==0){
            taskService.moveToArchive(taskBto);
        }
        else {
            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);
            }
            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);
            });
            if (idList.size()>0) {
                MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", idList, 1);
                messageService.add(messageBto);
            }
        }
        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);
        //不上传单据
        if (fileVo.getStatus()==0){
            taskService.moveToArchive(taskBto);
        }
        else {
            RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
            RepairSendBill repairSendBill = deviceRepairSendBillDao.findByDeviceRepairBillId(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());
            }
            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 -> {
                DeviceLogDto deviceLogDto = new DeviceLogDto(integer, "上传维修单", fileVoList);
                deviceLogService.addLog(deviceLogDto);
            });
            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);
        List<RepairDetail> orderList = new ArrayList<>();
        repairDetails.forEach(repairDetail -> {
            if (!repairDetail.getRepairStatus().equals(RepairStatusEnum.CHANGE_NEW.id) && !repairDetail.getRepairStatus().equals(RepairStatusEnum.CHANGE_NEW_DEVICE.id)) {
                orderList.add(repairDetail);
                if (repairDetail.getRepairStatus().equals(RepairStatusEnum.SCRAPPED.id)) {
                    if (repairDetail.getNewDeviceDetailId() > 0) {
                        orderList.add(deviceRepairDetailService.getOne(repairDetail.getNewDeviceDetailId()));
                    }
                }
            }
        });
        return orderList;
    }

    @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));
    }
}
