package com.yfd.platform.modules.basedata.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfd.platform.component.WebSocketServer;
import com.yfd.platform.component.nettyudpserver.MyMessageProtocol;
import com.yfd.platform.modules.basedata.domain.LinkageSignal;
import com.yfd.platform.modules.basedata.mapper.LinkageSignalMapper;
import com.yfd.platform.modules.basedata.service.ILinkageSignalService;
import com.yfd.platform.modules.patroltask.domain.Task;
import com.yfd.platform.modules.patroltask.domain.TaskTodo;
import com.yfd.platform.modules.patroltask.mapper.TaskTodoMapper;
import com.yfd.platform.modules.patroltask.service.ITaskService;
import com.yfd.platform.modules.patroltask.service.impl.QuartzMultiTaskManage;
import com.yfd.platform.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 联动信号关联表 服务实现类
 * </p>
 *
 *
 * @since 2023-04-06
 */
@Service
public class LinkageSignalServiceImpl extends ServiceImpl<LinkageSignalMapper, LinkageSignal> implements ILinkageSignalService {

    @Resource
    private ITaskService taskService;

    @Resource
    private QuartzMultiTaskManage quartztaskManage;

    @Resource
    private TaskTodoMapper taskTodoMapper;

    /**********************************
     * 用途说明: 接收文件
     * 参数说明 link
     * 返回值说明: void
     ***********************************/
    @Override
    public void receiveFile(MultipartFile file, String type) throws IOException, ParseException {
        Reader reader = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(reader);
        br.readLine();//br是迭代器类型的，每readline一次，行数指向next，用于过滤第0行标题
        String line;
        while ((line = br.readLine()) != null) {
            String trim = line.trim();
            if (!trim.startsWith("#")) {
                continue;
            }
            String[] split = trim.split("\\s+");
            if (split.length == 7 && "1".equals(type)) {
                saveLinkageSignal(split);
            }

            if (split.length == 7 && "2".equals(type)) {
                createTask(split[2]);
            }
        }
    }

    /**********************************
     * 用途说明: 创建联动任务并且立即执行
     * 参数说明 link
     * 返回值说明: void
     ***********************************/
    @Override
    public void createLinkTask(String message) throws ParseException {
        String trimMessage = message.trim();
        String[] split = trimMessage.split("");
        int count = 0;
        StringBuilder data = new StringBuilder();
        List<String> result = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            if (StrUtil.isBlank(s) && count < 5) {
                result.add(data.toString());
                count++;
                data = new StringBuilder();
            } else {
                data.append(s);
                if (i == (split.length - 1)) {
                    result.add(data.toString());
                }
            }
        }
        createTask(result.get(1));
    }

    /**********************************
     * 用途说明: 创建任务并且立即执行
     * 参数说明 link
     * 返回值说明: void
     ***********************************/
    private void createTask(String controlNum) throws ParseException {
        LambdaQueryWrapper<LinkageSignal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LinkageSignal::getControlNum, controlNum).eq(LinkageSignal::getDatastatus, "1");
        List<LinkageSignal> list = this.list(queryWrapper);
        if (list == null || list.size() == 0) {
            throw new RuntimeException("不存在对应的联动信号或者未绑定点位");
        }
        LinkageSignal linkageSignal = list.get(0);
        Task task = new Task();
        task.setTaskId(IdUtil.fastSimpleUUID());
        task.setStationCode(linkageSignal.getStationCode());
        task.setStationName(linkageSignal.getStationName());
        int uuid = UUID.randomUUID().toString().replaceAll("-", "").hashCode();
        uuid = uuid < 0 ? -uuid : uuid;
        task.setTaskCode(Integer.toString(uuid));
        task.setTaskName("联动任务" + uuid);
        task.setType("4");
        // 主辅设备联动
        task.setTaskType("4");
        task.setTaskTodoType("1");
        task.setPriority("4");
        task.setDeviceLevel(3);
        task.setDeviceList(linkageSignal.getDeviceIdList());
        String currentUsername = "主辅联动";
        task.setLastmodifier(currentUsername);
        task.setCreator(currentUsername);
        Timestamp timestamp = new Timestamp(DateUtil.current());
        task.setLastmodifydate(timestamp);
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
        task.setCreateTime(format);
        task.setIsenable("1");
        task.setIsReport("0");
        task.setDatastatus("2");
        task.setControlNum(linkageSignal.getControlNum());
        taskService.save(task);
        TaskTodo taskTodo = taskService.createRunNowTask(task);
        List<TaskTodo> list1 = taskTodoMapper.selectList(new LambdaQueryWrapper<TaskTodo>().
                eq(TaskTodo::getStationCode, taskTodo.getStationCode()).
                in(TaskTodo::getTaskState, "2").
                ne(TaskTodo::getTaskTodoId, taskTodo.getTaskTodoId()).orderByDesc(TaskTodo::getPlanStartTime)
        );
        for (TaskTodo taskTodo1 : list1) {
            if ("2".equals(taskTodo1.getTaskState())) {//执行中
                quartztaskManage.interruptJob(taskTodo1); //中断
                // 汤伟加的逻辑
                taskTodo1.setTaskState("3");
                taskTodo1.setCustom1("3"); //程序控制的中断执行
                taskTodoMapper.updateById(taskTodo1);
            }
        }
        String taskTodoId = taskTodo.getTaskTodoId();
        String taskType = taskTodo.getTaskType();
        JSONObject jsonObject = new JSONObject();
        jsonObject.putOnce("taskTodoId", taskTodoId);
        jsonObject.putOnce("taskType", taskType);
        WebSocketServer.sendInfo("taskresult_" + taskTodo.getStationCode(), jsonObject.toString());
        //立即执行当前任务
        quartztaskManage.runJobNow(taskTodo);
    }

    /**********************************
     * 用途说明: 新增联动信号
     * 参数说明 link
     * 返回值说明: void
     ***********************************/
    private void saveLinkageSignal(String[] link) {
        LinkageSignal linkageSignal = new LinkageSignal();
        // 序号
        linkageSignal.setOrderNum(link[0].replace("#", ""));
        // 站序号
        linkageSignal.setStationNum(link[1]);
        // 监控索引号
        String controlNum = link[2];
        linkageSignal.setControlNum(controlNum);
        // 设备名称
        linkageSignal.setLinkageDeviceName(link[3]);
        // 设备类型
        linkageSignal.setLinkageDeviceType(link[4]);
        // 实物ID
        linkageSignal.setMaterialId(link[5]);
        linkageSignal.setTime(LocalDateTime.now());
        // 是否联动信号
        linkageSignal.setIsLinkageFlag(link[6]);
        linkageSignal.setLastmodifier(SecurityUtils.getCurrentUsername());
        linkageSignal.setLastmodifydate(LocalDateTime.now());
        linkageSignal.setStationId("9b4e9d9f70b2256a69dfcbdecb13c960");
        linkageSignal.setDatastatus("0");
        LinkageSignal linkageSignal1 =
                this.getOne(new LambdaQueryWrapper<LinkageSignal>().eq(LinkageSignal::getControlNum,
                        controlNum));
        if (linkageSignal1 == null) {
            this.save(linkageSignal);
        } else {
            String id = linkageSignal1.getId();
            linkageSignal.setId(id);
            this.updateById(linkageSignal);
        }

    }


    @Override
    public boolean createLinkSiginTask(MyMessageProtocol msg) throws ParseException, InterruptedException {
        LambdaQueryWrapper<LinkageSignal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LinkageSignal::getControlNum, msg.getMonitorindex());
        List<LinkageSignal> list = this.list(queryWrapper);
        if (list == null || list.size() == 0) {
            throw new RuntimeException("不存在对应的联动信号或者未绑定点位");
        }
        LinkageSignal linkageSignal = list.get(0);
        Task task = new Task();
        String uuid = IdUtil.fastSimpleUUID();
        task.setTaskId(uuid);
        task.setStationCode(linkageSignal.getStationCode());
        task.setStationName(linkageSignal.getStationName());
        long eventtime = DateUtil.parse(msg.getEventtime(), "yyyy-MM-dd HH:mm:ss.SSS").getTime();
        task.setTaskCode(String.valueOf(msg.getMonitorindex()) + "-" + eventtime);
        String taskName = "一键顺控任务-"+DateUtil.format(new Timestamp(eventtime),"MMddHHmmss");
        if ("2".equals(linkageSignal.getLinkageType())) {
            taskName = "智能联动任务-" + DateUtil.format(new Timestamp(eventtime), "MMddHHmmss");
        }
        task.setTaskName(taskName);
        //特殊巡视
        task.setType("2");
        // 主辅设备联动
        task.setTaskType("4");
        //1立即执行
        task.setTaskTodoType("1");
        //优先级最高(4级)
        task.setPriority("4");

        task.setDeviceLevel(3);
        task.setDeviceList(linkageSignal.getDeviceIdList());
        String currentUsername = "主辅联动";
        task.setLastmodifier(currentUsername);
        task.setCreator(currentUsername);
        Timestamp timestamp = new Timestamp(DateUtil.current());
        task.setLastmodifydate(timestamp);
        task.setCreateTime(msg.getEventtime());
        task.setIsenable("1");
        task.setIsReport("0");
        task.setDatastatus("2");
        task.setCustom3(msg.getValue());
        // 修改为索引号
        task.setControlNum(String.valueOf(msg.getMonitorindex()));//代用了一键顺控的属性值
        taskService.save(task);
        TaskTodo taskTodo = taskService.createRunNowTask(task);
        List<TaskTodo> list1 = taskTodoMapper.selectList(new LambdaQueryWrapper<TaskTodo>().
                eq(TaskTodo::getStationCode, taskTodo.getStationCode()).
                in(TaskTodo::getTaskState, "2").
                ne(TaskTodo::getTaskTodoId, taskTodo.getTaskTodoId()).orderByDesc(TaskTodo::getPlanStartTime)
        );
        //立即执行当前任务
        for (TaskTodo taskTodo1 : list1) {
            if ("2".equals(taskTodo1.getTaskState())) {//执行中
                quartztaskManage.interruptJob(taskTodo1); //中断
                // 汤伟加的逻辑
                taskTodo1.setTaskState("3");
                taskTodo1.setCustom1("3"); //程序控制的中断执行
                taskTodoMapper.updateById(taskTodo1);
            }
        }
        //立即执行当前任务
        quartztaskManage.addJob(taskTodo);
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.putOnce("taskTodoId", taskTodo.getTaskTodoId());
//        jsonObject.putOnce("taskType", taskTodo.getTaskType());
//        WebSocketServer.sendInfo("taskresult_" + taskTodo.getStationCode(), jsonObject.toString());
        return true;
    }
}
