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.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();
        //保存后的实体
        AllotBackBill allotBackBill;
        //如果是直接发起（不是草稿，没有taskId）,当前操作人为发件方A岗,添加账单
        if (allotBillSaveVo.getTaskId()==null){
            a.setSendUseraId(userUtils.getCurrentUserId());
            allotBackBill = allotBackBillService.addEntity(a);
        }
        //从草稿发起
        else {
            //获取草稿账单
            allotBackBill = allotBackBillService.getOne(taskService.get(allotBillSaveVo.getTaskId()).getBillId());
            //copy非null相同字段值
            MapperUtils.copyNoNullProperties(a,allotBackBill);
            //判断是否取消上传申请单和批复单据
            if (a.getApplyFiles()==null||"".equals(a.getApplyFiles())){
                allotBackBill.setApplyFiles(null);
            }
            if (a.getReplyFiles()==null||"".equals(a.getReplyFiles())){
                allotBackBill.setReplyFiles(null);
            }
            allotBackBill = allotBackBillService.update(allotBackBill);
        }
        //按照当前时间和保存账单的id拼接生成退回单号并保存
        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 signId2 = snowflake.creatNextId();
        //判断是否上传了发送方签章id
        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.发起任务
        //构建task涉及人员集合
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        userIds.add(0);
        //保存后的taskBto
        TaskBto saveEntity;
        //直接发起
        if (allotBillSaveVo.getTaskId()==null) {
            TaskBto taskBto = new TaskBto(StatusEnum.ALLOT_BACKING.id, "退回业务", null, ".", billId, 22, userPublicService.findUnitIdByName(allotBillSaveVo.getReceiveUnit()), 1, null, userIds);
            saveEntity = taskService.start(taskBto);
        }
        //从草稿发起
        else {
            TaskBto taskBto = taskService.get(allotBillSaveVo.getTaskId());
            //添加当前操作人为涉及人员
            TaskBto taskBto1 = taskService.addInvolveUser(taskBto,userId);
            //任务所属单位改为收件单位
            taskBto1.setOwnUnit(userPublicService.findUnitIdByName(allotBillSaveVo.getReceiveUnit()));
            //推动任务到退回中状态
            saveEntity = taskService.moveToSpecial(taskBto1,StatusEnum.ALLOT_BACKING,0);
        }
        //生成发件方上传退回单的子任务
        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<>();
        //存装备日志
        String[] strings = deviceIdDetail.split("x");
        //存放所有出库装备id
        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) {
        //当前操作人id
        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.getReceiveFileList()!=null&&allotBackReceiveVo.getReceiveFileList().size()>0){
            allotBackReceiveVo.getReceiveFileList().forEach(fileRet -> {
                fileVoList.add(new FileVo("退回单", fileRet.getName(), fileRet.getPreviewPath()));
            });
            allotBackBill.setReceiveFiles(FilesUtil.stringFileToList(allotBackReceiveVo.getReceiveFileList()));
        }
        //是否上传了收件单位签章id
        if (allotBackReceiveVo.getRightSignatureId()!=null&&!"".equals(allotBackReceiveVo.getRightSignatureId())) {
            allotBackBill.setRightSignatureId(allotBackReceiveVo.getRightSignatureId());
        }
        //更新账单状态为退回完成
        allotBackBill.setBackStatus(3);
        //复制非空相同字段
        MapperUtils.copyNoNullProperties(allotBackReceiveVo, allotBackBill);
        //set接收时间
        allotBackBill.setReceiveTime(TimestampUtil.getCurrentTimestamp());
        //如果收件方A岗未上传，默认为当前操作人
        if (allotBackBill.getReceiveUseraId()==null) {
            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);
        //如果上传了单据或双方都盖章，该业务和子业务都办结
        if (allotBackReceiveVo.getStatus()==0) {
            taskService.moveToEnd(taskBto);
            //子任务完结
            taskService.moveAllSonNodeToEnd(taskBto.getId());
        }
        else {
            //推至待上传签收单的状态
            taskService.moveToSpecial(taskBto,StatusEnum.WAIT_UPLOAD_ALLOT_BACK_FILE,0);
        }
        //分隔装备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))) {
                    //装备id
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    //改变装备状态、所属所在
                    DeviceLibrary deviceLibraryEntity = deviceLibraryService.getOne(id);
                    deviceLibraryEntity.setLocationUnit(userUtils.getCurrentUserUnitName());
                    deviceLibraryEntity.setLifeStatus(2);
                    deviceLibraryEntity.setOwnUnit(userUtils.getCurrentUserUnitName());
                    deviceLibraryEntity.setManageStatus(1);
                    //存装备日志
                    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);
        }
        //根据status判断是否业务完结，发送不同的阅知message
        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);
        //业务和子业务办结
        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());
        }
        //是否上传接收方B岗
//        if (fileUploadVo.getReceiveUserbId()!=null){
//            allotBackBill.setReceiveUserbId(fileUploadVo.getReceiveUserbId());
//            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", Collections.singletonList(fileUploadVo.getReceiveUserbId()), 1);
//            messageService.add(messageBto);
//        }
        //文件列表
        List<FileVo> fileVoList = new ArrayList<>();
        if (fileUploadVo.getReceiveFileList()!=null&&fileUploadVo.getReceiveFileList().size()>0){
            fileUploadVo.getReceiveFileList().forEach(fileRet -> {
                fileVoList.add(new FileVo("退回单", fileRet.getName(), fileRet.getPreviewPath()));
            });
            allotBackBill.setReceiveFiles(FilesUtil.stringFileToList(fileUploadVo.getReceiveFileList()));
        }
        allotBackBillService.update(allotBackBill);
        //添加装备日志
        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());
        //存放接收方经办人id
        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());
        }
        //签发人阅知
        if (fileVo.getSendUserbId()!=null){
            allotBackBill.setSendUserbId(fileVo.getSendUserbId());
            allotBackBill.setAgent(userPublicService.getOne(fileVo.getSendUserbId()).getName());
            List<Integer> idList1 = new ArrayList<>();
            idList1.add(fileVo.getSendUserbId());
            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为签发人", idList1, 1);
            messageService.add(messageBto);
        }
        //保存账单
        //回执单
        allotBackBill.setSendFiles(FilesUtil.stringFileToList(fileVo.getAllotFiles()));
        //状态退回完成
        allotBackBill.setBackStatus(3);
        //接收时间
        allotBackBill.setReceiveTime(TimestampUtil.getCurrentTimestamp());
        allotBackBillService.update(allotBackBill);
        //装备Id集合
        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);
            DeviceLibrary deviceLibrary = deviceLibraryService.getOne(integer);
            deviceLibrary.setLocationUnit(allotBackBill.getReceiveUnit());
            deviceLibrary.setLifeStatus(2);
            deviceLibrary.setOwnUnit(allotBackBill.getReceiveUnit());
            deviceLibrary.setManageStatus(1);
            deviceLibraryService.update(deviceLibrary);
        });
        //经办人阅知
//        if (idList.size()>0) {
//            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "被选为经办人", idList, 1);
//            messageService.add(messageBto);
//        }
        //发送阅知信息
        List<Integer> userIds = userPublicService.findOtherUser(userUtils.getCurrentUserId());
        userIds.addAll(userDao.findAllByUnitsId(userPublicService.findUnitIdByName(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.getAllotCheckDetail()!=null&&allotBillSaveVo.getAllotCheckDetail().length()>0) {
            deviceLibraryService.isInStockOrWaitRetired(StringSplitUtil.split(allotBillSaveVo.getAllotCheckDetail()));
        }
        //第一次保存（没有taskId）
        if (allotBillSaveVo.getTaskId()==null){
            Integer userId = userUtils.getCurrentUserId();
            //保存退回单
            List<Integer> userIds = new ArrayList<>();
            userIds.add(userId);
            //转Do
            AllotBackBill allotBackBill = allotBillSaveVo.toBackDo();
            //状态设为草稿
            allotBackBill.setBackStatus(1);
            //发件A岗设为当前操作人
            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);
            //返回保存成功的id
            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);
        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);
        AllotBackBill allotBill = allotBackBillService.getOne(taskBto.getBillId());
        //如果是收件方申请电子签章
        if (allotBill.getBackStatus()!=1){
            //当前用户设为接收A岗
            allotBill.setReceiveUseraId(userUtils.getCurrentUserId());
            allotBackBillService.update(allotBill);
        }
        //推动任务到盖章待审核状态
        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()==1) {
                //当前用户设为签发人
                allotBill.setSendUserbId(userUtils.getCurrentUserId());
                allotBill.setAgent(userUtils.getCurrentName());
            }
            //收件方盖章
            else {
                //当前用户设为接收方B岗
                allotBill.setReceiveUserbId(userUtils.getCurrentUserId());
            }
            allotBackBillService.update(allotBill);
        }
        else {
            //发件方盖章不同意任务返回草稿状态
            if (allotBill.getBackStatus()==1) {
                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());
        //将用户id转为名字
        if (allotBillEntity.getSendUseraId() != null) {
            allotBillEntity.setSenderUserA(userPublicService.getOne(allotBillEntity.getSendUseraId()).getName());
        }
        if (allotBillEntity.getSendUserbId() != null) {
            allotBillEntity.setSenderUserB(userPublicService.getOne(allotBillEntity.getSendUserbId()).getName());
        }
        if (allotBillEntity.getReceiveUseraId() != null) {
            allotBillEntity.setReceiveUserA(userPublicService.getOne(allotBillEntity.getReceiveUseraId()).getName());
        }
        if (allotBillEntity.getReceiveUserbId() != null) {
            allotBillEntity.setReceiveUserB(userPublicService.getOne(allotBillEntity.getReceiveUserbId()).getName());
        }
        //分隔装备id得到装备信息
        if (allotBillEntity.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()));
        //返回前端单据json详情
        if (allotBillEntity.getScriptJson()!=null){
            allotBillEntity.setScripts(JacksonUtil.readValue(allotBillEntity.getScriptJson(),new TypeReference<List<ScriptSaveVo>>() {}));
        }
        return ResponseEntity.ok(allotBillEntity);
    }
}
