package cd.casic.ci.process.process.service.task.impl;

import cd.casic.ci.process.dto.req.task.TaskUpdateReq;
import cd.casic.ci.process.dto.resp.task.TasksResp;
import cd.casic.ci.process.engine.manager.LoggerManager;
import cd.casic.ci.process.engine.manager.RunContextManager;
import cd.casic.ci.process.process.converter.TaskConverter;
import cd.casic.ci.process.process.dao.pipeline.PipTaskDao;
import cd.casic.ci.process.process.dataObject.task.PipTask;
import cd.casic.ci.process.process.service.task.TaskService;
import cd.casic.framework.commons.exception.ServiceException;
import cd.casic.framework.commons.exception.enums.GlobalErrorCodeConstants;
import cd.casic.framework.commons.pojo.CommonResult;
import cd.casic.ci.process.util.WebFrameworkUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class TaskServiceImpl extends ServiceImpl<PipTaskDao, PipTask> implements TaskService {
    @Resource
    private PipTaskDao taskDao;
    @Resource
    private RunContextManager contextManager;
    @Resource
    private LoggerManager loggerManager;
    @Resource
    private TaskConverter taskConverter;


    @Override
    public void taskTypeExist(String taskType) {

    }

    @Override
    public List<PipTask> getTask(PipTask task) {
        LambdaQueryWrapper<PipTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(task.getId()),PipTask::getId,task.getId());
        wrapper.eq(StringUtils.isNotEmpty(task.getPipelineId()),PipTask::getPipelineId,task.getPipelineId());
        wrapper.eq(StringUtils.isNotEmpty(task.getStageId()),PipTask::getStageId,task.getStageId());
        return taskDao.selectList(wrapper);
    }
    @Override
    public List<PipTask> getTaskByStageIdList(List<String> stageIdList){
        LambdaQueryWrapper<PipTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(PipTask::getStageId,stageIdList);
        return taskDao.selectList(wrapper);
    }
    @Override
    public TasksResp getRespById(String taskId){
        PipTask pipTask = new PipTask();
        pipTask.setId(taskId);
        List<PipTask> taskList = getTask(pipTask);
        if (CollectionUtils.isEmpty(taskList)) {
            return null;
        }
        return taskConverter.doToResp(taskList.get(0));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void copyTask(String taskId) {
        PipTask sourceTask = getById(taskId);
        if (sourceTask == null) {
            return;
        }
        String stageId = sourceTask.getStageId();
        PipTask query = new PipTask();
        query.setStageId(stageId);
        List<PipTask> sameLevelTaskList = getTask(query);
        if (CollectionUtils.isEmpty(sameLevelTaskList)) {
            return;
        }
        List<PipTask> updateList = new ArrayList<>(sameLevelTaskList.size());
        for (PipTask pipTask : sameLevelTaskList) {
            if (!pipTask.getId().equals(sourceTask.getId())) {
                if (pipTask.getTaskSort()>sourceTask.getTaskSort()) {
                    pipTask.setTaskSort(pipTask.getTaskSort()+1);
                    updateList.add(pipTask);
                }
            }
        }
        sourceTask.setTaskSort(sourceTask.getTaskSort()+1);
        sourceTask.setId(null);
        save(sourceTask);
        if (!CollectionUtils.isEmpty(updateList)) {
            updateBatchById(updateList);
        }
    }

    @Override
    public Boolean updateTask(TaskUpdateReq req) {
        if (StringUtils.isEmpty(req.getId())) {
            throw new ServiceException(GlobalErrorCodeConstants.PIPELINE_ERROR.getCode(),"传入id有问题");
        }
        PipTask byId = getById(req.getId());
        if (byId == null) {
            throw new ServiceException(GlobalErrorCodeConstants.PIPELINE_ERROR.getCode(),"task不存在");
        }
        String taskName = req.getTaskName();
        Map<String, Object> taskProperties = req.getTaskProperties();
        String taskType = req.getTaskType();
        byId.setTaskProperties(taskProperties);
        byId.setTaskType(taskType);
        byId.setTaskName(taskName);
        byId.setUpdater(WebFrameworkUtils.getLoginUserIdStr());
        byId.setUpdateTime(LocalDateTime.now());
        return updateById(byId);
    }

    @Override
    public CommonResult<String> getLogContentByTaskId(String taskId) {
        return CommonResult.success(loggerManager.getLogContent(taskId));
    }
}
