package com.tykj.dev.device.destroy.service.Impl;

import com.tykj.dev.config.base.DeviceLifeStatus;
import com.tykj.dev.device.destroy.entity.domain.DeviceDestroyBill;
import com.tykj.dev.device.destroy.entity.vo.DeviceDestroyBillVo;
import com.tykj.dev.device.destroy.service.DeviceDestroyBillService;
import com.tykj.dev.device.destroy.service.DeviceDestroyBusinessService;
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.DeviceLog;
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.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.entity.SecurityUser;
import com.tykj.dev.device.user.subject.entity.User;
import com.tykj.dev.device.user.subject.service.UserService;
import com.tykj.dev.misc.base.BusinessEnum;
import com.tykj.dev.misc.base.StatusEnum;
import com.tykj.dev.misc.utils.DeviceSeqUtil;
import com.tykj.dev.misc.utils.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName DeviceDestroyBusinessServiceImpl.java
 * @Description TODO
 * @createTime 2021年04月09日 10:57:00
 */
@Service
@Slf4j
public class DeviceDestroyBusinessServiceImpl implements DeviceDestroyBusinessService {
    @Autowired
    TaskService taskService;

    @Autowired
    DeviceDestroyBillService deviceDestroyBillService;

    @Autowired
    DeviceLibraryService deviceLibraryService;

    @Autowired
    DeviceLogService deviceLogService;

    @Autowired
    DeviceLibraryDao deviceLibraryDao;

    @Autowired
    MessageService messageService;

    @Autowired
    UserService userService;


    @Override
    public TaskBto saveDeviceDestroyBill(SecurityUser securityUser, DeviceDestroyBillVo deviceDestroyBillVo) {
        TaskBto taskBto;
        DeviceDestroyBill deviceDestroyBill= deviceDestroyBillVo.toDeviceDestroyBill();
        deviceDestroyBill.setApplyFiles(FilesUtil.stringFileToList(deviceDestroyBill.getApplyFileList()));
        deviceDestroyBill.setReplayFiles(FilesUtil.stringFileToList(deviceDestroyBill.getReplayFileList()));
        deviceDestroyBill.setScriptJson(JacksonUtil.toJSon(deviceDestroyBill.getScripts()));
        if (deviceDestroyBillVo.getTaskId()==null){
            if (deviceDestroyBillVo.getApplyId()!=null) {
                Optional<DeviceDestroyBill> deviceDestroyBill1 = deviceDestroyBillService.findApplyId(deviceDestroyBillVo.getApplyId());
                if (deviceDestroyBill1.isPresent()) {
                    deviceDestroyBill.setId(deviceDestroyBill1.get().getId());
                }
            }
            deviceDestroyBillService.saveDeviceDestroyBill(deviceDestroyBill);
            deviceDestroyBill.setNum("NO:第" + LocalDateTime.now().getYear() + "XF" + deviceDestroyBill.getId());
            taskBto= sendDraftTask(securityUser.getCurrentUserInfo().getUnitsId(),deviceDestroyBill.getId(),securityUser.getCurrentUserInfo().getUserId());
            addMessage(new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"保存销毁任务草稿",gainThisUser(securityUser.getCurrentUserInfo().getUserId(),securityUser.getCurrentUserInfo().getUnitsId())));
        }else {
            taskBto=taskService.get(deviceDestroyBillVo.getTaskId());
            DeviceDestroyBill deviceDestroyBill1= deviceDestroyBillService.findDeviceDestroyBill(taskBto.getBillId());
            deviceDestroyBill.setId(deviceDestroyBill1.getId());
            deviceDestroyBill.setNum(deviceDestroyBill1.getNum());
        }
        deviceDestroyBillService.saveDeviceDestroyBill(deviceDestroyBill);
        return taskBto;
    }

    @Override
    public DeviceDestroyBill provinceDeviceDestroyBill(SecurityUser securityUser, DeviceDestroyBillVo deviceDestroyBillVo) {
        DeviceDestroyBill deviceDestroyBill= deviceDestroyBillVo.toDeviceDestroyBill();
        deviceDestroyBill.setApplyFiles(FilesUtil.stringFileToList(deviceDestroyBill.getApplyFileList()));
        deviceDestroyBill.setReplayFiles(FilesUtil.stringFileToList(deviceDestroyBill.getReplayFileList()));
        deviceDestroyBill.setScriptJson(JacksonUtil.toJSon(deviceDestroyBill.getScripts()));
        List<String> seqNumbers= scriptListToStringList(deviceDestroyBillVo);
        if (deviceDestroyBillVo.getTaskId()==null){
            deviceDestroyBillService.saveDeviceDestroyBill(deviceDestroyBill);
            deviceDestroyBill.setNum("NO:第" + LocalDateTime.now().getYear() + "XF" + deviceDestroyBill.getId());
            TaskBto taskBto= awaitUploadDestructionTask(securityUser.getCurrentUserInfo().getUnitsId(),deviceDestroyBill.getId(),securityUser.getCurrentUserInfo().getUserId());
            addMessage(new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"销毁任务等待补充手续",gainThisUser(securityUser.getCurrentUserInfo().getUserId(),securityUser.getCurrentUserInfo().getUnitsId())));
        }else {
           TaskBto taskBto = taskService.get(deviceDestroyBillVo.getTaskId());
           DeviceDestroyBill deviceDestroyBill1=deviceDestroyBillService.findDeviceDestroyBill(taskBto.getBillId());
           deviceDestroyBill.setId(deviceDestroyBill1.getId());
           deviceDestroyBill.setNum(deviceDestroyBill1.getNum());
           taskService.moveToSpecial(taskBto,StatusEnum.DESTROY_2,0,"country");
           addMessage(new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"销毁任务等待补充手续",gainThisUser(securityUser.getCurrentUserInfo().getUserId(),securityUser.getCurrentUserInfo().getUnitsId())));

        }
        deviceLibraryDao.upDateSeqNumbersLeftStatus(DeviceLifeStatus.IN_THE_DESTROYED.id,seqNumbers);
        deviceDestroyBillService.saveDeviceDestroyBill(deviceDestroyBill);
        devLogAdd(seqNumbers,"发了销毁任务,状态转化为销毁中",securityUser.getCurrentUserInfo().getUserId());
        if (deviceDestroyBillVo.getApplyId()!=null) {
            Optional<Task> billIdAndBusinessTypeNotBillStatus = taskService.findBillIdAndBusinessTypeNotBillStatus(deviceDestroyBillVo.getApplyId(), BusinessEnum.APPLY.id);
            taskService.moveToEnd(billIdAndBusinessTypeNotBillStatus.get().parse2Bto());
        }
        return deviceDestroyBill;
    }

    @Override
    public void receiptSingle(Integer taskId,DeviceDestroyBillVo deviceDestroyBillVo,SecurityUser securityUser) {
        TaskBto taskBto= taskService.get(taskId);
        DeviceDestroyBill deviceDestroyBill= deviceDestroyBillService.findDeviceDestroyBill(taskBto.getBillId());
        List<String> seqNumbers= scriptListToStringList(deviceDestroyBillVo);
        if (deviceDestroyBillVo.getSupervisor()!=null) {
            deviceDestroyBill.setSupervisor(deviceDestroyBill.getSupervisor());
        }
        if (deviceDestroyBillVo.getLeader()!=null) {
            deviceDestroyBill.setLeader(deviceDestroyBill.getLeader());
        }
        if (deviceDestroyBillVo.getUndertaker()!=null) {
            deviceDestroyBill.setUndertaker(deviceDestroyBill.getUndertaker());
        }
        deviceDestroyBill.setDestructionFiles(FilesUtil.stringFileToList(deviceDestroyBillVo.getDestructionFileList()));
        deviceDestroyBillService.saveDeviceDestroyBill(deviceDestroyBill);
        taskService.moveToEnd(taskBto);
        deviceLibraryDao.upDateSeqNumbersLeftStatus(DeviceLifeStatus.DESTROYED.id,seqNumbers);
        addMessage(new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"销毁任务补充手续完成",gainThisUser(securityUser.getCurrentUserInfo().getUserId(),securityUser.getCurrentUserInfo().getUnitsId())));
        devLogAdd(seqNumbers,"补充单据信息，状态转化已销毁",deviceDestroyBillVo.getOperationId());

    }

    @Override
    public void moveToArchiveDestroyBill(Integer taskId) {
        TaskBto taskBto= taskService.get(taskId);
        taskService.moveToArchive(taskBto);
    }

    /**
     * 保存为草稿
     */
    private TaskBto sendDraftTask(Integer unitId, Integer repelDetailId, Integer userId){
        List<Integer> list=new ArrayList<>();
        list.add(userId);
        return taskService.start(new TaskBto(StatusEnum.DESTROY_0.id, "销毁设备任务", null, ".", repelDetailId, BusinessEnum.DESTROY.id, unitId, 0, "", list));
    }

    /**
     * 等待上传销毁单据
     * @param userId 当前用户对象
     * @param unitId 单位id
     * @param repelDetailId 业务id
     */
    private TaskBto awaitUploadDestructionTask(Integer unitId, Integer repelDetailId,Integer userId){
        List<Integer> userIds = new ArrayList<>();
        userIds.add(userId);
        userIds.add(0);
        return taskService.start(new TaskBto(StatusEnum.DESTROY_2.id, "销毁设备任务", null, ".", repelDetailId, BusinessEnum.DESTROY.id, unitId, 1, "country", userIds));
    }

    private List<String> scriptListToStringList(DeviceDestroyBillVo deviceDestroyBillVo){
        List<ScriptSaveVo> scriptSaveVos = deviceDestroyBillVo.getScripts();
        List<String> seqNumbers = new ArrayList<>();
        scriptSaveVos.forEach(
                scriptSaveVo -> {
                    if (scriptSaveVo.getSeqNumber() != null) {
                        seqNumbers.addAll(DeviceSeqUtil.selectDeviceSeqs(scriptSaveVo.getSeqNumber()));
                    }
                }
        );
        return seqNumbers;
    }

    /**
     * 异步添加装备日志
     */
    private void devLogAdd(List<String> seqNumbers, String remark, Integer userId){

        CompletableFuture.runAsync(() -> {
            List<DeviceLog> logDtos=new ArrayList<>();
            deviceLibraryDao.findAllBySeqNumberIn(seqNumbers).forEach(
                    deviceLibrary -> {
                        logDtos.add(new DeviceLogDto(deviceLibrary.getId(),remark,null,userId).toDo());
                    }
            );
            deviceLogService.saveAllLog(logDtos);
        });

    }

    private void addMessage(MessageBto messageBto){
        messageService.add(messageBto);
    }

    /**
     * 根据单位id查询用户 去除用户id
     */
    private List<Integer> gainThisUser(Integer userId,Integer unitId){
        return userService.findAllByUnite(unitId).stream().filter(user -> user.getUnitsId()!=userId).map(User::getUserId).collect(Collectors.toList());
    }

    /**
     * 根据单位id查询用户id集合
     */
    private List<Integer> findUnitId(Integer unitId){
        return userService.findAllByUnite(unitId).stream().map(User::getUserId).collect(Collectors.toList());
    }
}
