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

import com.fasterxml.jackson.core.type.TypeReference;
import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.allot.service.AllotBackBillService;
import com.tykj.dev.device.allot.subject.domin.AllotBackBill;
import com.tykj.dev.device.allot.subject.vo.AgentVo;
import com.tykj.dev.device.allot.subject.vo.AllotBackReceiveVo;
import com.tykj.dev.device.allot.subject.vo.AllotBillSaveVo;
import com.tykj.dev.device.allot.subject.vo.FileUploadVo;
import com.tykj.dev.device.file.service.FilesUtil;
import com.tykj.dev.device.library.service.DeviceLibraryService;
import com.tykj.dev.device.library.service.DeviceLogService;
import com.tykj.dev.device.library.subject.Dto.DeviceLogDto;
import com.tykj.dev.device.library.subject.domin.DeviceLibrary;
import com.tykj.dev.device.library.subject.vo.FileVo;
import com.tykj.dev.device.library.subject.vo.ScriptSaveVo;
import com.tykj.dev.device.task.service.TaskService;
import com.tykj.dev.device.task.subject.bto.TaskBto;
import com.tykj.dev.device.user.read.service.MessageService;
import com.tykj.dev.device.user.read.subject.bto.MessageBto;
import com.tykj.dev.device.user.subject.dao.UserDao;
import com.tykj.dev.device.user.subject.entity.User;
import com.tykj.dev.device.user.subject.service.UserPublicService;
import com.tykj.dev.device.user.util.UserUtils;
import com.tykj.dev.misc.base.ResultObj;
import com.tykj.dev.misc.base.StatusEnum;
import com.tykj.dev.misc.utils.*;
import com.tykj.dev.rfid.service.InputOutputDeviceService;
import com.tykj.dev.socket.MyWebSocket;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author dengdiyi
 */
@RestController
@RequestMapping(value = "/back")
@AutoDocument
@Api(tags = "装备退回模块", description = "装备退回接口")
@Slf4j
public class BackController {

    @Autowired
    UserUtils userUtils;

    @Autowired
    AllotBackBillService allotBackBillService;

    @Autowired
    Snowflake snowflake;

    @Autowired
    UserPublicService userPublicService;

    @Autowired
    private DeviceLibraryService deviceLibraryService;

    @Autowired
    private DeviceLogService deviceLogService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private InputOutputDeviceService inputOutputDeviceService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MyWebSocket myWebSocket;

    @ApiOperation(value = "发起退回业务", notes = "可以通过这个接口发起退回任务")
    @PostMapping(value = "/addBackBill")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity addBackBill(@RequestBody @Validated AllotBillSaveVo allotBillSaveVo) {
        if (allotBillSaveVo.getAllotCheckDetail()!=null&&allotBillSaveVo.getAllotCheckDetail().length()>0) {
            deviceLibraryService.isInStockOrWaitRetired(StringSplitUtil.split(allotBillSaveVo.getAllotCheckDetail()));
        }
        //1.添加配发单
        AllotBackBill a = allotBillSaveVo.toBackDo();
        if (allotBillSaveVo.getTaskId()==null) {
            a.setSendUseraId(userUtils.getCurrentUserId());
        }
        AllotBackBill allotBackBill = allotBackBillService.addEntity(a);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int year = calendar.get(Calendar.YEAR);
        String num = "NO:第" + year + "TH" + allotBackBill.getId() + "号";
        allotBackBill.setNum(num);
        //生成电子签章id
//        Long signId = snowflake.creatNextId();
        Long signId2 = snowflake.creatNextId();
        if (allotBillSaveVo.getLeftSignatureId()!=null) {
            allotBackBill.setLeftSignatureId(allotBillSaveVo.getLeftSignatureId());
        }
        allotBackBill.setRightSignatureId(signId2.toString());
        AllotBackBill allotBackBill1 = allotBackBillService.update(allotBackBill);
        Integer billId = allotBackBill.getId();
        Integer userId = userUtils.getCurrentUserId();
        String deviceIdDetail = allotBackBill.getBackCheckDetail();
        //2.发起任务
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        userIds.add(0);
        TaskBto saveEntity;
        TaskBto taskBto = new TaskBto(StatusEnum.ALLOT_BACKING.id, "退回业务", null, ".", billId, 22, userPublicService.findUnitIdByName(allotBillSaveVo.getReceiveUnit()), 1, null, userIds);
        saveEntity = taskService.start(taskBto);
        TaskBto taskBto2 = new TaskBto(StatusEnum.WAIT_UPLOAD_BACK_FILE_2.id, "退回业务", saveEntity.getId(), saveEntity.getNodeIdDetail() + saveEntity.getId() + ".", saveEntity.getBillId(), 22, userPublicService.findUnitIdByName(allotBackBill1.getSendUnit()), 0, null, Collections.singletonList(0));
        taskService.start(taskBto2);
        List<FileVo> fileVoList = new ArrayList<>();
//        fileVoList.add(new FileVo("出库确认单", allotBillEntity.getFileName(), allotBillEntity.getFileUrl()));
        //存装备日志
        String[] strings = deviceIdDetail.split("x");
        List<Integer> ids = new ArrayList<>();
        for (String s : strings) {
            if (s.length() >= 2) {
                Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                ids.add(id);
                //改变装备状态
                DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                deviceLibraryEntity.setLifeStatus(3);
                deviceLibraryEntity.setManageStatus(0);
                deviceLibraryService.update(deviceLibraryEntity);
                DeviceLogDto deviceLogDto = new DeviceLogDto(id, "对" + allotBackBill.getReceiveUnit() + "发起退回", fileVoList);
                deviceLogService.addLog(deviceLogDto);
            }
        }
        //添加出库白名单
        inputOutputDeviceService.addWhiteDevices(ids, userUtils.getCurrentUnitId(), 1);
        //发送阅知信息
        List<Integer> idList = userPublicService.findOtherUser(userId);
        idList.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(allotBackBill.getReceiveUnit())).stream()
                .map(User::getUserId)
                .collect(Collectors.toList()));
        if (allotBillSaveVo.getSendUserbId()!=null) {
            List<Integer> idList1 = new ArrayList<>();
            idList1.add(allotBillSaveVo.getSendUserbId());
            MessageBto messageBto = new MessageBto(saveEntity.getId(), saveEntity.getBusinessType(), "被选为签发人", idList1, 1);
            messageService.add(messageBto);
        }
        MessageBto messageBto = new MessageBto(saveEntity.getId(),saveEntity.getBusinessType(),"对" + userPublicService.getAreaNameByUnitName(allotBackBill.getReceiveUnit()) + "发起退回",idList,1);
        messageService.add(messageBto);
        log.info("[退回模块]:" + allotBackBill.getSendUnit() + "对" + allotBackBill.getReceiveUnit() + "发起退回");
        myWebSocket.sendMessage1();
        return ResponseEntity.ok(new ResultObj(allotBackBill1, "发起成功"));
    }

    @ApiOperation(value = "接收退回装备", notes = "可以通过这个接口接收退回装备")
    @PostMapping(value = "/receiveDevice")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity receiveDevice(@RequestBody @Validated AllotBackReceiveVo allotBackReceiveVo) {
        Integer userId = userUtils.getCurrentUserId();
        //获取当前任务
        TaskBto taskBto = taskService.get(allotBackReceiveVo.getTaskId());
        List<StatusEnum> statusEnums = Arrays.asList(StatusEnum.ALLOT_BACKING,StatusEnum.BACK_WAIT_SIGN);
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),statusEnums);
        AllotBackBill allotBackBill = allotBackBillService.getOne(taskBto.getBillId());
        List<FileVo> fileVoList = new ArrayList<>();
        if (allotBackReceiveVo.getReceiveFiles()!=null&&allotBackReceiveVo.getReceiveFiles().size()>0){
            allotBackReceiveVo.getReceiveFiles().forEach(fileRet -> {
                fileVoList.add(new FileVo("退回单", fileRet.getName(), fileRet.getPreviewPath()));
            });
            allotBackBill.setReceiveFiles(FilesUtil.stringFileToList(allotBackReceiveVo.getReceiveFiles()));
        }
//        fileVoList.add(new FileVo("退回单", allotBackReceiveVo.getBillFileName(), allotBackReceiveVo.getBillFileUrl()));
//        fileVoList.add(new FileVo("入库确认单", allotReceiveVo.getReceiveFileName(), allotReceiveVo.getReceiveFileUrl()));
        //更新账单状态
        allotBackBill.setBackStatus(3);
        BeanUtils.copyProperties(allotBackReceiveVo, allotBackBill);
        allotBackBill.setReceiveTime(TimestampUtil.getCurrentTimestamp());
        allotBackBill.setReceiveUseraId(userId);
        if (allotBackReceiveVo.getSendUserbId()!=null){
            allotBackBill.setSendUserbId(allotBackReceiveVo.getSendUserbId());
            allotBackBill.setAgent(userPublicService.getOne(allotBackReceiveVo.getSendUserbId()).getName());
        }
        allotBackBillService.update(allotBackBill);
        taskService.addInvolveUser(taskBto, userId);
//        //推至下一阶段
//        taskService.update(taskService.moveToNext(taskBto, allotReceiveVo.getReceiveUserbId()));
        if (allotBackReceiveVo.getStatus()==0) {
            taskService.moveToEnd(taskBto);
            taskService.moveAllSonNodeToEnd(taskBto.getId());
        }
        else {
            taskService.moveToNext(taskBto);
        }
        //分隔装备id信息
        String deviceIdDetail = allotBackReceiveVo.getReceiveCheckDetail();
        String[] strings = deviceIdDetail.split("x");
        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));
                    //改变装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
//                    deviceLibraryEntity.setLifeStatus(0);
                    deviceLibraryEntity.setLocationUnit(userUtils.getCurrentUserUnitName());
                    deviceLibraryEntity.setLifeStatus(2);
                    deviceLibraryEntity.setOwnUnit(userUtils.getCurrentUserUnitName());
                    deviceLibraryEntity.setManageStatus(1);
                    //存装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id, "接收并发起入库", fileVoList);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
                //接收缺失
                if ("0".equals(s.substring(s.length() - 1))) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    //改变装备状态
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLifeStatus(11);
                    //存装备日志
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id, "接收入库丢失", fileVoList);
                    deviceLogService.addLog(deviceLogDto);
                    deviceLibraryService.update(deviceLibraryEntity);
                }
            }
        }
        //发送阅知信息
        List<Integer> ids = userPublicService.findOtherUser(userId);
        ids.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(allotBackBill.getSendUnit())).stream()
                .map(User::getUserId)
                .collect(Collectors.toList()));
        if (allotBackReceiveVo.getReceiveUserbId()!=null) {
            List<Integer> idList1 = new ArrayList<>();
            idList1.add(allotBackReceiveVo.getReceiveUserbId());
            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", idList1, 1);
            messageService.add(messageBto);
        }
        if (allotBackReceiveVo.getSendUserbId()!=null) {
            List<Integer> idList1 = new ArrayList<>();
            idList1.add(allotBackReceiveVo.getSendUserbId());
            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为签发人", idList1, 1);
            messageService.add(messageBto);
        }
        String message = allotBackReceiveVo.getStatus()==0?"业务办结":"接收退回装备";
        MessageBto messageBto = new MessageBto(taskBto.getId(),taskBto.getBusinessType(),message,ids,1);
        messageService.add(messageBto);
        log.info("[退回模块]:接收并发起入库");
        myWebSocket.sendMessage1();
        return ResponseEntity.ok("退回接收入库");
    }

    @ApiOperation(value = "上传接收方退回单", notes = "可以通过这个接口上传送修单")
    @PostMapping(value = "/uploadAllotBill")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity uploadAllotBill(@RequestBody @Validated FileUploadVo fileUploadVo){
        TaskBto taskBto = taskService.get(fileUploadVo.getTaskId());
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),StatusEnum.WAIT_UPLOAD_ALLOT_BACK_FILE);
        Integer userId = userUtils.getCurrentUserId();
        taskService.addInvolveUser(taskBto,userId);
        //不上传单据
        if (fileUploadVo.getStatus()==0){
            taskService.moveToArchive(taskBto);
        }
        else {
            taskService.moveToEnd(taskBto);
            taskService.moveAllSonNodeToEnd(taskBto.getId());
            AllotBackBill allotBackBill = allotBackBillService.getOne(taskBto.getBillId());
            allotBackBill.setBillFileName(fileUploadVo.getBillFileName());
            allotBackBill.setBillFileUrl(fileUploadVo.getBillFileUrl());
            if (fileUploadVo.getSendUserbId()!=null){
                allotBackBill.setSendUserbId(fileUploadVo.getSendUserbId());
                allotBackBill.setAgent(userPublicService.getOne(fileUploadVo.getSendUserbId()).getName());
            }
            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()));
                });
                allotBackBill.setReceiveFiles(FilesUtil.stringFileToList(fileUploadVo.getReceiveFiles()));
            }
            allotBackBillService.update(allotBackBill);
//            fileVoList.add(new FileVo("退回单", allotBackBill.getBillFileName(), allotBackBill.getBillFileUrl()));
            //添加装备日志
            List<Integer> deviceIds = StringSplitUtil.split(allotBackBill.getBackCheckDetail());
            deviceIds.forEach(integer -> {
                //存装备日志
                DeviceLogDto deviceLogDto = new DeviceLogDto(integer, "上传退回单据", fileVoList);
                deviceLogService.addLog(deviceLogDto);
            });
            if (fileUploadVo.getSendUserbId()!=null) {
                List<Integer> idList1 = new ArrayList<>();
                idList1.add(fileUploadVo.getSendUserbId());
                MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为签发人", idList1, 1);
                messageService.add(messageBto);
            }
            //发送阅知信息
            List<Integer> ids = userPublicService.findOtherUser(userId);
            ids.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(allotBackBill.getSendUnit())).stream()
                    .map(User::getUserId)
                    .collect(Collectors.toList()));
            MessageBto messageBto = new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"业务办结",ids,1);
            messageService.add(messageBto);
        }
        return ResponseEntity.ok("上传成功");
    }

    @ApiOperation(value = "上传发送方退回单", notes = "上传退回单")
    @PostMapping(value = "/uploadFile")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity uploadFile(@RequestBody @Validated com.tykj.dev.device.allot.subject.vo.FileVo fileVo){
        //获取task
        TaskBto taskBto = taskService.get(fileVo.getTaskId());
        taskService.addInvolveUser(taskBto,userUtils.getCurrentUserId());
        List<StatusEnum> statusEnums = new ArrayList<>();
        statusEnums.add(StatusEnum.WAIT_UPLOAD_BACK_FILE_2);
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),statusEnums);
        AllotBackBill allotBackBill = allotBackBillService.getOne(taskBto.getBillId());
        List<Integer> idList = new ArrayList<>();
        if (fileVo.getReceiveUseraId()!=null) {
            allotBackBill.setReceiveUseraId(fileVo.getReceiveUseraId());
            idList.add(fileVo.getReceiveUseraId());
        }
        if (fileVo.getReceiveUserbId()!=null) {
            allotBackBill.setReceiveUserbId(fileVo.getReceiveUserbId());
            idList.add(fileVo.getReceiveUserbId());
        }
        //保存账单
        allotBackBill.setSendFiles(FilesUtil.stringFileToList(fileVo.getAllotFiles()));
        allotBackBillService.update(allotBackBill);
        List<Integer> ids = StringSplitUtil.split(allotBackBill.getBackCheckDetail());
        //业务完结
        taskService.moveToEnd(taskBto);
        //主业务完结
        taskService.moveToEnd(taskService.get(taskBto.getParentTaskId()));
        //装备日志
        List<FileVo> fileVoList = new ArrayList<>();
        fileVo.getAllotFiles().forEach(fileRet -> fileVoList.add(new FileVo("退回单", fileRet.getName(), fileRet.getPreviewPath())));
        ids.forEach(integer -> {
            DeviceLogDto deviceLogDto = new DeviceLogDto(integer, "上传退回单", fileVoList);
            deviceLogService.addLog(deviceLogDto);
        });
        if (idList.size()>0) {
            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", idList, 1);
            messageService.add(messageBto);
        }
        //发送阅知信息
        List<Integer> userIds = userPublicService.findOtherUser(userUtils.getCurrentUserId());
        userIds.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(allotBackBill.getReceiveUnit())).stream()
                .map(User::getUserId)
                .collect(Collectors.toList()));
        MessageBto messageBto = new MessageBto(taskBto.getParentTaskId(),taskBto.getBusinessType(),"业务办结",userIds,1);
        messageService.add(messageBto);
        return ResponseEntity.ok("OK");
    }

    @ApiOperation(value = "上传发送方签发人", notes = "上传发送方签发人")
    @PostMapping(value = "/updateAgent")
    public ResponseEntity updateAgent(@RequestBody AgentVo agentVo){
        TaskBto taskBto = taskService.get(agentVo.getId());
        List<Integer> idList = new ArrayList<>();
        idList.add(agentVo.getSendUserbId());
        MessageBto messageBto = new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"被选为签发人",idList,1);
        messageService.add(messageBto);
        AllotBackBill allotBackBill = allotBackBillService.getOne(taskBto.getBillId());
        allotBackBill.setAgent(agentVo.getName());
        allotBackBill.setSendUserbId(agentVo.getSendUserbId());
        return ResponseEntity.ok(allotBackBillService.update(allotBackBill));
    }

    @ApiOperation(value = "保存退回操作", notes = "可以通过这个接口保存退回操作")
    @PostMapping(value = "/saveBackBill")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity saveBackBill(@RequestBody AllotBillSaveVo allotBillSaveVo) {
        //第一次保存
        if (allotBillSaveVo.getTaskId()==null){
            Integer userId = userUtils.getCurrentUserId();
            //保存退回单
            List<Integer> userIds = new ArrayList<>();
            userIds.add(userId);
            AllotBackBill allotBackBill = allotBillSaveVo.toBackDo();
            allotBackBill.setBackStatus(1);
            allotBackBill.setSendUseraId(userId);
            AllotBackBill allotBackBill1 = allotBackBillService.addEntity(allotBackBill);
            //发起任务
            TaskBto taskBto = new TaskBto(StatusEnum.BACK_DRAFT.id, "退回业务", null, ".", allotBackBill1.getId(), 22, userUtils.getCurrentUnitId(), 0, null, userIds);
            TaskBto taskBto1 = taskService.start(taskBto);
            //改变装备状态为待退回
//            if (allotBillSaveVo.getAllotCheckDetail()!=null){
//                Map<Integer,DeviceLibrary> map = deviceLibraryService.getAllDeviceMap();
//                StringSplitUtil.split(allotBillSaveVo.getAllotCheckDetail()).forEach(integer -> {
//                    if (map.get(integer)!=null){
//                        DeviceLibrary deviceLibrary = map.get(integer);
//                        deviceLibrary.setLifeStatus(22);
//                        deviceLibraryService.update(deviceLibrary);
//                    }
//                });
//            }
            Integer id = taskBto1.getId();
            myWebSocket.sendMessage1();
            return ResponseEntity.ok("保存成功"+id);
        }
        else {
            //更新账单
            TaskBto taskBto = taskService.get(allotBillSaveVo.getTaskId());
            AllotBackBill allotBackBill = allotBackBillService.getOne(taskBto.getBillId());
            AllotBackBill allotBackBill1 = allotBillSaveVo.toBackDo();
            allotBackBill1.setBackStatus(1);
            MapperUtils.copyNoNullProperties(allotBackBill1,allotBackBill);
            allotBackBillService.update(allotBackBill);
            return ResponseEntity.ok("更新成功"+taskBto.getId());
        }
    }

    @ApiOperation(value = "删除退回单草稿", notes = "可以通过这个接口删除退回单草稿")
    @PostMapping(value = "/deleteBackBill/{taskId}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity deleteBackBill(@PathVariable("taskId") int taskId) {
        //任务封存
        TaskBto taskBto = taskService.get(taskId);
        TaskBto taskBto1 = taskService.addInvolveUser(taskBto,userUtils.getCurrentUserId());
        taskService.moveToArchive(taskBto1);
        //更改装备状态为在库
//        AllotBackBill allotBackBill = allotBackBillService.getOne(taskBto1.getBillId());
//        if (allotBackBill.getBackCheckDetail()!=null){
//            Map<Integer,DeviceLibrary> map = deviceLibraryService.getAllDeviceMap();
//            StringSplitUtil.split(allotBackBill.getBackCheckDetail()).forEach(integer -> {
//                if (map.get(integer)!=null){
//                    DeviceLibrary deviceLibrary = map.get(integer);
//                    deviceLibrary.setLifeStatus(2);
//                    deviceLibraryService.update(deviceLibrary);
//                }
//            });
//        }
        myWebSocket.sendMessage1();
        return ResponseEntity.ok("删除成功");
    }

    @ApiOperation(value = "申请电子签章", notes = "可以通过这个接口申请电子签章")
    @PostMapping(value = "/applySign/{taskId}/{userId}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity applySign(@PathVariable("taskId") int taskId,@PathVariable("userId") int userId) {
        //推动任务
        TaskBto taskBto = taskService.get(taskId);
        taskService.moveToSpecial(taskBto,StatusEnum.BACK_SIGN_WAIT_CONFIRM,userId);
        myWebSocket.sendMessage1();
        return ResponseEntity.ok("申请成功");
    }

    @ApiOperation(value = "申请电子签章审核", notes = "可以通过这个接口申请电子签章审核")
    @PostMapping(value = "/applySignConfirm/{taskId}/{status}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity applySignConfirm(@PathVariable("taskId") int taskId,@PathVariable("status") int status) {
        //推动任务
        TaskBto taskBto = taskService.get(taskId);
        AllotBackBill allotBill = allotBackBillService.getOne(taskBto.getBillId());
        if (status==1){
            taskService.moveToSpecial(taskBto,StatusEnum.BACK_WAIT_SIGN);
            if (allotBill.getBackStatus()==0) {
                allotBill.setSendUserbId(userUtils.getCurrentUserId());
                allotBill.setAgent(userUtils.getCurrentName());
            }
            else {
                allotBill.setReceiveUserbId(userUtils.getCurrentUserId());
            }
            allotBackBillService.update(allotBill);
        }
        else {
            if (allotBill.getBackStatus()==0) {
                taskService.moveToSpecial(taskBto, StatusEnum.BACK_DRAFT, taskBto.getCreateUserId());
            }
            else {
                taskService.moveToSpecial(taskBto, StatusEnum.ALLOT_BACKING, allotBill.getReceiveUseraId());
            }
        }
        myWebSocket.sendMessage1();
        return ResponseEntity.ok("申请成功");
    }

    @ApiOperation(value = "查询退回草稿详情", notes = "可以通过这个接口查询退回草稿详情")
    @PostMapping(value = "/selectBackDetail/{taskId}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity selectBackDetail(@PathVariable("taskId") int taskId) {
        TaskBto taskBto = taskService.get(taskId);
        AllotBackBill allotBillEntity = allotBackBillService.getOne(taskBto.getBillId());
        if (allotBillEntity.getSendUseraId() != null) {
            allotBillEntity.setSenderUserA(userPublicService.getOne(allotBillEntity.getSendUseraId()).getName());
        }
        if (allotBillEntity.getSendUserbId() != null) {
            allotBillEntity.setSenderUserB(userPublicService.getOne(allotBillEntity.getSendUserbId()).getName());
        }
        if (allotBillEntity.getReceiveUseraId() != null) {
            allotBillEntity.setReceiveUserA(userPublicService.getOne(allotBillEntity.getReceiveUseraId()).getName());
        }
        if (allotBillEntity.getReceiveUserbId() != null) {
            allotBillEntity.setReceiveUserB(userPublicService.getOne(allotBillEntity.getReceiveUserbId()).getName());
        }
        if (allotBillEntity.getBackCheckDetail()!=null){
            List<Integer> ids = StringSplitUtil.split(allotBillEntity.getBackCheckDetail());
            List<DeviceLibrary> deviceLibraryList = new ArrayList<>();
            ids.forEach(integer -> deviceLibraryList.add(deviceLibraryService.getOne(integer)));
            allotBillEntity.setDeviceLibraries(deviceLibraryList);
        }
        allotBillEntity.setReplyFileList(FilesUtil.stringFileToList(allotBillEntity.getReplyFiles()));
        allotBillEntity.setApplyFileList(FilesUtil.stringFileToList(allotBillEntity.getApplyFiles()));
        if (allotBillEntity.getScriptJson()!=null){
            allotBillEntity.setScripts(JacksonUtil.readValue(allotBillEntity.getScriptJson(),new TypeReference<List<ScriptSaveVo>>() {}));
        }
        return ResponseEntity.ok(allotBillEntity);
    }
}
