package com.cmvr.test.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmvr.common.utils.StringUtils;
import com.cmvr.test.enums.RunModeEnum;
import com.cmvr.test.enums.TaskStatusEnum;
import com.cmvr.test.mapper.TeTaskInstMapper;
import com.cmvr.test.model.domain.TeTaskConfigInfo;
import com.cmvr.test.model.domain.TeTaskInst;
import com.cmvr.test.model.vo.TeQueryTaskInstVO;
import com.cmvr.test.model.vo.TeTaskInstVO;
import com.cmvr.test.service.ITeTaskInstService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 任务实例Service业务层处理
 *
 * @author cmvr-iot
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TeTaskInstServiceImpl extends ServiceImpl<TeTaskInstMapper, TeTaskInst> implements ITeTaskInstService {

    /**
     * 查询任务实例列表
     */
    @Override
    public List<TeTaskInstVO> selectTeTaskInstList(TeQueryTaskInstVO queryTaskInstVO) {
        MPJLambdaWrapper<TeTaskInst> queryWrapper = new MPJLambdaWrapper<>();

        queryWrapper.selectAll(TeTaskInst.class)
                .select(TeTaskConfigInfo::getTaskName)
                .selectAs(TeTaskInst::getTaskId, TeQueryTaskInstVO::getTaskId)
                .leftJoin(TeTaskConfigInfo.class, TeTaskConfigInfo::getId, TeTaskInst::getTaskId)
                .eq(TeTaskInst::getRunMode, RunModeEnum.NORMAL)
                .eq(StringUtils.isNotBlank(queryTaskInstVO.getStatus()), TeTaskInst::getStatus, queryTaskInstVO.getStatus())
                .like(StringUtils.isNotBlank(queryTaskInstVO.getTaskName()), TeTaskConfigInfo::getTaskName, queryTaskInstVO.getTaskName())
                .ge(StringUtils.isNotBlank(queryTaskInstVO.getStartTime()), TeTaskInst::getCreateTime, queryTaskInstVO.getStartTime())
                .le(StringUtils.isNotBlank(queryTaskInstVO.getEndTime()), TeTaskInst::getCreateTime, queryTaskInstVO.getEndTime())
                .orderByDesc(TeTaskInst::getCreateTime);

        // 执行查询并返回结果
        return this.baseMapper.selectJoinList(TeTaskInstVO.class, queryWrapper);
    }

/*
    @Override
    public void pauseTask(String instId) {
        // todo 调用 edge 暂停接口

        TaskContext ctx = taskInstHolder.getContext(instId);
        if (ctx == null || ctx.isStopped()) {
            throw new GlobalException("任务不存在或已终止，无法暂停");
        }
        if (ctx.isPaused()) {
            throw new GlobalException("任务已处于暂停状态");
        }

        List<FlowNodePath> nodePaths = ctx.getActiveNodeInfo();
        if (CollUtil.isEmpty(nodePaths)) {
            throw new GlobalException("当前任务节点路径信息缺失，无法暂停");
        }

        FlowNodePath flowNodePath = nodePaths.get(0);

        // 调用 Node-RED 停止当前流程
        String stopUrl = StrUtil.format(nodeRedProperties.getStopProcess(), flowNodePath.getCurrentNodeId());
        CallAPIUtil.doPostJson(stopUrl, null, null);

        // 统一记录日志 + 设置上下文状态 + 数据库状态
        taskInstHolder.markPaused(instId, ctx.getTaskId(), ctx.getItemId());
    }

    @Override
    public void stopTask(String instId) {
        // todo调用edge

        TaskContext ctx = taskInstHolder.getContext(instId);
        if (ctx == null) {
            throw new GlobalException("任务不存在");
        }
        if (ctx.isStopped()) {
            throw new GlobalException("任务已终止，无需重复操作");
        }

        List<FlowNodePath> nodePaths = ctx.getActiveNodeInfo();
        if (CollUtil.isEmpty(nodePaths)) {
            throw new GlobalException("当前任务节点路径信息缺失，无法终止");
        }

        FlowNodePath flowNodePath = nodePaths.get(0);

        // 调用 Node-RED 停止当前流程
        String stopUrl = StrUtil.format(nodeRedProperties.getStopProcess(), flowNodePath.getCurrentNodeId());
        CallAPIUtil.doPostJson(stopUrl, null, null);

        // 统一记录日志 + 设置上下文状态 + 数据库状态
        taskInstHolder.markStopped(instId, ctx.getTaskId(), ctx.getItemId());
    }

    @Override
    public void resumeTask(String instId) {
        TaskContext ctx = taskInstHolder.getContext(instId);
        if (ctx == null) {
            throw new GlobalException("任务不存在");
        }
        if (!ctx.isPaused()) {
            throw new GlobalException("当前任务未处于暂停状态，无法继续运行");
        }

        List<FlowNodePath> nodePaths = ctx.getActiveNodeInfo();
        if (CollUtil.isEmpty(nodePaths)) {
            throw new GlobalException("当前任务节点路径信息缺失，无法暂停");
        }

        // 先处理统一状态
        // 统一记录日志 + 设置上下文状态 + 数据库状态
        taskInstHolder.markResumed(instId, ctx.getTaskId(), ctx.getItemId());

        // 循环调用 Node-RED 的 resume 接口
        for (FlowNodePath nodePath : nodePaths) {
            String resumeUrl = StrUtil.format(nodeRedProperties.getStartProcess(), nodePath.getCurrentNodeId());
            TeTaskRunMessageVO msg = new TeTaskRunMessageVO();
            msg.setInstId(instId);
            msg.setTaskId(ctx.getTaskId());
            msg.setItemId(ctx.getItemId());
            msg.setTerminalId(ctx.getTerminalId());
            msg.setNodeId(nodePath.getCurrentNodeId());
            msg.setNodeType(nodePath.getCurrentNodeType());
            msg.setParams(JSONObject.parseObject(nodePath.getCurrentParams()));
            msg.setStatus(TaskStatusEnum.RUNNING.name());
            CallAPIUtil.doPostJson(resumeUrl, null, msg);
        }

    }

    @Override
    public TaskContext getTaskContext(String instId) {
        return taskInstHolder.getContext(instId);
    }
*/

    @Override
    public boolean updateStatus(String instId, TaskStatusEnum taskStatusEnum) {
        return this.update(
                new LambdaUpdateWrapper<TeTaskInst>()
                        .eq(TeTaskInst::getId, instId)
                        .set(TeTaskInst::getStatus, taskStatusEnum.getCode())
        );
    }
}
