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

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.roses.kernel.rule.enums.YesOrNotEnum;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.workflow.api.entity.instance.RuntimeInstance;
import cn.stylefeng.workflow.api.entity.task.RuTask;
import cn.stylefeng.workflow.api.enums.InstanceStatusEnum;
import cn.stylefeng.workflow.api.enums.TaskStatusEnum;
import cn.stylefeng.workflow.instance.modular.manage.service.RuntimeInstanceService;
import cn.stylefeng.workflow.instance.modular.task.enums.RuTaskExceptionEnum;
import cn.stylefeng.workflow.instance.modular.task.pojo.operate.CancelRequest;
import cn.stylefeng.workflow.instance.modular.task.service.RuTaskService;
import cn.stylefeng.workflow.instance.modular.task.taskopt.TaskCancelService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TaskCancelServiceImpl implements TaskCancelService {

    @Resource
    private RuTaskService ruTaskService;

    @Resource
    private RuntimeInstanceService runtimeInstanceService;

    @Override
    public void cancel(CancelRequest cancelRequest) {

        RuntimeInstance runtimeInstance = runtimeInstanceService.getInstanceInfById(cancelRequest.getInstanceId());
        if (!runtimeInstance.getInstanceStatus().equals(InstanceStatusEnum.PROCESSING.getStatus())) {
            throw new ServiceException(RuTaskExceptionEnum.INSTANCE_STATUS_NOT_RIGHT_CNACEL);
        }

        List<RuTask> instanceIdRunningTask = ruTaskService.getInstanceIdRunningTask(cancelRequest.getInstanceId());

        if (ObjectUtil.isNotEmpty(instanceIdRunningTask)) {
            for (RuTask ruTask : instanceIdRunningTask) {
                ruTask.setTaskStatus(TaskStatusEnum.CLOSE.getCode());
                ruTask.setSuggestContent("流程被发起人撤销");
                ruTask.setReadFlag(YesOrNotEnum.Y.getCode());
            }
        }

        runtimeInstance.setInstanceStatus(InstanceStatusEnum.INVALID.getStatus());
        runtimeInstanceService.updateById(runtimeInstance);
    }

}
