package cn.axzo.workflow.core.engine.cmd;

import cn.axzo.workflow.common.enums.BpmnCountersignTypeEnum;
import cn.axzo.workflow.common.exception.WorkflowEngineException;
import cn.axzo.workflow.common.model.request.bpmn.task.AttachmentDTO;
import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper;
import cn.axzo.workflow.core.engine.model.AddComment;
import cn.axzo.workflow.core.service.ExtAxHiTaskInstService;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.ProcessDefinitionUtil;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskInfo;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.axzo.workflow.common.code.OtherRespCode.ASSIGNEE_NODE_ID_NOT_EXISTS;
import static cn.axzo.workflow.common.constant.BpmnConstants.COUNTERSIGN_ASSIGNER_SHOW_NUMBER;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_ACTIVITY_RELATION_ASSIGNEE_LIST_INFO_SNAPSHOT;
import static cn.axzo.workflow.common.enums.BpmnProcessInstanceResultEnum.COUNTERSIGN;
import static cn.axzo.workflow.core.common.utils.BpmnMetaParserHelper.getCategoryVersion;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.batchAddAttachment;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.completeVirtualTask;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.createVirtualTask;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.getDuplicatePendingTasks;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.validTask;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.validTaskAssignerCount;

/**
 * 自定义的加签用户任务命令实现
 * <p>
 * 支持向前/向后/共享三种加签的模式
 *
 * @author wangli
 * @since 2023/12/25 14:05
 */
@Slf4j
public class CustomCountersignUserTaskCmd extends AbstractCommand<Void> implements Serializable {

    private static final long serialVersionUID = -2354973133616698898L;
    private final BpmnCountersignTypeEnum countersignType;
    private final String originTaskId;
    private final BpmnTaskDelegateAssigner originTaskAssignee;
    private final String advice;
    private final List<AttachmentDTO> attachmentList;
    private final List<BpmnTaskDelegateAssigner> targetTaskAssigneeList;
    private final ExtAxHiTaskInstService extAxHiTaskInstService;

    public CustomCountersignUserTaskCmd(BpmnCountersignTypeEnum countersignType, String originTaskId,
                                        BpmnTaskDelegateAssigner originTaskAssignee, String advice,
                                        List<AttachmentDTO> attachmentList,
                                        List<BpmnTaskDelegateAssigner> targetTaskAssigneeList, ExtAxHiTaskInstService extAxHiTaskInstService) {
        this.countersignType = countersignType;
        this.originTaskId = originTaskId;
        this.originTaskAssignee = originTaskAssignee;
        this.advice = advice;
        this.attachmentList = attachmentList;
        this.targetTaskAssigneeList = targetTaskAssigneeList;
        this.extAxHiTaskInstService = extAxHiTaskInstService;
    }

    @Override
    public String paramToJsonString() {
        Map<String, Object> params = new HashMap<>();
        params.put("countersignType", countersignType.getType());
        params.put("originTaskId", originTaskId);
        params.put("originTaskAssignee", originTaskAssignee);
        params.put("advice", advice);
        params.put("attachmentList", JSON.toJSONString(attachmentList));
        params.put("targetTaskAssigneeList", JSON.toJSONString(targetTaskAssigneeList));
        return JSON.toJSONString(params);
    }

    @Override
    public Void execute(CommandContext commandContext) {
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);
        HistoricTaskInstanceQuery taskQuery =
                processEngineConfiguration.getHistoryService().createHistoricTaskInstanceQuery();
        HistoricTaskInstance historicTaskInstance = taskQuery.taskId(originTaskId).singleResult();

        TaskService taskService = processEngineConfiguration.getTaskService();
        TaskEntity task = (TaskEntity) taskService.createTaskQuery().taskId(originTaskId).singleResult();

        validTargetAssigneeNodeId(task.getProcessDefinitionId());

        validTask(historicTaskInstance, task, originTaskAssignee, null);

        validTaskAssignerCount(processEngineConfiguration.getRuntimeService(), task, targetTaskAssigneeList);

        resolveOriginTask(commandContext, extAxHiTaskInstService, taskService, task);

        batchAddAttachment(commandContext, task.getProcessInstanceId(), task, attachmentList,
                originTaskAssignee);

        //查询重复任务
        List<Task> duplicatePendingTasks = getDuplicatePendingTasks(commandContext, task, targetTaskAssigneeList);
        List<BpmnTaskDelegateAssigner> valuTargetAssigneeList;
        if (CollectionUtils.isEmpty(duplicatePendingTasks)) {
            valuTargetAssigneeList = targetTaskAssigneeList;
        } else {
            valuTargetAssigneeList = new ArrayList<>();
            Set<String> duplicateAssigneeSet = duplicatePendingTasks.stream().map(TaskInfo::getAssignee).collect(Collectors.toSet());
            for (BpmnTaskDelegateAssigner assigner : targetTaskAssigneeList) {
                if (!duplicateAssigneeSet.contains(assigner.buildAssigneeId())) {
                    valuTargetAssigneeList.add(assigner);
                }
            }
        }
        //需要加签的
        if (!CollectionUtils.isEmpty(valuTargetAssigneeList)) {
            switch (countersignType) {
                case FORWARD_COUNTERSIGN:
                    // 加签的一种方式：前加签，具体定义由后续产品需求来定
                    break;
                case BACK_COUNTERSIGN:
                    // 加签的另一种方式
                    break;
                default:
                    // 共享签，不区分顺序
                    shareCountSign(commandContext, task, valuTargetAssigneeList);
                    break;
            }
        }
        return null;
    }

    /**
     * 共享签
     *
     * @param commandContext
     * @param taskEntity
     */
    private void shareCountSign(CommandContext commandContext, TaskEntity taskEntity, List<BpmnTaskDelegateAssigner> valuTargetAssigneeList) {
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);
        RuntimeService runtimeService = processEngineConfiguration.getRuntimeService();
        // 这个节点下所有审批人快照
        String activityListSnapshot =
                INTERNAL_ACTIVITY_RELATION_ASSIGNEE_LIST_INFO_SNAPSHOT + taskEntity.getTaskDefinitionKey();
        List<BpmnTaskDelegateAssigner> taskDelegateAssigners =
                processEngineConfiguration.getRuntimeService().getVariable(taskEntity.getProcessInstanceId(), activityListSnapshot, List.class);
        taskDelegateAssigners.addAll(valuTargetAssigneeList);
        runtimeService.setVariable(taskEntity.getProcessInstanceId(), activityListSnapshot, taskDelegateAssigners);
        log.info("正在进行加签任务:{},待加签人合并列表:{}", taskEntity.getId(), JSONUtil.toJsonStr(taskDelegateAssigners));

        valuTargetAssigneeList.forEach(assigner -> CustomTaskHelper.addMultiTask(commandContext, taskEntity, assigner));
    }

    private void resolveOriginTask(CommandContext commandContext, ExtAxHiTaskInstService extAxHiTaskInstService,
                                   TaskService taskService, TaskEntity task) {
        // 构建评论内容
        StringBuilder message = new StringBuilder("添加");
        int end = Math.min(targetTaskAssigneeList.size(), COUNTERSIGN_ASSIGNER_SHOW_NUMBER);
        //加签人员数量显示指定个数
        for (int i = 0; i < end; i++) {
            message.append(targetTaskAssigneeList.get(i).getAssignerName());
            if (i < end - 1) {
                message.append("、");
            }
        }
        if (targetTaskAssigneeList.size() > end) {
            message.append("等");
        }
        message.append(targetTaskAssigneeList.size()).append("人进行审批");
        Task virtualTask = createVirtualTask(commandContext, extAxHiTaskInstService, task.getProcessInstanceId(), task.getName(),
                task.getTaskDefinitionKey(), advice, originTaskAssignee, COUNTERSIGN.getStatus(), new AddComment(message.toString()));
        batchAddAttachment(commandContext, task.getProcessInstanceId(), task, attachmentList, originTaskAssignee);
        completeVirtualTask(commandContext, virtualTask);
    }

    private void validTargetAssigneeNodeId(String processDefinitionId) {
        BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(processDefinitionId);
        boolean present = targetTaskAssigneeList.stream().anyMatch(assigner -> !org.springframework.util.StringUtils.hasText(assigner.getNodeId()));
        Integer categoryVersion = getCategoryVersion(bpmnModel.getMainProcess()).orElse(0);
        if (categoryVersion > 0 && present) {
            throw new WorkflowEngineException(ASSIGNEE_NODE_ID_NOT_EXISTS, "审批人");
        }
    }
}
