"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const functionCore = require("./functionCore.js");
require("vue");
function calculate(params) {
  const { text, marks = [], value = {}, fieldsList = [] } = params;
  if (!text) return new Error("非法公式");
  try {
    let str = text;
    let offset = 0;
    const regex = /\{(\w+)\}/g;
    let match;
    const fields = [];
    while ((match = regex.exec(text)) !== null) {
      fields.push({
        enCode: match[1],
        startIndex: match.index,
        endIndex: match.index + match[0].length
      });
    }
    for (const field of fields) {
      const { enCode, startIndex, endIndex } = field;
      let data = value[enCode];
      if (enCode.indexOf(".") > -1) {
        const [key, subKey] = enCode.split(".");
        if (value[key]) data = value[key].map((o) => o[subKey]);
      }
      const fieldItem = fieldsList.find((item) => item.fieldName == enCode);
      if (fieldItem) {
        switch (fieldItem.fieldType) {
          case "number":
            if (!data) {
              data = 0;
            } else {
              Number(data);
            }
            break;
          case "switch":
            data = false;
            if (!data) {
              data = false;
            } else if ("true" == data + "") {
              Number(data);
            } else {
              data = false;
            }
            break;
          default:
            if (!data) {
              data = "";
            }
            data = JSON.stringify(data);
        }
      } else {
        data = JSON.stringify(data);
      }
      const actualStart = startIndex + offset;
      const actualEnd = endIndex + offset;
      str = str.slice(0, actualStart) + data.toString() + str.slice(actualEnd);
      offset += data.toString().length - (endIndex - startIndex);
    }
    const result = functionCore.default.executeFunction(str);
    if (result instanceof Date) {
      const year = result.getFullYear();
      const month = String(result.getMonth() + 1).padStart(2, "0");
      const day = String(result.getDate()).padStart(2, "0");
      const hh = String(result.getHours()).padStart(2, "0");
      const mm = String(result.getMinutes()).padStart(2, "0");
      const ss = String(result.getSeconds()).padStart(2, "0");
      return `${year}/${month}/${day} ${hh}:${mm}:${ss}`;
    }
    return result;
  } catch (e) {
    const errorTypes = {
      TypeError: () => "类型错误",
      RangeError: () => "范围错误",
      SyntaxError: () => "语法错误",
      ReferenceError: () => {
        const regex = /^(\w+)\s+is\s+not\s+defined$/;
        const match = e.message.match(regex);
        return match ? `${match[1]} 未定义` : "未定义的变量";
      }
    };
    const errorType = errorTypes[e.constructor.name];
    const errorMessage = (errorType == null ? void 0 : errorType()) || `其他错误: ${e.message}`;
    return {
      error: true,
      message: errorMessage
    };
  }
}
exports.calculate = calculate;
