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

import cn.stylefeng.workflow.api.entity.task.RuTask;
import cn.stylefeng.workflow.api.enums.NodeEventTypeEnum;
import cn.stylefeng.workflow.api.enums.TaskStatusEnum;
import cn.stylefeng.workflow.api.pojo.InstanceContext;
import cn.stylefeng.workflow.event.api.EventPublishApi;
import cn.stylefeng.workflow.instance.api.WorkflowControlApi;
import cn.stylefeng.workflow.instance.api.WorkflowStatusApi;
import cn.stylefeng.workflow.instance.api.pojo.request.WorkflowChangeStatusRequest;
import cn.stylefeng.workflow.instance.api.pojo.task.RuTaskRequest;
import cn.stylefeng.workflow.instance.modular.task.pojo.operate.RejectTaskRequest;
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.TaskRejectService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class TaskRejectServiceImpl implements TaskRejectService {

    @Resource
    private RuTaskService ruTaskService;

    @Resource
    private WorkflowControlApi workflowControlApi;

    @Resource
    private EventPublishApi eventPublishApi;

    @Resource
    private WorkflowStatusApi workflowStatusApi;

    @Resource
    private TaskDaoWithEvent taskDaoWithEvent;

    @Override
    public void rejectTask(RejectTaskRequest rejectTaskRequest) {

        RuTaskRequest ruTaskRequest = new RuTaskRequest();
        ruTaskRequest.setTaskId(rejectTaskRequest.getTaskId());
        RuTask ruTask = this.ruTaskService.detail(ruTaskRequest);
        taskDaoWithEvent.updateTaskStatus(ruTask, TaskStatusEnum.REJECT.getCode(), rejectTaskRequest.getSuggestContent());

        this.ruTaskService.deleteAnyOtherTask(ruTask.getRuNodeId(), ruTask.getTaskId());

        workflowControlApi.reject(new WorkflowChangeStatusRequest(ruTask.getInstanceId()));

        InstanceContext instanceContext = workflowStatusApi.buildInstanceContext(ruTask.getInstanceId());
        eventPublishApi.publishNodeEvent(NodeEventTypeEnum.REJECT_PASSED, ruTask.getReNodeId(), instanceContext);
    }

}
