package com.ningdatech.pmapi.todocenter.extension.cmd;

import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.compatibility.Flowable5CompatibilityHandler;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.persistence.entity.CommentEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.Flowable5Util;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.task.Comment;
import org.flowable.task.api.Task;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;

/**
 * 保存评论
 *
 * @author CMM
 * @since 2023/02/09 11:43
 */

public class SaveCommentCmd implements Command<Comment> {

    protected String taskId;
    protected String processInstanceId;
    protected String userId;
    protected String message;
    protected String type;


    public SaveCommentCmd(String taskId, String processInstanceId, String userId , String message) {
        this.taskId = taskId;
        this.processInstanceId = processInstanceId;
        this.userId = userId;
        this.message = message;
    }

    @Override
    public Comment execute(CommandContext commandContext) {
        ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
        TaskEntity task = null;
        if (this.taskId != null) {
            task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(this.taskId);
            if (task == null) {
                throw new FlowableObjectNotFoundException("Cannot find task with id " + this.taskId, Task.class);
            }

            if (task.isSuspended()) {
                throw new FlowableException(this.getSuspendedTaskException());
            }
        }

        ExecutionEntity execution = null;
        if (this.processInstanceId != null) {
            execution = (ExecutionEntity)processEngineConfiguration.getExecutionEntityManager().findById(this.processInstanceId);
            if (execution == null) {
                throw new FlowableObjectNotFoundException("execution " + this.processInstanceId + " doesn't exist", Execution.class);
            }

            if (execution.isSuspended()) {
                throw new FlowableException(this.getSuspendedExceptionMessage());
            }
        }

        String processDefinitionId = null;
        if (execution != null) {
            processDefinitionId = execution.getProcessDefinitionId();
        } else if (task != null) {
            processDefinitionId = task.getProcessDefinitionId();
        }

        if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, processDefinitionId)) {
            Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
            return compatibilityHandler.addComment(this.taskId, this.processInstanceId, this.type, this.message);
        } else {
            CommentEntity comment = (CommentEntity)processEngineConfiguration.getCommentEntityManager().create();
            comment.setUserId(userId);
            comment.setType(this.type == null ? "comment" : this.type);
            comment.setTime(processEngineConfiguration.getClock().getCurrentTime());
            comment.setTaskId(this.taskId);
            comment.setProcessInstanceId(this.processInstanceId);
            comment.setAction("AddComment");
            String eventMessage = this.message.replaceAll("\\s+", " ");
            if (eventMessage.length() > 163) {
                eventMessage = eventMessage.substring(0, 160) + "...";
            }

            comment.setMessage(eventMessage);
            comment.setFullMessage(this.message);
            processEngineConfiguration.getCommentEntityManager().insert(comment);
            return comment;
        }
    }
    protected String getSuspendedTaskException() {
        return "Cannot add a comment to a suspended task";
    }
    protected String getSuspendedExceptionMessage() {
        return "Cannot add a comment to a suspended execution";
    }
}
