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

import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.library.service.DeviceLibraryService;
import com.tykj.dev.device.library.service.DeviceLogService;
import com.tykj.dev.device.library.subject.Dto.DeviceLogDto;
import com.tykj.dev.device.library.subject.domin.DeviceLibrary;
import com.tykj.dev.device.library.subject.vo.FileVo;
import com.tykj.dev.device.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.task.subject.common.BusinessEnum;
import com.tykj.dev.device.task.subject.common.GlobalMap;
import com.tykj.dev.device.task.subject.common.RepairStatusEnum;
import com.tykj.dev.device.task.subject.common.StatusEnum;
import com.tykj.dev.device.task.subject.domin.Task;
import com.tykj.dev.device.user.subject.service.UserPublicService;
import com.tykj.dev.device.user.util.UserUtils;
import com.tykj.dev.misc.utils.ResultUtil;
import com.tykj.dev.misc.utils.StringSplitUtil;
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.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;

    @ApiOperation(value = "发起维修", notes = "可以通过这个接口发起维修")
    @PostMapping(value = "/form")
    public ResponseEntity createRepair(@RequestBody RepairBillSaveVo repairBillSaveVo) {
        //添加维修单和送修单
        RepairBill repairBill = new RepairBill();
        RepairSendBill deviceRepairSendBillEntity = new RepairSendBill();
        Integer userId = userUtils.getCurrentUserId();
        BeanUtils.copyProperties(repairBillSaveVo, repairBill);
        BeanUtils.copyProperties(repairBillSaveVo, deviceRepairSendBillEntity);
        repairBill.setRepairStatus(0);
        if (repairBillSaveVo.getRepairUseraId() != null) {
            repairBill.setRepairUserA(userPublicService.getOne(repairBillSaveVo.getRepairUseraId()).getName());
        }
        repairBill.setStartUserA(userPublicService.getOne(repairBillSaveVo.getStartUseraId()).getName());
        repairBill.setStartUserB(userPublicService.getOne(repairBillSaveVo.getStartUserbId()).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);
        //发起维修业务
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        userIds.add(repairBillSaveVo.getStartUserbId());
        TaskBto taskBto = new TaskBto(StatusEnum.REPAIR_SEND_CONFIRM.id,"维修业务",null,".",repairBill1.getId(),5,userUtils.getCurrentUnitId(),1,null,userIds);
        Task saveEntity = taskService.start(taskBto);
        //存业务日志
        List<FileVo> fileVoList = new ArrayList<>();
        fileVoList.add(new FileVo("出库确认单",repairBillSaveVo.getFileName(),repairBillSaveVo.getFileUrl()));
        TaskLogBto taskLogBto = new TaskLogBto(saveEntity.getId(),"向"+repairBillSaveVo.getReceiveUnit()+"发起装备维修",fileVoList);
        taskLogService.addLog(taskLogBto);
        deviceRepairSendBillEntity.setRepairStatus(0);
        deviceRepairSendBillEntity.setSendTime(new Date());
        StringBuffer stringBuffer = new StringBuffer();
        //存维修详情单
        for (DeviceDetailVo d:repairBillSaveVo.getDeviceList()) {
            stringBuffer.append(d.getDeviceId());
            stringBuffer.append("Ǵ");
            stringBuffer.append(d.getRemark());
            stringBuffer.append("Ǵ");
            RepairDetail repairDetail = new RepairDetail();
            repairDetail.setDeviceId(d.getDeviceId());
            DeviceLibrary deviceLibraryEntity =deviceLibraryService.getOne(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);
            //存装备日志
            DeviceLogDto deviceLogDto = new DeviceLogDto(d.getDeviceId(),"向"+repairBillSaveVo.getReceiveUnit()+"发起装备维修",fileVoList);
            deviceLogService.addLog(deviceLogDto);
        }
        //存送修单
        deviceRepairSendBillEntity.setRepairDeviceDetail(stringBuffer.toString());
        deviceRepairSendBillEntity.setDeviceRepairBillId(repairBill1.getId());
        deviceRepairSendBillEntity.setAgent(repairBillSaveVo.getAgent());
        deviceRepairSendBillEntity.setTitle("维修业务");
        deviceRepairSendBillService.addEntity(deviceRepairSendBillEntity);
        myWebSocket.sendMessage1();
        return ResultUtil.success(saveEntity);
    }

    @ApiOperation(value = "继续向上发起维修", notes = "可以通过这个接口继续向上发起维修")
    @PostMapping(value = "/continue/form")
    public ResponseEntity continueCreateRepair(@RequestBody RepairBillSaveVo deviceRepairBillSaveVo) {
        ResponseEntity responseEntity = createRepair(deviceRepairBillSaveVo);
        TaskBto taskBto = Objects.requireNonNull((Task) responseEntity.getBody()).parse2Bto();
        TaskBto parentTask = taskService.get(deviceRepairBillSaveVo.getTaskId());
        taskBto.setParentTaskId(parentTask.getId());
        taskBto.setNodeIdDetail(parentTask.getNodeIdDetail() + deviceRepairBillSaveVo.getTaskId() + ".");
        taskService.update(taskBto);
        return ResultUtil.success("继续向上级发起维修成功");
    }

    @ApiOperation(value = "发起维修审核", notes = "可以通过这个接口发起维修审核")
    @PostMapping(value = "/sendConfirm")
    public ResponseEntity sendConfirm(@RequestBody RepairConfirmVo deviceRepairConfirmVo) {
        Integer level = userUtils.getCurrentUnitLevel();
        TaskBto taskBto = taskService.get(deviceRepairConfirmVo.getTaskId());
        //获取维修单，送修单，装备详情
        RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
        RepairSendBill repairSendBill = deviceRepairSendBillDao.findByDeviceRepairBillId(repairBill.getId());
        String deviceIdDetail = repairSendBill.getRepairDeviceCheckDetail();
        List<Integer> idList = StringSplitUtil.split(deviceIdDetail);
        //审核成功
        if (deviceRepairConfirmVo.getStatus() == 0) {
            if (userUtils.getCurrentUnitLevel()!=1) {
                taskBto.setOwnUnit(userPublicService.findUnitIdByName(repairBill.getReceiveUnit()));
            }
            //任务推至下一阶段
            if (level==1) {
                if (repairSendBill.getRepairUseraId() != null) {
                    //指定用户
                    taskService.update(taskService.moveToNext(taskBto, repairSendBill.getRepairUseraId()));
                } else {
                    //不指定用户
                    taskService.update(taskService.moveToNext(taskBto));
                }
            }
            //省送国家，任务之间推至维修状态,发起人a的待办
            else{
                taskService.update(taskService.moveToSpecial(taskBto,StatusEnum.REPAIRING,repairSendBill.getStartUseraId()));
            }
            //存业务日志
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"审核成功并出库",null);
            taskLogService.addLog(taskLogBto);
            //如果当前为省，改变装备的所在为中办
            if (level==1){
                //获取当前业务维修详情
                List<RepairDetail> repairDetailEntities = deviceRepairDetailService.findByBillId(repairBill.getId());
                //获取所有父业务id
                List<Integer> fathers = StringSplitUtil.taskIdSplit(taskBto.getNodeIdDetail());
                fathers.forEach(integer -> {
                    //筛选出父业务相同装备的维修详情
                    List<RepairDetail> repairDetails = repairDetailDao.findByDeviceRepairBillId(taskService.get(integer).getBillId()).stream()
                            .filter(repairDetail -> idList.contains(repairDetail.getDeviceId()))
                            .collect(Collectors.toList());
                    //添加维修详情
                    repairDetailEntities.addAll(repairDetails);
                });
                //改变维修详情装备所在单位为中办
                repairDetailEntities.forEach(repairDetail -> {
                    repairDetail.setLocationUnit("中办");
                    deviceRepairDetailService.update(repairDetail);
                });
            }
            //更新维修单和送修单状态
            //如果当前为省像国家发起的
            if (level==1){
                repairBill.setRepairStatus(4);
                repairSendBill.setRepairStatus(5);
            }
            else {
                repairBill.setRepairStatus(2);
                repairSendBill.setRepairStatus(2);
            }
            deviceRepairBillService.update(repairBill);
            deviceRepairSendBillService.update(repairSendBill);
            //修改装备状态，存装备日志
            if (idList.size()>0) {
                for (Integer id:idList) {
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    //如果当前为省像国家发起的
                    if (level==1){
                        deviceLibraryEntity.setLifeStatus(4);
                    }
                    else {
                        deviceLibraryEntity.setLifeStatus(3);
                    }
                    deviceLibraryEntity.setManageStatus(0);
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"审核成功并出库",null);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
            myWebSocket.sendMessage1();
            return ResultUtil.success("维修出库审核通过");
        }
        //审核失败
        if (deviceRepairConfirmVo.getStatus()==1) {
            //业务封存
            taskService.update(taskService.moveToArchive(taskBto));
            //更新维修单和送修单状态
            repairBill.setRepairStatus(1);
            repairSendBill.setRepairStatus(1);
            deviceRepairBillService.update(repairBill);
            deviceRepairSendBillService.update(repairSendBill);
            //存装备日志
            if (idList.size() > 0) {
                for (Integer id : idList) {
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"维修出库审核失败",null);
                    deviceLogService.addLog(deviceLogDto);
                }
            }
            myWebSocket.sendMessage1();
            return ResultUtil.success("维修出库审核失败");
        }
        else {
            return ResultUtil.failed("status只能为0或1");
        }
    }

    @ApiOperation(value = "接收维修装备", notes = "可以通过这个接口接收维修装备")
    @PostMapping(value = "/receive")
    public ResponseEntity receiveDevice(@RequestBody RepairReceiveVo repairReceiveVo) {
        //获取当前任务
        TaskBto taskBto = taskService.get(repairReceiveVo.getTaskId());
        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);
        }
        //任务推至下一阶段
        taskService.update(taskService.moveToNext(taskBto,repairReceiveVo.getReceiveUserbId()));
        //存业务日志
        List<FileVo> fileVoList = new ArrayList<>();
        fileVoList.add(new FileVo("维修单",repairSendBill.getBillFileName(),repairSendBill.getBillFileUrl()));
        fileVoList.add(new FileVo("入库确认单",repairSendBill.getReceiveFileName(),repairSendBill.getReceiveFileUrl()));
        TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"接收并发起入库",fileVoList);
        taskLogService.addLog(taskLogBto);
        //更新维修单和送修单
        repairBill.setRepairStatus(6);
        repairBill.setRepairUserB(userPublicService.getOne(repairReceiveVo.getReceiveUserbId()).getName());
        deviceRepairBillService.update(repairBill);
        repairSendBill.setRepairStatus(6);
        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());
        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(0);
                    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);
                }
            }
        }
        //获取所有父业务id
        List<Integer> fathers = StringSplitUtil.taskIdSplit(taskBto.getNodeIdDetail());
        fathers.forEach(integer -> {
            //筛选出父业务相同装备的维修详情
            List<RepairDetail> repairDetails = repairDetailDao.findByDeviceRepairBillId(taskService.get(integer).getBillId()).stream()
                    .filter(repairDetail -> idList.contains(repairDetail.getDeviceId()))
                    .collect(Collectors.toList());
            //添加维修详情
            repairDetailEntities.addAll(repairDetails);
        });
        //改变维修详情装备所在单位为当前单位
        repairDetailEntities.forEach(repairDetail -> {
            repairDetail.setLocationUnit(userUtils.getCurrentUserUnitName());
            deviceRepairDetailService.update(repairDetail);
        });
        myWebSocket.sendMessage1();
        return ResultUtil.success("维修装备接收入库");
    }

    @ApiOperation(value = "接收维修装备审核", notes = "可以通过这个接口对接收维修装备审核")
    @PostMapping(value = "/receiveConfirm")
    public ResponseEntity receiveConfirm(@RequestBody RepairConfirmVo repairConfirmVo) {
        //获取任务
        TaskBto taskBto = taskService.get(repairConfirmVo.getTaskId());
        //获取维修单，送修单，装备详情，维修详情单
        RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
        RepairSendBill repairSendBill = deviceRepairSendBillDao.findByDeviceRepairBillId(repairBill.getId());
        String deviceIdDetail = repairSendBill.getRepairReciveCheckDetail();
        String[] strings = deviceIdDetail.split("x");
        List<RepairDetail> repairDetailEntities = deviceRepairDetailService.findByBillId(repairBill.getId());
        //审核通过
        if (repairConfirmVo.getStatus() == 0) {
            //任务推至下一阶段
            taskService.update(taskService.moveToNext(taskBto,repairSendBill.getRepairUseraId()));
            //添加业务日志
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"审核成功并入库维修",null);
            taskLogService.addLog(taskLogBto);
            //修改维修单，送修单状态
            repairBill.setRepairStatus(4);
            repairSendBill.setRepairStatus(5);
            deviceRepairBillService.update(repairBill);
            deviceRepairSendBillService.update(repairSendBill);
            for (String s:strings) {
                //接收无误的装备
                if (s.length()>=2&& "1".equals(s.substring(s.length()-1))) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    //更新装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(4);
                    //添加装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"审核成功并入库维修",null);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
            //更改维修详情单装备的状态
            repairDetailEntities.forEach(deviceRepairDetailEntity -> {
                deviceRepairDetailEntity.setRepairStatus(1);
                deviceRepairDetailService.update(deviceRepairDetailEntity);
            });
            myWebSocket.sendMessage1();
            return ResultUtil.success("入库审核通过配发接收成功");
        }
        //审核失败
        if (repairConfirmVo.getStatus()==1){
            //业务封存
            taskService.update(taskService.moveToArchive(taskBto));
            //添加业务日志
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"维修装备入库审核失败",null);
            taskLogService.addLog(taskLogBto);
            //修改维修单，送修单状态
            repairBill.setRepairStatus(3);
            repairSendBill.setRepairStatus(4);
            deviceRepairBillService.update(repairBill);
            deviceRepairSendBillService.update(repairSendBill);
            for (String s:strings) {
                //接收无误的装备
                if (s.length()>=2&& "1".equals(s.substring(s.length()-1))) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    //更新装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(1);
                    //添加装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"维修装备入库审核失败",null);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
            myWebSocket.sendMessage1();
            return ResultUtil.success("维修装备接收入库审核失败");
        }
        else {
            return ResultUtil.failed("status只能为0或1");
        }
    }

    @ApiOperation(value = "修好装备出库查询", notes = "可以通过这个接口修好装备出库查询")
    @GetMapping(value = "/backDeviceSelect/{id}")
    public ResponseEntity backDeviceSelect(@PathVariable("id") int id) {
        RepairOutPutDeviceVo repairOutPutDeviceVo = new RepairOutPutDeviceVo();
        //获取业务和账单
        TaskBto taskBto = taskService.get(id);
        RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
        repairOutPutDeviceVo.setRepairBill(repairBill);
        List<DeviceLibrary> deviceLibraryEntities = new ArrayList<>();
        //筛选所有修好装备或换新装备的id
        List<Integer> idList = deviceRepairDetailService.findByBillId(taskBto.getBillId()).stream()
                .filter(deviceRepairDetailEntity -> deviceRepairDetailEntity.getRepairStatus().equals(2) || deviceRepairDetailEntity.getRepairStatus().equals(3))
                .map(RepairDetail::getDeviceId)
                .collect(Collectors.toList());
        //根据id添加装备
        idList.forEach(integer -> deviceLibraryEntities.add(deviceLibraryService.getOne(integer)));
        repairOutPutDeviceVo.setDeviceLibraries(deviceLibraryEntities);
        return ResultUtil.success(repairOutPutDeviceVo);
    }

    @ApiOperation(value = "往上维修出库装备查询", notes = "可以通过这个接口往上维修出库装备查询")
    @GetMapping(value = "/sendDeviceSelect/{id}")
    public ResponseEntity sendDeviceSelect(@PathVariable("id") int id) {
        RepairOutPutDeviceVo repairOutPutDeviceVo = new RepairOutPutDeviceVo();
        //获取业务和账单
        TaskBto taskBto = taskService.get(id);
        RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
        repairOutPutDeviceVo.setRepairBill(repairBill);
        List<DeviceLibrary> deviceLibraryEntities = new ArrayList<>();
        //筛选所有还没修好装备的id
        List<Integer> idList = deviceRepairDetailService.findByBillId(taskBto.getBillId()).stream()
                .filter(deviceRepairDetailEntity -> deviceRepairDetailEntity.getRepairStatus().equals(1))
                .map(RepairDetail::getDeviceId)
                .collect(Collectors.toList());
        //根据id添加装备
        idList.forEach(integer -> deviceLibraryEntities.add(deviceLibraryService.getOne(integer)));
        repairOutPutDeviceVo.setDeviceLibraries(deviceLibraryEntities);
        return ResultUtil.success(repairOutPutDeviceVo);
    }

//    @ApiOperation(value = "送国家维修装备出库",notes = "可以通过这个接口送国家维修装备出库")
//    @PostMapping(value = "/sendCountry")
//    public ResponseEntity sendCountry(@RequestBody RepairBillSaveVo repairBillSaveVo){
//        //获取父任务
//        TaskBto fatherTask = taskService.get(repairBillSaveVo.getTaskId());
//        //添加维修单,送修单
//        RepairBill repairbill= new RepairBill();
//        RepairSendBill repairSendBill = new RepairSendBill();
//        Integer userId = userUtils.getCurrentUserId();
//        BeanUtils.copyProperties(repairBillSaveVo,repairbill);
//        BeanUtils.copyProperties(repairBillSaveVo,repairSendBill);
//        repairbill.setRepairStatus(0);
//        if (repairBillSaveVo.getRepairUserA()!=null) {
//            repairbill.setRepairUserA(repairBillSaveVo.getRepairUserA());
//        }
//        repairbill.setStartUserA(userPublicService.getOne(repairBillSaveVo.getStartUseraId()).getName());
//        repairbill.setStartUserB(userPublicService.getOne(repairBillSaveVo.getStartUserbId()).getName());
//        RepairBill repairBill1 = deviceRepairBillService.addEntity(repairbill);
//        Calendar calendar = Calendar.getInstance();
//        String s1 ="NO:第"+calendar.get(Calendar.YEAR)+"PF"+repairBill1.getId()+"号";
//        repairBill1.setDocNum(s1);
//        deviceRepairBillService.update(repairBill1);
//        //发起维修业务
//        List<Integer> userIds = new ArrayList<>();
//        userIds.add(userId);
//        userIds.add(repairBillSaveVo.getStartUserbId());
//        TaskBto taskBto = new TaskBto(StatusEnum.REPAIR_SEND_CONFIRM.id,"维修业务",repairBillSaveVo.getTaskId(),fatherTask.getNodeIdDetail()+fatherTask.getId()+".",repairBill1.getId(),5,userUtils.getCurrentUnitId(),1,null,userIds);
//        Task saveEntity = taskService.start(taskBto);
//        //存业务日志
//        List<FileVo> fileVoList = new ArrayList<>();
//        fileVoList.add(new FileVo("出库确认单",repairBillSaveVo.getFileName(),repairBillSaveVo.getFileUrl()));
//        TaskLogBto taskLogBto = new TaskLogBto(saveEntity.getId(),"向"+repairBillSaveVo.getReceiveUnit()+"发起装备维修",fileVoList);
//        taskLogService.addLog(taskLogBto);
//        repairSendBill.setRepairStatus(0);
//        repairSendBill.setSendTime(new Date());
//        StringBuffer stringBuffer = new StringBuffer();
//        //存维修详情单
//        for (DeviceDetailVo d:repairBillSaveVo.getDeviceList()) {
//            stringBuffer.append(d.getDeviceId());
//            stringBuffer.append("Ǵ");
//            stringBuffer.append(d.getRemark());
//            stringBuffer.append("Ǵ");
//            RepairDetail repairDetail = new RepairDetail();
//            repairDetail.setDeviceId(d.getDeviceId());
//            DeviceLibrary deviceLibraryEntity =deviceLibraryService.getOne(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);
//            //存装备日志
//            DeviceLogDto deviceLogDto = new DeviceLogDto(d.getDeviceId(),"向"+repairBillSaveVo.getReceiveUnit()+"发起装备维修",fileVoList);
//            deviceLogService.addLog(deviceLogDto);
//        }
//        //存送修单
//        repairSendBill.setRepairDeviceDetail(stringBuffer.toString());
//        repairSendBill.setDeviceRepairBillId(repairBill1.getId());
//        repairSendBill.setAgent(repairBillSaveVo.getAgent());
//        repairSendBill.setTitle("维修业务");
//        deviceRepairSendBillService.addEntity(repairSendBill);
//        myWebSocket.sendMessage1();
//        return ResponseEntity.ok(saveEntity);
//    }

    @ApiOperation(value = "送国家维修装备出库审核", notes = "可以通过这个接口送国家维修装备出库审核")
    @PostMapping(value = "/sendCountry/confirm")
    public ResponseEntity sendCountryConfirm(@RequestBody RepairConfirmVo deviceRepairConfirmVo) {
        return null;
    }

    @ApiOperation(value = "送国家维修装备入库接收", notes = "可以通过这个接口送国家维修装备入库接收")
    @PostMapping(value = "/sendCountry/receive")
    public ResponseEntity sendCountryReceive() {
        return null;
    }

    @ApiOperation(value = "送国家维修装备入库审核", notes = "可以通过这个接口送国家维修装备入库审核")
    @PostMapping(value = "/sendCountry/receive/confirm")
    public ResponseEntity sendCountryReceiveConfirm(@RequestBody RepairConfirmVo deviceRepairConfirmVo) {
        return null;
    }

    @ApiOperation(value = "修好装备出库", notes = "可以通过这个接口修好装备出库")
    @PostMapping(value = "/back")
    public ResponseEntity repairBack(@RequestBody RepairBackBillSaveVo repairBackBillSaveVo) {
        //获取当前维修业务，维修单
        TaskBto taskBto = taskService.get(repairBackBillSaveVo.getTaskId());
        Integer userId = userUtils.getCurrentUserId();
        RepairBill repairBill = deviceRepairBillService.getOne(taskBto.getBillId());
        //生成维修退回单
        RepairBackBill repairBackBill = new RepairBackBill();
        BeanUtils.copyProperties(repairBackBillSaveVo, repairBackBill);
        repairBackBill.setBackStatus(0);
        repairBackBill.setDeviceRepairBillId(repairBill.getId());
        repairBackBill.setSendTime(new Date());
        repairBackBill.setTitle("维修退回业务");
        repairBackBill.setAgent(repairBackBillSaveVo.getAgent());
        Calendar calendar = Calendar.getInstance();
        String s1 ="NO:第"+calendar.get(Calendar.YEAR)+"HZ"+repairBackBill.getId()+"号";
        repairBackBill.setDocNum(s1);
        RepairBackBill deviceRepairBackBillEntity1 = deviceRepairBackBillService.save(repairBackBill);
        //发起维修退回子业务
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        userIds.add(repairBackBillSaveVo.getStartUserbId());
        TaskBto taskBto1 = new TaskBto(StatusEnum.REPAIR_BACK_CONFIRM.id, "维修退回", taskBto.getId(), taskBto.getNodeIdDetail()+taskBto.getId()+".", deviceRepairBackBillEntity1.getId(), BusinessEnum.REPAIR_BACK.id, userUtils.getCurrentUnitId(), 1, null, userIds);
        Task task = taskService.start(taskBto1);
        //添加业务日志
        List<FileVo> fileVoList = new ArrayList<>();
        fileVoList.add(new FileVo("出库确认单",repairBackBillSaveVo.getFileName(),repairBackBillSaveVo.getFileUrl()));
        TaskLogBto taskLogBto = new TaskLogBto(task.getId(),"向" + repairBackBillSaveVo.getReceiveUnit() + "发起配发",fileVoList);
        taskLogService.addLog(taskLogBto);
        //添加装备日志
        for (DeviceDetailVo d:repairBackBillSaveVo.getDeviceList()) {
            DeviceLogDto deviceLogDto = new DeviceLogDto(d.getDeviceId(),"向" + repairBackBillSaveVo.getReceiveUnit() + "退还维修装备",fileVoList);
            deviceLogService.addLog(deviceLogDto);
        }
        //判断是否修完
        List<RepairDetail> deviceRepairDetailEntities = deviceRepairDetailService.findByBillId(repairBill.getId());
        //获取所有装备的维修状态
        Set<Integer> statusSet = deviceRepairDetailEntities.stream()
                .map(RepairDetail::getRepairStatus)
                .collect(Collectors.toSet());
        //存放所有维修完成的状态
        Set<Integer> integerSet = new HashSet<>();
        integerSet.add(3);
        integerSet.add(4);
        integerSet.add(5);
        //取交集
        integerSet.retainAll(statusSet);
        //如果取交集后size不变，则说明全部都是维修完成的状态
        if (integerSet.size()==statusSet.size()){
            //维修主业务完结
            taskService.update(taskService.moveToEnd(taskBto));
        }
        myWebSocket.sendMessage1();
        return ResultUtil.success("出库成功待审核");
    }

    @ApiOperation(value = "修好装备出库审核", notes = "可以通过这个接口修好装备出库审核")
    @PostMapping(value = "/back/confirm")
    public ResponseEntity backConfirm(@RequestBody RepairConfirmVo repairConfirmVo) {
        //获取业务，账单，相关装备Id
        TaskBto taskBto = taskService.get(repairConfirmVo.getTaskId());
        RepairBackBill repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
        String deviceIdDetail = repairBackBill.getBackCheckDetail();
        List<Integer> idList = StringSplitUtil.split(deviceIdDetail);
        //审核成功
        if (repairConfirmVo.getStatus() == 0) {
            //改变账单状态
            repairBackBill.setBackStatus(2);
            deviceRepairBackBillService.update(repairBackBill);
            if (idList.size()>0) {
                for (Integer id:idList) {
                    //改变装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(3);
                    deviceLibraryEntity.setManageStatus(0);
                    //添加装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"维修退回审核成功并出库",null);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
            //设置任务的所属单位
            taskBto.setOwnUnit(userPublicService.findUnitIdByName(repairBackBill.getReceiveUnit()));
            //不指定接收人
            if (repairBackBill.getReceiveUseraId()!=null) {
                //业务推至下一阶段
                taskService.update(taskService.moveToNext(taskBto,repairBackBill.getReceiveUseraId()));
            }
            else {
                taskService.update(taskService.moveToNext(taskBto));
            }
            //添加业务日志
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"维修退回审核成功并出库",null);
            taskLogService.addLog(taskLogBto);
            myWebSocket.sendMessage1();
            return ResultUtil.success("维修退回出库审核通过");
        }
        //审核失败
        if (repairConfirmVo.getStatus()==1) {
            //业务封存
            taskService.update(taskService.moveToArchive(taskBto));
            //添加业务日志
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"维修退回出库审核失败",null);
            taskLogService.addLog(taskLogBto);
            //更新退回单状态
            repairBackBill.setBackStatus(1);
            deviceRepairBackBillService.update(repairBackBill);
            if (idList.size() > 0) {
                for (Integer id : idList) {
                    //添加装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"维修退回出库审核失败",null);
                    deviceLogService.addLog(deviceLogDto);
                }
            }
            myWebSocket.sendMessage1();
            return ResultUtil.success("维修退回出库审核失败");
        }
        else {
            return ResultUtil.failed("status只能为0或1");
        }
    }

    @ApiOperation(value = "修好装备送回接收入库", notes = "可以通过这个接口修好装备送回接收")
    @PostMapping(value = "/back/receive")
    public ResponseEntity backReceive(@RequestBody RepairReceiveVo repairReceiveVo) {
        //获取当前任务
        TaskBto taskBto = taskService.get(repairReceiveVo.getTaskId());
        Integer userId = userUtils.getCurrentUserId();
        //获取退回单和装备id
        RepairBackBill repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
        String deviceIdDetail = repairReceiveVo.getReceiveCheckDetail();
        if (repairBackBill.getReceiveUseraId() == null) {
            repairBackBill.setReceiveUseraId(userId);
            taskService.addInvolveUser(taskBto, userId);
        }
        //任务推至下一阶段
        taskService.update(taskService.moveToNext(taskBto,repairReceiveVo.getReceiveUserbId()));
        //添加业务日志
        List<FileVo> fileVoList = new ArrayList<>();
        fileVoList.add(new FileVo("维修单",repairBackBill.getBillFileName(),repairBackBill.getBillFileUrl()));
        fileVoList.add(new FileVo("入库确认单",repairBackBill.getReceiveFileName(),repairBackBill.getReceiveFileUrl()));
        TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"维修退回装备接收并发起入库",fileVoList);
        taskLogService.addLog(taskLogBto);
        //更新退回单
        repairBackBill.setBackStatus(3);
        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());
        deviceRepairBackBillService.update(repairBackBill);
        String[] strings = deviceIdDetail.split("x");
        //存放正常接收的装备id
        List<Integer> idList = new ArrayList<>();
        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));
                    idList.add(id);
                    //更改装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(0);
                    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);
                }
            }
        }
        //获取维修详情
        List<RepairDetail> repairDetailList = deviceRepairDetailService.findByBillId(taskBto.getBillId());
        //获取所有父业务id
        List<Integer> fathers = StringSplitUtil.taskIdSplit(taskBto.getNodeIdDetail());
        fathers.forEach(integer -> {
            //筛选出父业务相同装备的维修详情
            List<RepairDetail> repairDetails = repairDetailDao.findByDeviceRepairBillId(taskService.get(integer).getBillId()).stream()
                    .filter(repairDetail -> idList.contains(repairDetail.getDeviceId()))
                    .collect(Collectors.toList());
            //添加维修详情
            repairDetailList.addAll(repairDetails);
        });
        //改变维修详情装备所在单位为当前单位
        repairDetailList.forEach(repairDetail -> {
            repairDetail.setLocationUnit(userUtils.getCurrentUserUnitName());
            deviceRepairDetailService.update(repairDetail);
        });
        myWebSocket.sendMessage1();
        return ResultUtil.success("维修成功退回装备接收入库");
    }

    @ApiOperation(value = "修好装备送回接收入库审核", notes = "可以通过这个接口修好装备送回接收")
    @PostMapping(value = "/back/receive/confirm")
    public ResponseEntity backReceiveConfirm(@RequestBody RepairConfirmVo repairConfirmVo) {
        //获取业务，退回单，装备id
        TaskBto taskBto = taskService.get(repairConfirmVo.getTaskId());
        RepairBackBill repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
        String deviceIdDetail = repairBackBill.getBackReciveCheckDetail();
        String[] strings = deviceIdDetail.split("x");
        //审核通过
        if (repairConfirmVo.getStatus() == 0) {
            //业务完结
            taskService.update(taskService.moveToEnd(taskBto));
            //存业务日志
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"维修退回装备入库审核成功",null);
            taskLogService.addLog(taskLogBto);
            //更新退回单状态
            repairBackBill.setBackStatus(5);
            deviceRepairBackBillService.update(repairBackBill);
            for (String s:strings) {
                //接收无误的装备
                if (s.length()>=2&& "1".equals(s.substring(s.length()-1))) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    //更新装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(2);
                    //添加装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"维修退回装备入库审核成功",null);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
            myWebSocket.sendMessage1();
            return ResultUtil.success("维修成功退回装备入库审核成功");
        }
        //审核失败
        if (repairConfirmVo.getStatus()==1){
            //业务封存
            taskService.update(taskService.moveToArchive(taskBto));
            //存业务日志
            TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),"维修退回装备入库审核失败",null);
            taskLogService.addLog(taskLogBto);
            //更新退回单状态
            repairBackBill.setBackStatus(4);
            deviceRepairBackBillService.update(repairBackBill);
            for (String s:strings) {
                //接收无误的装备
                if (s.length()>=2&& "1".equals(s.substring(s.length()-1))) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    //修改装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(1);
                    //添加装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"维修退回装备入库审核失败",null);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
            myWebSocket.sendMessage1();
            return ResultUtil.success("维修成功退回装备入库审核失败");
        }
        else {
            return ResultUtil.failed("status只能为0或1");
        }
    }

    @ApiOperation(value = "更改维修装备状态", notes = "可以通过这个接口更改维修装备状态")
    @PostMapping(value = "/change")
    public ResponseEntity changeRepairDeviceStatus(@RequestBody RepairStatusChangeVo repairStatusChangeVo) {
        //获取当前任务
        TaskBto taskBto = taskService.get(repairStatusChangeVo.getTaskId());
        //获取所有父任务id
        List<Integer> fathers = StringSplitUtil.taskIdSplit(taskBto.getNodeIdDetail());
        //获取维修详情单
        RepairDetail repairDetail1 = deviceRepairDetailService.getOne(repairStatusChangeVo.getId());
        //获取旧状态
        Integer oldStatus = repairDetail1.getRepairStatus();
        //修改当前任务维修详情单该装备状态
        repairDetail1.setRepairStatus(repairStatusChangeVo.getNewStatus());
        //如果修改为已报废，更改新装备详情id为0
        if (repairStatusChangeVo.getNewStatus()==4){
            repairDetail1.setNewDeviceDetailId(0);
        }
        deviceRepairDetailService.update(repairDetail1);
        //修改父任务中所有维修详情单中的该装备的状态
        if (fathers.size()>0) {
            fathers.forEach(integer -> {
                deviceRepairDetailService.findByBillId(integer).stream()
                        .filter(repairDetail -> repairDetail.getDeviceId().equals(repairStatusChangeVo.getDeviceId()))
                        .forEach(repairDetail -> {
                            repairDetail.setRepairStatus(repairStatusChangeVo.getNewStatus());
                            deviceRepairDetailService.update(repairDetail);
                        });
            });
        }
        //获取装备名称
        String deviceName = deviceLibraryService.getOne(repairStatusChangeVo.getDeviceId()).getName();
        //添加业务日志
        String remark = "将装备"+deviceName+"状态由"+ GlobalMap.getRepairStatusMap().get(oldStatus).name+"改为"+GlobalMap.getRepairStatusMap().get(repairStatusChangeVo.getNewStatus()).name;
        TaskLogBto taskLogBto = new TaskLogBto(taskBto.getId(),remark,null);
        taskLogService.addLog(taskLogBto);
        return ResultUtil.success("修改成功");
    }

    @ApiOperation(value = "维修换新设备", notes = "可以通过这个接口维修换新设备")
    @PostMapping(value = "/change/new")
    public ResponseEntity changeNewDevice(@RequestBody 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 deviceLibrary = deviceLibraryService.getOne(changeNewDeviceVo.getDeviceId());
        //判断当前装备是否已报废
        if(repairDetail1.getNewDeviceDetailId()==0){
            //添加新的维修装备详情
            RepairDetail repairDetail = new RepairDetail();
            BeanUtils.copyProperties(repairDetail1,repairDetail);
            repairDetail.setRepairStatus(RepairStatusEnum.CHANGE_NEW.id);
            repairDetail.setDeviceId(changeNewDeviceVo.getDeviceId());
            repairDetail.setNewDeviceDetailId(null);
            repairDetail.setRfidSurfaceId(deviceLibrary.getRfidSurfaceId());
            repairDetail.setSeqNumber(deviceLibrary.getSeqNumber());
            //当前业务和父任务添加该详情
            deviceRepairDetailService.save(repairDetail);
            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());
            });
            //改变装备的所属
            deviceLibrary.setOwnUnit(repairDetail.getOwnUnit());
            deviceLibraryService.update(deviceLibrary);
        }
        return ResultUtil.success("换新成功");
    }

    @ApiOperation(value = "查询维修详情", notes = "可以通过这个接口查询维修详情")
    @GetMapping(value = "/detail/{id}")
    public ResponseEntity getDetail(@PathVariable("id") int id) {
        //获取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());
                repairBillDetailVo.setRepairSendBill(repairSendBill);
                List<Integer> ids = StringSplitUtil.split(repairSendBill.getRepairDeviceCheckDetail());
                List<DeviceLibrary> deviceLibraries = ids.stream()
                        .map(integer -> deviceLibraryService.getOne(integer))
                        .collect(Collectors.toList());
                //获取维修详情
                List<RepairDetail> repairDetails = getRepairDetail(repairBill.getId());
                repairBillDetailVo.setRepairDetails(repairDetails);
                //设置装备备注
                deviceLibraries.forEach(deviceLibrary -> {
                    for (RepairDetail r:repairDetails) {
                        if (r.getDeviceId().equals(deviceLibrary.getId())){
                            deviceLibrary.setRemark(r.getRemark());
                        }
                    }
                });
                if (repairSendBill.getRepairReciveCheckDetail()!=null){
                    List<Integer> integerList = StringSplitUtil.split(repairSendBill.getRepairReciveCheckDetail());
                    List<DeviceLibrary> deviceLibraryList = integerList.stream()
                            .map(integer -> deviceLibraryService.getOne(integer))
                            .collect(Collectors.toList());
                    deviceLibraryList.forEach(deviceLibrary -> {
                        for (RepairDetail r:repairDetails) {
                            if (r.getDeviceId().equals(deviceLibrary.getId())){
                                deviceLibrary.setRemark(r.getRemark());
                            }
                        }
                    });
                    repairBillDetailVo.setReceiveDevices(deviceLibraryList);
                }
                repairBillDetailVo.setDeviceLibraries(deviceLibraries);
                break;
            case 10:
                //获取维修退回单
                RepairBackBill repairBackBill = deviceRepairBackBillService.getOne(taskBto.getBillId());
                if (repairBackBill.getStartUseraId()!=null){
                    repairBackBill.setStartUserA(userPublicService.getOne(repairBackBill.getStartUseraId()).getName());
                }
                if (repairBackBill.getStartUserbId()!=null){
                    repairBackBill.setStartUserB(userPublicService.getOne(repairBackBill.getStartUserbId()).getName());
                }
                if (repairBackBill.getReceiveUseraId()!=null){
                    repairBackBill.setReceiveUserA(userPublicService.getOne(repairBackBill.getReceiveUseraId()).getName());
                }
                if (repairBackBill.getReceiveUserbId()!=null){
                    repairBackBill.setReceiveUserB(userPublicService.getOne(repairBackBill.getReceiveUserbId()).getName());
                }
                //获取装备列表
                List<Integer> integers = StringSplitUtil.split(repairBackBill.getBackCheckDetail());
                List<DeviceLibrary> deviceLibraryList = integers.stream()
                        .map(integer -> deviceLibraryService.getOne(integer))
                        .collect(Collectors.toList());
                //获取维修详情
                List<RepairDetail> repairDetailList = getRepairDetail(repairBackBill.getDeviceRepairBillId());
                repairBillDetailVo.setRepairDetails(repairDetailList);
                //设置装备备注
                deviceLibraryList.forEach(deviceLibrary -> {
                    for (RepairDetail r:repairDetailList) {
                        if (r.getDeviceId().equals(deviceLibrary.getId())){
                            deviceLibrary.setRemark(r.getRemark());
                        }
                    }
                });
                repairBillDetailVo.setDeviceLibraries(deviceLibraryList);
                break;
            default:break;
        }
        return ResultUtil.success(repairBillDetailVo);
    }

    /**
     * @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)) {
                orderList.add(repairDetail);
                if (repairDetail.getRepairStatus().equals(RepairStatusEnum.SCRAPPED.id)) {
                    if (repairDetail.getNewDeviceDetailId()!=null&&repairDetail.getNewDeviceDetailId() > 0) {
                        orderList.add(deviceRepairDetailService.getOne(repairDetail.getNewDeviceDetailId()));
                    }
                }
            }
        });
        return orderList;
    }
}
