import { checkFilterMatch } from "./parseFilterConfig.mjs";
import { defaultActionHandlers } from "./eventFlow/actionHandlers.mjs";
import "../../../../node_modules/element-plus/es/index.mjs";
import { ElMessage } from "../../../../node_modules/element-plus/es/components/message/index.mjs";
const NodeType = {
  START: "start",
  END: "end",
  EXCLUSIVE: "exclusive",
  // 独占网关
  CONDITION: "condition",
  // 条件分支
  APPROVAL: "approval"
  // 动作/审批节点
};
class EventFlowParser {
  constructor(options = {}) {
    this.options = options;
    this.eventFlow = options.eventFlow || null;
    this.fields = options.fields || [];
    this.data = options.data || {};
    this.components = options.components || {};
    this.currentNode = null;
    this.isPaused = false;
    this.pausePromise = null;
    this.pauseResolve = null;
    this.pauseReject = null;
    this.executionPath = [];
    this.context = {
      variables: {},
      // 运行时变量
      results: []
      // 每个节点的执行结果
    };
    this.metadata = options.metadata || {};
    this.actionHandlers = {
      ...defaultActionHandlers,
      ...options.customActionHandlers
      // 允许自定义动作处理器
    };
    this.bindActionHandlers();
  }
  /**
   * 启动事件流
   * @param {Object} data - 数据对象
   * @returns {Promise<Object>} 执行结果
   */
  async start(data = null) {
    if (data) {
      this.data = data;
    }
    if (!this.eventFlow) {
      throw new Error("事件流配置未设置");
    }
    this.isPaused = false;
    this.pausePromise = null;
    this.pauseResolve = null;
    this.pauseReject = null;
    this.executionPath = [];
    this.context = {
      variables: {},
      results: []
    };
    const startNode = this.eventFlow;
    if (startNode.type !== NodeType.START) {
      throw new Error("事件流缺少开始节点");
    }
    this.currentNode = startNode;
    return await this.executeCurrentNode();
  }
  /**
   * 继续执行（用于从暂停状态恢复）
   * @param {*} resumeData - 恢复时传递的数据（例如confirm的结果）
   * @returns {Promise<Object>}
   */
  async resume(resumeData = null) {
    if (!this.isPaused || !this.pauseResolve) {
      throw new Error("事件流未处于暂停状态");
    }
    this.isPaused = false;
    this.pauseResolve(resumeData);
    await this.pausePromise;
    return await this.executeCurrentNode();
  }
  /**
   * 取消执行（用于取消confirm等操作）
   * @param {*} reason - 取消原因
   */
  cancel(reason = "用户取消") {
    if (!this.isPaused || !this.pauseReject) {
      throw new Error("事件流未处于暂停状态");
    }
    this.isPaused = false;
    this.pauseReject(new Error(reason));
  }
  /**
   * 执行当前节点
   * @returns {Promise<Object>}
   */
  async executeCurrentNode() {
    if (!this.currentNode) {
      return this.getExecutionResult();
    }
    const node = this.currentNode;
    const nodeResult = {
      id: node.id,
      type: node.type,
      name: node.name,
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      success: true,
      data: null,
      error: null
    };
    try {
      let nextNode = null;
      switch (node.type) {
        case NodeType.START:
          nextNode = await this.executeStartNode(node);
          break;
        case NodeType.END:
          nextNode = await this.executeEndNode(node);
          break;
        case NodeType.EXCLUSIVE:
          nextNode = await this.executeExclusiveNode(node);
          break;
        case NodeType.CONDITION:
          nextNode = await this.executeConditionNode(node);
          break;
        case NodeType.APPROVAL:
          nextNode = await this.executeApprovalNode(node);
          break;
        default:
          throw new Error(`未知的节点类型: ${node.type}`);
      }
      nodeResult.data = this.context.variables[node.id] || null;
      this.context.results.push(nodeResult);
      const pathItem = {
        nodeId: node.id,
        nodeName: node.name,
        nodeType: node.type,
        timestamp: nodeResult.timestamp
      };
      pathItem.actionType = node.actionType;
      pathItem.actionName = node.actionName;
      pathItem.actionResult = nodeResult.data;
      this.executionPath.push(pathItem);
      if (nextNode) {
        this.currentNode = nextNode;
        return await this.executeCurrentNode();
      } else {
        return this.getExecutionResult();
      }
    } catch (error) {
      nodeResult.success = false;
      nodeResult.error = error.message;
      this.context.results.push(nodeResult);
      throw error;
    }
  }
  /**
   * 执行开始节点
   */
  async executeStartNode(node) {
    return node.next || null;
  }
  /**
   * 执行结束节点
   */
  async executeEndNode(node) {
    return null;
  }
  /**
   * 执行独占网关
   * 根据条件选择分支
   */
  async executeExclusiveNode(node) {
    if (!node.branches || node.branches.length === 0) {
      throw new Error("独占网关没有配置分支");
    }
    let matchedBranch = null;
    let defaultBranch = null;
    for (const branch of node.branches) {
      if (branch.def) {
        defaultBranch = branch;
        continue;
      }
      if (await this.checkBranchCondition(branch)) {
        matchedBranch = branch;
        break;
      }
    }
    if (!matchedBranch && defaultBranch) {
      matchedBranch = defaultBranch;
    }
    if (!matchedBranch) {
      throw new Error("没有满足条件的分支，且没有默认分支");
    }
    this.context.variables[node.id] = {
      selectedBranch: matchedBranch.id,
      branchName: matchedBranch.name
    };
    return matchedBranch.next || node.next || null;
  }
  /**
   * 检查分支条件是否满足
   */
  async checkBranchCondition(branch) {
    if (!branch.conditions) {
      return false;
    }
    if (branch.def && (!branch.conditions.conditions || branch.conditions.conditions.length === 0)) {
      return true;
    }
    return checkFilterMatch(branch.conditions, this.data, this.fields);
  }
  /**
   * 执行条件节点
   */
  async executeConditionNode(node) {
    return node.next || null;
  }
  /**
   * 执行动作/审批节点
   */
  async executeApprovalNode(node) {
    var _a, _b;
    if (!node.actionType) {
      throw new Error("动作节点没有配置动作类型");
    }
    if ((_a = node.advanced) == null ? void 0 : _a.skipCondition) {
      const shouldSkip = checkFilterMatch(
        node.advanced.skipCondition,
        this.data,
        this.fields
      );
      if (shouldSkip) {
        this.context.variables[node.id] = { skipped: true, reason: "满足跳过条件" };
        this.executionPath.push({
          nodeId: node.id,
          nodeType: node.type,
          actionType: node.actionType,
          actionName: node.actionName,
          result: {
            skipped: true,
            reason: "满足跳过条件"
          }
        });
        return node.next || null;
      }
    }
    const actionResult = await this.executeAction(node);
    if (actionResult === null) {
      return null;
    }
    this.context.variables[node.id] = {
      actionType: node.actionType,
      actionName: node.actionName,
      result: actionResult
    };
    if (actionResult.success === false) {
      const errorMessage = actionResult.message || "动作执行失败";
      console.error("[EventFlow] 动作执行失败:", errorMessage);
      if (actionResult.shouldShowError !== false) {
        ElMessage.error(errorMessage);
      }
      throw new Error(errorMessage);
    }
    if ((_b = node.advanced) == null ? void 0 : _b.blockCondition) {
      const shouldBlock = checkFilterMatch(
        node.advanced.blockCondition,
        this.data,
        this.fields
      );
      if (shouldBlock) {
        console.log("后续动作被阻止条件拦截");
        this.executionPath.push({
          nodeId: node.id,
          nodeType: node.type,
          actionType: node.actionType,
          actionName: node.actionName,
          result: {
            blocked: true,
            reason: "后续动作被阻止条件拦截"
          }
        });
        return null;
      }
    }
    return node.next || null;
  }
  /**
   * 执行动作
   */
  async executeAction(node) {
    var _a, _b, _c, _d, _e, _f;
    const handler = this.actionHandlers[node.actionType];
    if (!handler) {
      throw new Error(`未找到动作处理器: ${node.actionType}`);
    }
    const context = {
      parser: this,
      instance: (_a = this.options) == null ? void 0 : _a.instance,
      ctx: (_c = (_b = this.options) == null ? void 0 : _b.instance) == null ? void 0 : _c.proxy,
      customActions: (_d = this.options) == null ? void 0 : _d.customActions,
      localConfig: (_e = this.options) == null ? void 0 : _e.localConfig,
      components: this.components,
      metadata: (_f = this.options) == null ? void 0 : _f.metadata
    };
    return await handler(node, this.data, this.fields, context);
  }
  /**
   * 绑定动作处理器的上下文
   */
  bindActionHandlers() {
    for (const actionType in this.actionHandlers) {
      if (typeof this.actionHandlers[actionType] === "function") {
        this.actionHandlers[actionType] = this.actionHandlers[actionType].bind(this);
      }
    }
  }
  /**
   * 暂停事件流执行
   * @returns {Promise} 返回一个 Promise，在 resume 时 resolve
   */
  async pause() {
    if (this.isPaused) {
      throw new Error("事件流已经处于暂停状态");
    }
    this.isPaused = true;
    this.pausePromise = new Promise((resolve, reject) => {
      this.pauseResolve = resolve;
      this.pauseReject = reject;
    });
    return this.pausePromise;
  }
  /**
   * 获取执行结果
   */
  getExecutionResult() {
    return {
      success: true,
      completed: true,
      executionPath: this.executionPath,
      context: this.context,
      data: this.data
    };
  }
  /**
   * 获取当前节点信息
   */
  getCurrentNodeInfo() {
    if (!this.currentNode) {
      return null;
    }
    return {
      id: this.currentNode.id,
      type: this.currentNode.type,
      name: this.currentNode.name,
      isPaused: this.isPaused
    };
  }
  /**
   * 注册自定义动作处理器
   * @param {String} actionType - 动作类型
   * @param {Function} handler - 处理器函数 (node, data, fields) => Promise
   */
  registerActionHandler(actionType, handler) {
    this.actionHandlers[actionType] = handler.bind(this);
  }
  /**
   * 销毁解析器
   */
  destroy() {
    if (this.isPaused) {
      this.cancel("解析器被销毁");
    }
    this.eventFlow = null;
    this.fields = [];
    this.data = {};
    this.currentNode = null;
    this.executionPath = [];
    this.context = {
      variables: {},
      results: []
    };
    this.actionHandlers = {};
  }
}
function createEventFlowParser(options = {}) {
  return new EventFlowParser(options);
}
export {
  EventFlowParser,
  NodeType,
  createEventFlowParser,
  EventFlowParser as default
};
