package com.cmvr.test.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmvr.common.utils.uuid.IdUtils;
import com.cmvr.test.enums.RunModeEnum;
import com.cmvr.test.mapper.TeTaskOrchestrationMapper;
import com.cmvr.test.model.domain.TeDetectionItem;
import com.cmvr.test.model.domain.TeTaskConfigInfo;
import com.cmvr.test.model.domain.TeTaskOrchestration;
import com.cmvr.test.model.dto.TeQueryTaskDetailDTO;
import com.cmvr.test.model.vo.TeQueryTaskOrchestraItemVO;
import com.cmvr.test.model.vo.TeTaskOrchestraVO;
import com.cmvr.test.service.ITeTaskConfigInfoService;
import com.cmvr.test.service.ITeTaskOrchestrationService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.hibernate.validator.internal.util.stereotypes.Lazy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 任务编排Service业务层处理
 *
 * @author cmvr-iot
 */
@Service
public class TeTaskOrchestrationServiceImpl extends ServiceImpl<TeTaskOrchestrationMapper, TeTaskOrchestration> implements ITeTaskOrchestrationService {
    @Autowired
    @Lazy
    private ITeTaskConfigInfoService taskConfigInfoService;

    @Override
    public List<TeQueryTaskOrchestraItemVO> queryByTaskId(String taskId) {
        MPJLambdaWrapper<TeTaskOrchestration> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAs(TeTaskOrchestration::getItemId, TeQueryTaskOrchestraItemVO::getItemId)
                .select(TeTaskOrchestration::getOrderNum)
                .leftJoin(TeDetectionItem.class, TeDetectionItem::getId, TeTaskOrchestration::getItemId)
                .selectAs(TeDetectionItem::getDetectName, TeQueryTaskOrchestraItemVO::getItemName)
                .selectAs(TeDetectionItem::getConfig, TeQueryTaskOrchestraItemVO::getConfig)
                .eq(TeTaskOrchestration::getTaskId, taskId)
                .orderByAsc(TeTaskOrchestration::getOrderNum);

        return baseMapper.selectJoinList(TeQueryTaskOrchestraItemVO.class, wrapper);
    }

    /**
     * 新增任务编排
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertTeTaskOrchestration(TeTaskOrchestraVO taskOrchestraVO) {
        // 校验任务是否存在
        if (!taskConfigInfoService.isTaskExist(taskOrchestraVO.getTaskId())) {
            throw new IllegalArgumentException("ID为" + taskOrchestraVO.getTaskId() + "的任务配置不存在!");
        }

        // 先删除原有编排
        deleteByTaskId(taskOrchestraVO.getTaskId());

        List<String> itemIds = taskOrchestraVO.getItemIds();

        List<TeTaskOrchestration> list = new ArrayList<>();
        for (int i = 0; i < itemIds.size(); i++) {
            TeTaskOrchestration orchestra = new TeTaskOrchestration();
            orchestra.setTaskId(taskOrchestraVO.getTaskId());
            orchestra.setItemId(itemIds.get(i));
            orchestra.setOrderNum(i + 1);
            list.add(orchestra);
        }

        return saveBatch(list);
    }

    /**
     * 根据任务ID删除编排信息
     */
    @Override
    public void deleteByTaskId(String id) {
        LambdaQueryWrapper<TeTaskOrchestration> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TeTaskOrchestration::getTaskId, id);
        this.baseMapper.delete(wrapper);
    }

    /**
     * 根据任务IDs删除编排信息
     */
    @Override
    public void deleteByTaskIds(String[] idArr) {
        LambdaQueryWrapper<TeTaskOrchestration> wrapper = Wrappers.lambdaQuery();
        //数组转List，精准匹配Collection入参的in方法
        wrapper.in(TeTaskOrchestration::getTaskId, Arrays.asList(idArr));
        this.baseMapper.delete(wrapper);
    }

    /**
     * 查询任务详情
     */
    @Override
    public List<TeQueryTaskDetailDTO> queryTaskDetail(String taskId) {
        MPJLambdaWrapper<TeTaskOrchestration> wrapper = new MPJLambdaWrapper<>();
        wrapper
                .selectAs(TeTaskOrchestration::getItemId, TeQueryTaskDetailDTO::getDetectItemId)
                .selectAs(TeDetectionItem::getSceneCode, TeQueryTaskDetailDTO::getSceneType)
                .select(TeTaskOrchestration::getOrderNum)
                .select(TeDetectionItem::getFlowData)
                .eq(TeTaskOrchestration::getTaskId, taskId)
                .leftJoin(TeDetectionItem.class, TeDetectionItem::getId, TeTaskOrchestration::getItemId)
                .orderByAsc(TeTaskOrchestration::getOrderNum);

        return this.baseMapper.selectJoinList(TeQueryTaskDetailDTO.class, wrapper);
    }

    /**
     * 构建试运行任务
     */
    @Override
    public String buildTrialTask(String itemId) {
        // 新建试运行任务
        TeTaskConfigInfo task = new TeTaskConfigInfo();
        task.setTaskName(StrUtil.format("{}_{}",RunModeEnum.TRIAL, IdUtils.fastSimpleUUID()));
        task.setRunMode(RunModeEnum.TRIAL.name());
        taskConfigInfoService.save(task);
        // 编排单一检测项
        TeTaskOrchestration orchestration = new TeTaskOrchestration();
        orchestration.setTaskId(task.getId());
        orchestration.setItemId(itemId);
        orchestration.setOrderNum(1);
        this.save(orchestration);
        return task.getId();
    }
}
