package cn.stylefeng.workflow.instance.modular.task.taskopt.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.workflow.api.entity.task.RuTask;
import cn.stylefeng.workflow.api.enums.TaskStatusEnum;
import cn.stylefeng.workflow.instance.modular.task.enums.RuTaskExceptionEnum;
import cn.stylefeng.workflow.instance.modular.task.pojo.operate.BeginHandleRequest;
import cn.stylefeng.workflow.instance.modular.task.service.RuTaskService;
import cn.stylefeng.workflow.instance.modular.task.service.TaskDaoWithEvent;
import cn.stylefeng.workflow.instance.modular.task.taskopt.TaskBeginHandleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class TaskBeginHandleServiceImpl implements TaskBeginHandleService {

    @Resource
    private RuTaskService ruTaskService;

    @Resource
    private TaskDaoWithEvent taskDaoWithEvent;

    @Override
    public void beginHandleTask(BeginHandleRequest beginHandleRequest) {

        RuTask userWaitToStartTask = this.getRuTask(beginHandleRequest.getTaskId());

        taskDaoWithEvent.updateTaskStatus(userWaitToStartTask, TaskStatusEnum.PROCESSING.getCode(), null);
    }

    private RuTask getRuTask(Long ruTaskId) {

        LambdaQueryWrapper<RuTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RuTask::getTaskId, ruTaskId);

        RuTask waitStartRuTask = this.ruTaskService.getOne(queryWrapper, false);

        if (ObjectUtil.isEmpty(waitStartRuTask)) {
            throw new ServiceException(RuTaskExceptionEnum.CANT_FIND_START_TASK);
        }

        return waitStartRuTask;
    }

}
