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

import com.fasterxml.jackson.core.type.TypeReference;
import com.tykj.dev.config.repository.SystemVariableDao;
import com.tykj.dev.config.service.SystemVariableService;
import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.file.service.FilesUtil;
//import com.tykj.dev.device.library.repository.DeviceLibraryDao;
import com.tykj.dev.device.library.service.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.selfcheck.base.SelfCheckSchedulerTask;
import com.tykj.dev.device.selfcheck.service.SelfCheckBillService;
import com.tykj.dev.device.selfcheck.subject.domin.SelfCheckBill;
import com.tykj.dev.device.selfcheck.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.domin.Task;
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.UnitsDao;
import com.tykj.dev.device.user.subject.entity.Units;
import com.tykj.dev.device.user.subject.entity.User;
import com.tykj.dev.device.user.subject.service.UserPublicService;
import com.tykj.dev.device.user.util.UserUtils;
import com.tykj.dev.misc.base.BusinessEnum;
import com.tykj.dev.misc.base.StatusEnum;
import com.tykj.dev.misc.exception.ApiException;
import com.tykj.dev.misc.utils.JacksonUtil;
import com.tykj.dev.misc.utils.ResultUtil;
import com.tykj.dev.misc.utils.StringSplitUtil;
import com.tykj.dev.misc.utils.TaskDisposeUtil;
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.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
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.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;

/**
 * @author dengdiyi
 */
@RestController
@RequestMapping(value = "/selfCheck")
@AutoDocument
@Api(tags = "自查模块",description = "自查接口")
@Slf4j
public class SelfCheckController {

    @Autowired
    private SelfCheckBillService selfExaminationBillService;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private TaskService taskService;

    @Autowired
    private DeviceLibraryService deviceLibraryService;

//    @Autowired
//    private DeviceLibraryDao deviceLibraryDao;

    @Autowired
    private DeviceLogService deviceLogService;

    @Autowired
    private TaskLogService taskLogService;

    @Autowired
    private UserPublicService userPublicService;

    @Autowired
    private MyWebSocket myWebSocket;

    @Autowired
    private SystemVariableService systemVariableService;

    @Autowired
    private SelfCheckSchedulerTask selfCheckSchedulerTask;

    @Autowired
    private MessageService messageService;

    @Autowired
    @Qualifier("taskExecutor")
    private Executor executor;

    /**
     * 月度
     */
    private String cron1 = "0 0 0 1 1/1 ? ";
    /**
     * 季度
     */
    private String cron2 = "0 0 0 1 1,4,7,10 ? ";
    /**
     * 年度
     */
    private String cron3 = "0 0 0 1 1 ? ";

    private String cron4 = "0 0/1 * * * ? ";

    @ApiOperation(value = "查询自查周期", notes = "可以通过这个接口查询自查周期")
    @GetMapping(value = "/select/cycle")
    public ResponseEntity selectCycle(){
        String vaule = systemVariableService.getVaule("selfCheckCycle");
        int type;
        if (' '==vaule.charAt(11)) {
            type = Integer.parseInt(vaule.substring(10,11));
        }
        else {
            type = Integer.parseInt(vaule.substring(10,12));
        }
        return ResponseEntity.ok(type);
    }

    @ApiOperation(value = "设置自查周期", notes = "可以通过这个接口设置自查周期")
    @PostMapping(value = "/set/cycle/{type}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity setCycle(@PathVariable("type") int type){
        if (selfCheckSchedulerTask!=null) {
            String corn = "0 0 0 1 1/"+type+" ? ";
            ScheduledFuture scheduledFuture = selfCheckSchedulerTask.getScheduledFuture();
            scheduledFuture.cancel(true);
            selfCheckSchedulerTask.setCron(corn);
            selfCheckSchedulerTask.startTask();
            systemVariableService.setVaule("selfCheckCycle",corn);
            log.info("[自查模块]:自查周期更改为"+type+"个月");
            return ResponseEntity.ok("自查周期更改为"+type+"个月");
//            switch (type) {
//                case 1:
//                    selfCheckSchedulerTask.setCron(cron1);
//                    ScheduledFuture scheduledFuture = selfCheckSchedulerTask.getScheduledFuture();
//                    scheduledFuture.cancel(true);
//                    selfCheckSchedulerTask.startTask();
//                    systemVariableService.setVaule("selfCheckCycle","month");
//                    log.info("[自查模块]:自查周期更改为月度");
//                    return ResponseEntity.ok("自查周期更改为月度");
//                case 2:
//                    selfCheckSchedulerTask.setCron(cron2);
//                    ScheduledFuture scheduledFuture2 = selfCheckSchedulerTask.getScheduledFuture();
//                    scheduledFuture2.cancel(true);
//                    selfCheckSchedulerTask.startTask();
//                    systemVariableService.setVaule("selfCheckCycle","quarter");
//                    log.info("[自查模块]:自查周期更改为季度");
//                    return ResponseEntity.ok("自查周期更改为季度");
//                case 3:
//                    selfCheckSchedulerTask.setCron(cron3);
//                    ScheduledFuture scheduledFuture3 = selfCheckSchedulerTask.getScheduledFuture();
//                    scheduledFuture3.cancel(true);
//                    selfCheckSchedulerTask.startTask();
//                    systemVariableService.setVaule("selfCheckCycle","year");
//                    log.info("[自查模块]:自查周期更改为年度");
//                    return ResponseEntity.ok("自查周期更改为年度");
//                case 4:
//                    selfCheckSchedulerTask.setCron(cron4);
//                    ScheduledFuture scheduledFuture4 = selfCheckSchedulerTask.getScheduledFuture();
//                    scheduledFuture4.cancel(true);
//                    selfCheckSchedulerTask.startTask();
//                    systemVariableService.setVaule("selfCheckCycle","minute");
//                    log.info("[自查模块]:自查周期更改为每分钟");
//                    return ResponseEntity.ok("自查周期更改为每分钟");
//                default:
//                    return ResponseEntity.ok(ResultUtil.failed("设置失败:type只能为1，2，3"));
//            }
        }
        else {
            throw new ApiException(ResultUtil.failed("selfCheckSchedulerTask为null"));
        }
    }

    @ApiOperation(value = "装备比较", notes = "可以通过这个接口发起比较装备")
    @PostMapping(value = "/compare")
    public ResponseEntity compare(@RequestBody CompareVo compareVo) {
        Map<Integer,DeviceLibrary> deviceLibraryMap = deviceLibraryService.getAllDeviceMap();
        CompareResultVo compareResultVo = new CompareResultVo();
        //所有装备id的集合
        List<Integer> list = compareVo.getDeivceIdList();
        List<String> list1 = new ArrayList<>();
        List<DeviceLibrary> deviceLibraryEntities = new ArrayList<>();
        List<DeviceLibrary> newList = new ArrayList<>();
        List<DeviceLibrary> resultList = new ArrayList<>();
        //前端出
        List<Integer> detailIds = compareVo.getDetailIdList();
        for (int i = 0;i<list.size();i++) {
            DeviceLibrary d = deviceLibraryMap.get(list.get(i));
            if (detailIds.size()>i){
                d.setDetailId(detailIds.get(i));
            }
            //list1存应查装备rfid卡号
            list1.add(d.getRfidCardId());
            //deviceLibraryEntities存应查装备
            deviceLibraryEntities.add(d);
        }
        //list2存扫码得到的rfid卡号
        List<String> list2 = compareVo.getRfidResultList();
        if (list2.size()>0) {
            //取交集
            list1.retainAll(list2);
            //遍历应查装备
            for (DeviceLibrary d : deviceLibraryEntities) {
                //如果在交集中，检查结果为正常
                if (list1.contains(d.getRfidCardId())) {
                    d.setCheckResult(1);
                }
                //否则检查结果为丢失
                else {
                    d.setCheckResult(0);
                }
            }
            //遍历扫码结果
            for (String s : list2) {
                //如果不在交集中，则为新增
                if (!list1.contains(s)) {
//                    List<DeviceLibrary> d = deviceLibraryDao.getAllByRfidCardId(s);
                    List<DeviceLibrary> d =deviceLibraryService.getAllByRfidCardId(s);
                    //如果新增的为系统中存在的装备
                    if (d.size() > 0) {
                        for (DeviceLibrary deviceLibraryEntity : d) {
                            deviceLibraryEntity.setCheckResult(2);
                            resultList.add(deviceLibraryEntity);
                        }
                    }
                    //如果为系统中不存在的装备，添加到newList
                    if (d.isEmpty()) {
                        DeviceLibrary deviceLibraryEntity = new DeviceLibrary();
                        deviceLibraryEntity.setCheckResult(2);
                        deviceLibraryEntity.setSeqNumber("-");
                        deviceLibraryEntity.setName("-");
                        deviceLibraryEntity.setType(0);
                        deviceLibraryEntity.setModel("-");
                        deviceLibraryEntity.setRfidSurfaceId("-");
                        deviceLibraryEntity.setProdNumber("-");
                        deviceLibraryEntity.setRfidCardId(s);
                        newList.add(deviceLibraryEntity);
                    }
                }
            }
            //在新增后面加丢失的装备
            for (DeviceLibrary d : deviceLibraryEntities) {
                if (d.getCheckResult() == 0) {
                    resultList.add(d);
                }
            }
            //最后加正常的装备
            for (DeviceLibrary d : deviceLibraryEntities) {
                if (d.getCheckResult() == 1) {
                    resultList.add(d);
                }
            }
            compareResultVo.setNewList(newList);
            compareResultVo.setResultList(resultList);
        }
        else {
            compareResultVo.setNewList(newList);
            for (DeviceLibrary d:deviceLibraryEntities) {
                d.setCheckResult(0);
                resultList.add(d);
            }
            compareResultVo.setResultList(resultList);
        }
        return ResultUtil.success(compareResultVo);
    }

    @ApiOperation(value = "生成自查待办", notes = "可以通过这个接口生成自查待办")
    @GetMapping(value = "/create/{type}")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity createTask(@PathVariable("type") int type){
        String message = type==0?"手动":"扫码";
        String message2 = type==0?"手动":"终端";
        String unitName = userUtils.getCurrentUserUnitName();
        SelfCheckBill selfCheckBill = new SelfCheckBill();
        selfCheckBill.setCheckStatus(3);
        selfCheckBill.setCheckUnit(unitName);
        selfCheckBill.setCheckUnitId(userUtils.getCurrentUnitId());
        selfCheckBill.setTitle(unitName + "发起的"+message2+"自查任务");
        SelfCheckBill selfCheckBill1 = selfExaminationBillService.addEntity(selfCheckBill);
        //发起待自查任务
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userUtils.getCurrentUserId());
        TaskBto taskBto = new TaskBto(StatusEnum.WAIT_SELF_CHECK.id,selfCheckBill1.getTitle(),null,".",selfCheckBill1.getId(),4,userUtils.getCurrentUnitId(),0,message,userIds);
        TaskBto taskBto1 = taskService.start(taskBto);
        return ResponseEntity.ok(taskBto1.getId());
    }

    @ApiOperation(value = "发起自查业务", notes = "可以通过这个接口发起自查业务")
    @PostMapping(value = "/addBill")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity addSelfExaminationBill(@RequestBody @Validated SelfCheckSaveVo selfCheckSaveVo) {
        //添加账单
        SelfCheckBill selfExaminationBillEntity;
        List<FileVo> fileVoList = new ArrayList<>();
        TaskBto taskBto;
        if (selfCheckSaveVo.getTaskId()!=null){
             taskBto = taskService.get(selfCheckSaveVo.getTaskId());
            TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),StatusEnum.WAIT_SELF_CHECK);
            selfExaminationBillEntity = selfExaminationBillService.getOne(taskBto.getBillId());
            selfExaminationBillEntity.setCheckTime(new Date());
            selfExaminationBillEntity.setCheckDetail(selfCheckSaveVo.getCheckDetail());
            selfExaminationBillEntity.setCheckResult(selfCheckSaveVo.getCheckResult());
            selfExaminationBillEntity.setCheckStatus(0);
            selfExaminationBillEntity.setCheckedCount(selfCheckSaveVo.getCheckedCount());
            selfExaminationBillEntity.setCheckingCount(selfCheckSaveVo.getCheckingCount());
            selfExaminationBillEntity.setUserbId(selfCheckSaveVo.getUserbId());
            selfExaminationBillEntity.setHandheldTerminalInformation(selfCheckSaveVo.getHandheldTerminalInformation());
            if (selfCheckSaveVo.getUnStockDevices()!=null&&selfCheckSaveVo.getUnStockDevices().size()>0){
                selfExaminationBillEntity.setUnStockDetail(JacksonUtil.toJSon(selfCheckSaveVo.getUnStockDevices()));
            }
        }
        else {
            selfExaminationBillEntity = selfCheckSaveVo.toDo();
            selfExaminationBillEntity.setTitle(userUtils.getCurrentUserUnitName() + "发起的自查任务");
            selfExaminationBillEntity.setCheckUnit(userUtils.getCurrentUserUnitName());
            selfExaminationBillEntity.setCheckUnitId(userUtils.getCurrentUnitId());
        }
        selfExaminationBillEntity.setUseraId(userUtils.getCurrentUserId());
        selfExaminationBillEntity.setCreateUnitId(userUtils.getCurrentUnitId());
        if (selfCheckSaveVo.getNewDeviceList() != null) {
            //按新增不在系统的装备按rfid卡号拼接保存
            StringBuilder stringBuffer = new StringBuilder();
            stringBuffer.append(".");
            for (String s : selfCheckSaveVo.getNewDeviceList()) {
                stringBuffer.append(s);
                stringBuffer.append(".");
            }
            selfExaminationBillEntity.setNewDeviceDetail(stringBuffer.toString());
        }
        if(selfCheckSaveVo.getCheckFiles()!=null&&selfCheckSaveVo.getCheckFiles().size()>0) {
            selfExaminationBillEntity.setCheckFiles(FilesUtil.stringFileToList(selfCheckSaveVo.getCheckFiles()));
            selfCheckSaveVo.getCheckFiles().forEach(fileRet -> {
                fileVoList.add(new FileVo("自查单", fileRet.getName(), fileRet.getPreviewPath()));
            });
        }
        SelfCheckBill selfExaminationBillEntity1 = selfExaminationBillService.addEntity(selfExaminationBillEntity);
        Integer userId = userUtils.getCurrentUserId();
        String deviceIdDetail = selfCheckSaveVo.getCheckDetail();
        String[] strings = deviceIdDetail.split("x");
        if (selfCheckSaveVo.getTaskId()!=null){
            //获取任务
             taskBto = taskService.get(selfCheckSaveVo.getTaskId());
            if (selfCheckSaveVo.getType()==0){
                taskBto.setCustomInfo("手动");
                //添加涉及人员
                taskService.addInvolveUser(taskBto,userId);
                //推至下一阶段
                taskService.moveToNext(taskBto,selfExaminationBillEntity1.getUseraId());
            }
            else if (selfCheckSaveVo.getType()==1){
                taskBto.setCustomInfo("扫码");
                //添加涉及人员
                taskService.addInvolveUser(taskBto,userId);
                if (selfCheckSaveVo.getUserbId()!=null) {
                    taskService.moveToEnd(taskBto);
                    selfExaminationBillEntity1.setUserbId(selfCheckSaveVo.getUserbId());
                    List<Integer> idList = new ArrayList<>();
                    idList.add(selfCheckSaveVo.getUserbId());
                    //阅知
                    MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), "完成终端自查", idList, 0,0);
                    messageService.add(messageBto);
                }
                else {
                    taskService.moveToNext(taskBto,selfExaminationBillEntity1.getUseraId());
                }
                selfExaminationBillEntity1.setCheckStatus(2);
                selfExaminationBillService.update(selfExaminationBillEntity1);
            }
            else {
                throw new ApiException("type只能为0或1");
            }
        }
        else {
            //发起任务
            List<Integer> userIds = new ArrayList<>();
            userIds.add(userId);
//            if (selfExaminationBillEntity1.getUserbId()!=null){
//                userIds.add(selfExaminationBillEntity1.getUserbId());
//            }
             taskBto = new TaskBto(StatusEnum.SELF_CHECK_CONFIRM.id, userUtils.getCurrentUserUnitName() + "发起的自查任务", null, ".", selfExaminationBillEntity1.getId(), 4, userUtils.getCurrentUnitId(), 0, null, userIds);
            if (selfCheckSaveVo.getType()==0){
                taskBto.setCustomInfo("手动");
                taskService.start(taskBto);
            }
            else if (selfCheckSaveVo.getType()==1){
                taskBto.setCustomInfo("扫码");
                if (selfCheckSaveVo.getUserbId()!=null) {
                    taskBto.setBillStatus(StatusEnum.END.id);
                }
//                taskBto.setCurrentPoint(0);
                TaskBto taskBto1 = taskService.start(taskBto);
                if (selfCheckSaveVo.getUserbId()!=null) {
                    selfExaminationBillEntity1.setUserbId(selfCheckSaveVo.getUserbId());
                    List<Integer> idList = new ArrayList<>();
                    idList.add(selfCheckSaveVo.getUserbId());
                    //阅知
                    MessageBto messageBto = new MessageBto(taskBto1.getId(), taskBto1.getBusinessType(), "完成终端自查", idList, 0);
                    messageService.add(messageBto);
                }
                selfExaminationBillEntity1.setCheckStatus(2);
                selfExaminationBillService.update(selfExaminationBillEntity1);
            }
        }
        //添加装备日志
        //进行修改日志存储慢的问题
        List<DeviceLogDto> deviceLogDtos = new ArrayList<>();
        for (String s:strings) {
            if (s.length()>=2) {
                Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
//                DeviceLogDto deviceLogDto = new DeviceLogDto(id,"发起自查",fileVoList,taskBto.getId(),null);
                DeviceLogDto deviceLogDto = new DeviceLogDto(id,"发起自查",fileVoList,userId,taskBto.getId());
                deviceLogDtos.add(deviceLogDto);
//                deviceLogService.addLog(deviceLogDto);
            }
        }
        executor.execute(
                ()->{
                    deviceLogService.addAllLog(deviceLogDtos);
                }
        );
        log.info("[自查模块]:发起自查");
        myWebSocket.sendMessage1();
        return ResultUtil.success(selfExaminationBillEntity1);
    }

    @ApiOperation(value = "自查审核", notes = "可以通过这个接口自查审核")
    @PostMapping(value = "/selfExaminationConfirm")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity selfExaminationConfirm(@RequestBody @Validated SelfCheckConfirmVo selfCheckConfirmVo) {
        TaskBto taskBto = taskService.get(selfCheckConfirmVo.getTaskId());
        Integer userId = userUtils.getCurrentUserId();
        TaskDisposeUtil.isNotSubmit(taskBto.getBillStatus(),StatusEnum.SELF_CHECK_CONFIRM);
        SelfCheckBill selfExaminationBillEntity = selfExaminationBillService.getOne(taskBto.getBillId());
        if(selfCheckConfirmVo.getCheckFiles()!=null&&selfCheckConfirmVo.getCheckFiles().size()>0){
            selfExaminationBillEntity.setCheckFiles(FilesUtil.stringFileToList(selfCheckConfirmVo.getCheckFiles()));
        }
        String deviceIdDetail = selfExaminationBillEntity.getCheckDetail();
        String[] strings = deviceIdDetail.split("x");
        //审核通过，改变账单和任务状态，发起确认的任务
        if (selfCheckConfirmVo.getStatus() == 0) {
            taskService.update(taskService.moveToEnd(taskBto));
            selfExaminationBillEntity.setCheckStatus(2);
            selfExaminationBillEntity.setUserbId(selfCheckConfirmVo.getUserbId());
            selfExaminationBillService.update(selfExaminationBillEntity);
            //阅知
            List<Integer> idList = new ArrayList<>();
            idList.add(selfCheckConfirmVo.getUserbId());
            String content;
            if ("扫码".equals(taskBto.getCustomInfo())) {
                content = "完成终端自查";
            }
            else {
                content = "完成手动自查";
            }
            MessageBto messageBto = new MessageBto(taskBto.getId(), taskBto.getBusinessType(), content, idList, 0);
            messageService.add(messageBto);
            //优化日志
            List<DeviceLogDto> deviceLogDtos = new ArrayList<>();
            for (String s:strings) {
                if (s.length()>=2) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
//                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"上传自查单",null,taskBto.getId(),null);
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"上传自查单",null,userId,taskBto.getId());
//                    deviceLogService.addLog(deviceLogDto);
                    deviceLogDtos.add(deviceLogDto);
                }
            }
            //使用异步
            executor.execute(()->{
                deviceLogService.addAllLog(deviceLogDtos);
            });
            log.info("[自查模块]:审核通过自查完成");
            myWebSocket.sendMessage1();
            return ResultUtil.success("审核通过自查完成");
        }
        //审核不通过，改变账单和任务状态
        if (selfCheckConfirmVo.getStatus()==1){
            taskService.update(taskService.moveToArchive(taskBto));
            selfExaminationBillEntity.setCheckStatus(1);
            selfExaminationBillService.update(selfExaminationBillEntity);
            for (String s:strings) {
                if (s.length()>=2) {
                    Integer id = Integer.parseInt(s.substring(0, s.length() - 1));
                    DeviceLogDto deviceLogDto = new DeviceLogDto(id,"自查审核失败",null,userId,taskBto.getId());
                    deviceLogService.addLog(deviceLogDto);
                }
            }
            log.info("[自查模块]:自查审核失败");
            myWebSocket.sendMessage1();
            return ResultUtil.success("自查审核失败");
        }
        else {
            return ResultUtil.failed("status只能为0或1");
        }
    }

    @ApiOperation(value = "查询自查任务", notes = "可以通过这个接口查询自查任务")
    @PostMapping(value = "/summary")
    public ResponseEntity selectSelfExaminationBill(@RequestBody SelfCheckSelectVo selfCheckSelectVo) {
        Page<SelfCheckBill> page = selfExaminationBillService.getPage(selfCheckSelectVo, selfCheckSelectVo.getPageable());
        for (SelfCheckBill s : page.getContent()) {
            if (s.getCreateUnitId()!=null) {
                s.setCreateUnit(userPublicService.findByUnitsToname(s.getCreateUnitId()));
            }
            if (s.getUseraId()!=null) {
                String user = userPublicService.getOne(s.getUseraId()).getName();
                s.setCheckUser(user);
            }
            if (s.getUserbId()!=null) {
                String user2 = userPublicService.getOne(s.getUserbId()).getName();
                s.setConfirmUser(user2);
            }
            if (s.getCreateUserId()!=null) {
                String user3 = userPublicService.getOne(s.getCreateUserId()).getName();
                s.setCreateUser(user3);
            }
            if (s.getId()!=null){
                s.setTaskId(taskService.get(s.getId(),4).getId());
            }
        }
        return ResultUtil.success(page);
    }

    @ApiOperation(value = "查询自查任务详情", notes = "可以通过这个接口查询自查任务详情")
    @GetMapping(value = "/detail/{billId}")
    public ResponseEntity selectDetail(@PathVariable("billId") int billId) {
        Map<Integer,DeviceLibrary> deviceLibraryMap = deviceLibraryService.getAllDeviceMap();
        List<Object> list = new ArrayList<>();
        //获取业务
        TaskBto taskBto = taskService.get(billId, BusinessEnum.SELF_CHECK.id);
        //获取账单
        SelfCheckBill selfExaminationBillEntity = selfExaminationBillService.getOne(billId);
        if (selfExaminationBillEntity.getUseraId()!=null && selfExaminationBillEntity.getUseraId() != 0) {
            selfExaminationBillEntity.setCheckUser(userPublicService.getOne(selfExaminationBillEntity.getUseraId()).getName());
        }
        if (selfExaminationBillEntity.getUserbId()!=null && selfExaminationBillEntity.getUserbId() != 0) {
            selfExaminationBillEntity.setConfirmUser(userPublicService.getOne(selfExaminationBillEntity.getUserbId()).getName());
        }
        //add
        selfExaminationBillEntity.setCheckFileList(FilesUtil.stringFileToList(selfExaminationBillEntity.getCheckFiles()));
        list.add(selfExaminationBillEntity);
        //获取自查详情
        String str3 = selfExaminationBillEntity.getCheckDetail();
        String str4 = selfExaminationBillEntity.getNewDeviceDetail();
        String[] split = str3.split("x");
        //添加新增不在系统的装备
        List<DeviceLibrary> newDeviceList = new ArrayList<>();
        if (str4!=null) {
            //分隔字符获得rfid卡号
            String[] split2 = str4.split("\\.");
            newDeviceList = new ArrayList<>();
            for (String rfid:split2){
                if (rfid.length()>0){
                    DeviceLibrary d = new DeviceLibrary();
                    d.setCheckResult(2);
                    d.setSeqNumber("-");
                    d.setName("-");
                    d.setType(0);
                    d.setRfidSurfaceId("-");
                    d.setProdNumber("-");
                    d.setRfidCardId(rfid);
                    newDeviceList.add(d);
                }
            }
        }
        list.add(newDeviceList);
        List<DeviceLibrary> libraryEntities1 = new ArrayList<>();
        //添加自查装备
        for (String s:split) {
            if (s.length()>=2) {
                Integer i = Integer.parseInt(s.substring(0, s.length() - 1));
                Integer checkResult = Integer.parseInt(s.substring(s.length()-1));
                DeviceLibrary deviceLibraryEntity = deviceLibraryMap.get(i);
                deviceLibraryEntity.setCheckResult(checkResult);
                libraryEntities1.add(deviceLibraryEntity);
            }
        }
        list.add(libraryEntities1);
        //添加业务日志
        list.add(taskLogService.getByTaskId(taskBto.getId()));
        if (selfExaminationBillEntity.getUnStockDetail()!=null){
            list.add(JacksonUtil.readValue(selfExaminationBillEntity.getUnStockDetail(), new TypeReference<List<DeviceLibrary>>() {
            }));
        }
        else {
            list.add(new ArrayList<>());
        }
        list.add(taskBto.toVo());
        return ResultUtil.success(list);
    }

    @ApiOperation(value = "是否保存自查任务", notes = "可以通过这个接口查询是否保存自查任务")
    @PostMapping(value = "/isSaveSelfTask")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity isSaveSelfTask(@RequestBody SaveSelfTaskVo saveSelfTaskVo){
        //保存自查任务
        if (saveSelfTaskVo.getIsSave() == 0){
           return this.selectDetail(taskService.get(saveSelfTaskVo.getTaskId()).getBillId());
        }else {
            //删除task
            TaskBto taskBto = taskService.get(saveSelfTaskVo.getTaskId());
            //将任务进封存
            taskService.moveToArchive(taskBto);
            //将DeviceUseReport删除
            selfExaminationBillService.delete(taskBto.getBillId());
            return ResponseEntity.ok("不保存");
        }
    }
    @Autowired
    private UnitsDao unitsDao;

    @Autowired
    private SystemVariableDao systemVariableDao;
    @Autowired
    private SelfCheckBillService selfCheckBillService;


    @ApiOperation(value = "是否保存自查任务", notes = "可以通过这个接口查询是否保存自查任务")
    @GetMapping(value = "/test")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity toSave(){
        List<Units> unitsList = unitsDao.findAll();
        unitsList.forEach(units -> {
            //添加账单
            SelfCheckBill selfCheckBill = new SelfCheckBill();
            selfCheckBill.setCheckStatus(3);
            selfCheckBill.setCheckUnit(units.getName());
            selfCheckBill.setCheckUnitId(units.getUnitId());
            StringBuffer title = new StringBuffer();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH)+1;
            title.append("系统发起定时"+units.getName());
            title.append(year).append("年");
            title.append(month).append("月自查任务");
            int type=1;
//            if (' '==cron.charAt(11)) {
//                type = Integer.parseInt(cron.substring(10,11));
//            }
//            else {
//                type = Integer.parseInt(cron.substring(10,12));
//            }
            if (type==1) {
                selfCheckBill.setCycle(1);
            }
            else if (type==3){
                selfCheckBill.setCycle(2);
            }
            else if (type==12){
                selfCheckBill.setCycle(3);
            }
            else {
                selfCheckBill.setCycle(type+2);
            }
//                    if (cron.equals(cron1)){
//                        title.append(month).append("月自查任务");
//                        selfCheckBill.setCycle(1);
//                    }
//                    else if (cron.equals(cron2)){
//                        title.append(getQuarter(month)).append("自查任务");
//                        selfCheckBill.setCycle(2);
//                    }
//                    else if (cron.equals(cron3)){
//                        title.append("自查任务");
//                        selfCheckBill.setCycle(3);
//                    }
//                    else {
//                        title.append("自查任务");
//                        selfCheckBill.setCycle(0);
//                    }
            selfCheckBill.setTitle(title.toString());
            SelfCheckBill selfCheckBill1 = selfCheckBillService.addEntity(selfCheckBill);
            //发起待自查任务
            List<Integer> userIds = new ArrayList<>();
            userIds.add(0);
//                    selfCheckBill.setTitle("系统发起"+units.getName()+"自查任务");
            TaskBto taskBto = new TaskBto(StatusEnum.WAIT_SELF_CHECK.id,title.toString(),null,".",selfCheckBill1.getId(),4,units.getUnitId(),0,null,userIds);
            taskService.start(taskBto);
        });
        return ResponseEntity.ok("ok");
    }

    @ApiOperation(value = "查询时间段系统发其自查任务", notes = "可以通过这个接口查询自查任务详情")
    @PostMapping(value = "/findBySystem1")
    public void findBySystem1() {
        //通过billId和businessType 和 ownUnit
        List<Task>  allByBillAndBusinessTypeAndOwnUnit = taskService.findAllByBillAndBusinessTypeAndOwnUnit(4, userUtils.getCurrentUnitId());
        if (allByBillAndBusinessTypeAndOwnUnit.size()>0){
            for (Task task : allByBillAndBusinessTypeAndOwnUnit) {
                taskService.moveToArchive(task.parse2Bto());
                //删除
                selfCheckBillService.delete(task.getBillId());
            }
        }
    }

    @ApiOperation(value = "自查任务撤回", notes = "根据任务id撤回自查任务")
    @GetMapping("/revokeTask/taskId")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity revokeTask(Integer taskId) {
        TaskBto taskBto = taskService.get(taskId);
        SelfCheckBill selfCheckBill = selfCheckBillService.getOne(taskBto.getBillId());
        //将任推至撤回状态
        taskService.moveToRevoke(taskBto);
        selfCheckBillService.delete(selfCheckBill.getId());
//        if (selfCheckBill.getCheckDetail() != null) {
//            List<Integer> ids = StringSplitUtil.split(selfCheckBill.getCheckDetail());
//            //所有的装备
//            List<DeviceLibrary> deviceLibraryList;
//            //所有的装备日志
//            List<DeviceLogDto> deviceLogDtos = new ArrayList<>();
//            ids.forEach(id -> {
//                DeviceLibrary deviceLibrary = deviceLibraryService.getOne(id);
//                //添加装备日志
//                DeviceLogDto deviceLogDto = new DeviceLogDto(id, "对" + deviceLibrary.getName() + "自查任务撤回", null, null, null);
//                deviceLogDtos.add(deviceLogDto);
//            });
//
//            //设置装备为在库
//            deviceLibraryService.updateLifeStatus2(2,ids);
//            deviceLibraryList = deviceLibraryService.findByIds(ids);
//            //添加日志
//            deviceLogService.addAllLog(deviceLogDtos);
//
//            allotBill.setDeviceLibraries(deviceLibraryList);
//            allotBillService.delete(allotBill.getId());
//
//        }
        return ResponseEntity.ok("自查任务撤回成功");

    }

    /**
     * 查看维修退回单据
     */
    @GetMapping("getSelfCheckFileList")
    @ApiOperation("通过任务id查询自查中文件")
    public ResponseEntity getBackFileList(Integer taskId){
        return ResponseEntity.ok(selfCheckBillService.getFileList(taskId));
    }

}
