var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
import { generateRandomData } from "../utils/index.mjs";
import { calculate } from "./calculate.mjs";
class FormulaEditorCore {
  // 需替换的变量列表
  constructor(view, text = "", formulaObjList = []) {
    __publicField(this, "view", null);
    // EditorView 实例
    __publicField(this, "formulaObjList", []);
    // 公式对象列表
    __publicField(this, "text", "");
    // 公式文本
    __publicField(this, "marks", []);
    this.view = view;
    this.text = text;
    this.formulaObjList = formulaObjList;
  }
  // 获取公式列表
  getFormulaList() {
    return this.formulaObjList.flatMap((o) => o.formula);
  }
  // 数据回显
  renderData(formulaData) {
    if (Object.keys(formulaData).length === 0) return;
    this.text = formulaData.text || "";
    this.marks = formulaData.marks || [];
    this.view.dispatch({
      changes: { from: 0, to: this.view.state.doc.length, insert: this.text }
    });
  }
  // 校验公式
  validateFormula(fieldList) {
    const variable = fieldList.reduce((acc, cur) => {
      acc[cur.fieldName] = generateRandomData(cur.fieldType);
      return acc;
    }, {});
    const result = calculate({ ...this.getData(), value: variable });
    const calculateResult = result.toString().includes("Error: #VALUE!");
    if (calculateResult) {
      return { error: true, message: "公式计算错误，请检查公式" };
    }
    if (result.error) {
      return result;
    }
    return { error: false };
  }
  // 注册监听器
  registerListen() {
  }
  getData() {
    const text = this.view.state.doc.toString();
    return {
      text,
      marks: this.marks
    };
  }
  /**
   * 获取反显数据 - 将字段标识转换为可读的 label
   * @param {Array} fieldList - 字段列表，包含 fieldName 和 label
   * @returns {string} 反显文本
   */
  getDisplayData(fieldList) {
    const formulaData = this.getData();
    const text = formulaData.text;
    if (!text) return "";
    let displayText = text;
    const regex = /\{(\w+)\}/g;
    let match;
    while ((match = regex.exec(text)) !== null) {
      const fieldName = match[1];
      const field = fieldList.find((item) => item.fieldName === fieldName);
      const label = field ? field.label : fieldName;
      displayText = displayText.replace(match[0], `「${label}」`);
    }
    return displayText;
  }
  reset() {
    this.text = "";
    this.marks = [];
    this.view.dispatch({
      changes: { from: 0, to: this.view.state.doc.length, insert: "" }
    });
  }
  /**
   * 插入文本
   * @param {string | object} text
   * @param {'formula' | 'field'} type
   */
  insertText(data, type) {
    const cursor = this.view.state.selection.main.head;
    const text = type === "field" ? `{${data.fieldName}}` : data;
    this.view.dispatch({
      changes: { from: cursor, to: cursor, insert: text }
    });
    const currentText = this.view.state.doc.toString();
    const beforeText = currentText.slice(0, cursor);
    const afterText = currentText.slice(cursor);
    this.text = beforeText + text + afterText;
    if (type === "formula") {
      const newPos = cursor + text.length - 1;
      this.view.dispatch({
        selection: { anchor: newPos, head: newPos }
      });
    } else if (type === "field") {
      const newPos = cursor + text.length;
      this.view.dispatch({
        selection: { anchor: newPos, head: newPos }
      });
    }
    this.view.focus();
  }
  /**
   *
   * @param {'left' | 'right' | 'up' | 'down'} direction 方向
   * @param {number} step 步长
   */
  moveCursor(direction, step) {
    const cursor = this.view.state.selection.main.head;
    if (direction === "left") {
      this.view.dispatch({
        selection: { anchor: cursor - step, head: cursor - step }
      });
    } else if (direction === "right") {
      this.view.dispatch({
        selection: { anchor: cursor + step, head: cursor + step }
      });
    } else if (direction === "up") {
      const line = this.view.state.doc.lineAt(cursor);
      if (line.number > 1) {
        const prevLine = this.view.state.doc.line(line.number - 1);
        const newCursor = Math.min(cursor, prevLine.to);
        this.view.dispatch({
          selection: { anchor: newCursor, head: newCursor }
        });
      }
    } else if (direction === "down") {
      const line = this.view.state.doc.lineAt(cursor);
      const nextLine = this.view.state.doc.line(line.number + 1);
      const newCursor = Math.min(cursor, nextLine.to);
      this.view.dispatch({
        selection: { anchor: newCursor, head: newCursor }
      });
    }
  }
  // 匹配字段
  matchField(text) {
    const regex = /\{[^}]+\}/g;
    return text.match(regex) || [];
  }
  // 匹配当前行的公式
  matchWord(text) {
    const match = text.match(/[a-zA-Z]+$/);
    return match ? match[0] : "";
  }
  // 匹配当前行的公式
  matchFormula(text) {
    if (!text) return false;
    const suggestions = this.getFormulaList();
    const match = suggestions.find((o) => o.name === text);
    return match;
  }
}
export {
  FormulaEditorCore as default
};
