// ../../node_modules/.pnpm/tsup@8.5.1_postcss@8.5.9_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js
import path from "path";
import { fileURLToPath } from "url";
var getFilename = () => fileURLToPath(import.meta.url);
var getDirname = () => path.dirname(getFilename());
var __dirname = /* @__PURE__ */ getDirname();

// src/index.ts
import path3 from "path";

// src/core/environment.ts
import { JSDOM, VirtualConsole } from "jsdom";
import * as fs from "fs";
import * as path2 from "path";
import { merge } from "lodash-es";
async function createBrowserEnvironment(options) {
  const html = options.html || `<!DOCTYPE html><html><body>
  <script>
      window.BI = window.BI || {};
      BI.fineServletURL = "/webroot/decision";
  </script>
 <div id="app"></div>
 </body></html>`;
  const virtualConsole = new VirtualConsole();
  virtualConsole.sendTo(console);
  const dom = new JSDOM(html, {
    url: options.baseUrl || "http://localhost/",
    runScripts: "dangerously",
    resources: "usable",
    virtualConsole
  });
  const { window } = dom;
  if (typeof window.HTMLCanvasElement !== "undefined") {
    window.HTMLCanvasElement.prototype.getContext = function() {
      return {
        fillRect: () => {
        },
        clearRect: () => {
        },
        getImageData: (x, y, w, h) => ({ data: new Array(w * h * 4) }),
        putImageData: () => {
        },
        createImageData: () => [],
        setTransform: () => {
        },
        drawImage: () => {
        },
        save: () => {
        },
        fillText: () => {
        },
        restore: () => {
        },
        beginPath: () => {
        },
        moveTo: () => {
        },
        lineTo: () => {
        },
        closePath: () => {
        },
        stroke: () => {
        },
        translate: () => {
        },
        scale: () => {
        },
        rotate: () => {
        },
        arc: () => {
        },
        fill: () => {
        },
        measureText: () => ({ width: 10 }),
        // 随便给个默认宽度防止后续数学运算出错
        transform: () => {
        },
        rect: () => {
        },
        clip: () => {
        }
      };
    };
  }
  ["window", "document", "navigator", "location"].forEach((prop) => {
    Object.defineProperty(global, prop, {
      value: window[prop],
      writable: true,
      configurable: true
    });
  });
  const dashboardEnv = await initDashboardDesignConfigure(options.dashboardId, options.finebiServerUrl);
  console.log(`[FineBI SDK] \u4EEA\u8868\u677F\u73AF\u5883\u53D8\u91CF\u63D0\u53D6\u5B8C\u6210\u3002`);
  window.BI = Object.assign(window.BI || {}, dashboardEnv.BI);
  const BI = global.BI = window.BI;
  BI.pool = BI.pool || {};
  BI.pool.confPool = BI.confPool || {};
  BI.pool.systemPool = BI.systemPool || {};
  if (options.scripts && options.scripts.length > 0) {
    await loadDependencies(window, options.scripts, options.finebiServerUrl);
  }
  const customPoolData = await initDashboardCustomPoolEnv(options.dashboardId, options.finebiServerUrl);
  console.log(`[FineBI SDK] \u4EEA\u8868\u677F Custom Pool \u6570\u636E\u83B7\u53D6\u5B8C\u6210\u3002`);
  BI.pool = merge(BI.pool, customPoolData);
  return {
    window,
    document: window.document,
    dom,
    options
  };
}
function getFineAuthToken() {
  const token = process.env.FINE_AUTH_TOKEN;
  if (!token) {
    throw new Error("[FineBI SDK] \u7F3A\u5C11\u73AF\u5883\u53D8\u91CF FINE_AUTH_TOKEN");
  }
  return token;
}
async function initDashboardDesignConfigure(dashboardId, serverUrl) {
  const token = getFineAuthToken();
  const url = `${serverUrl}/v5/design/report/pool/${dashboardId}/param?entryType=1&fine_auth_token=${token}`;
  const basicUrl = `${serverUrl}/v5/design/report/pool/basic?fine_auth_token=${token}`;
  console.log(`[FineBI SDK] \u6B63\u5728\u83B7\u53D6\u4EEA\u8868\u677F\u914D\u7F6E\u4FE1\u606F`);
  console.log(`[FineBI SDK] \u6B63\u5728\u83B7\u53D6\u4EEA\u8868\u677F\u57FA\u7840\u914D\u7F6E\u4FE1\u606F`);
  const [res, basicRes] = await Promise.all([fetch(url), fetch(basicUrl)]);
  if (!res.ok) {
    throw new Error(`\u8BF7\u6C42\u4EEA\u8868\u677F\u914D\u7F6E\u4FE1\u606F\u5931\u8D25: ${res.status} ${res.statusText}`);
  }
  if (!basicRes.ok) {
    throw new Error(`\u8BF7\u6C42\u4EEA\u8868\u677F\u57FA\u7840\u914D\u7F6E\u4FE1\u606F\u5931\u8D25: ${basicRes.status} ${basicRes.statusText}`);
  }
  const json = await res.json();
  const basicJson = await basicRes.json();
  const data = json.data;
  const basicData = basicJson.data;
  const parseJson = (str, key) => {
    try {
      return JSON.parse(str);
    } catch (err) {
      console.warn(`[FineBI SDK] \u89E3\u6790\u5B57\u6BB5 ${key} \u5931\u8D25\uFF0C\u5C06\u4FDD\u7559\u539F\u59CB\u5B57\u7B26\u4E32:`, err);
      return str;
    }
  };
  const parseMaybeJson = (value, key) => {
    if (typeof value !== "string") {
      return value;
    }
    return parseJson(value, key);
  };
  const biProperties = {
    basePool: parseJson(data.basePool, "basePool"),
    designConfigure: parseJson(data.designConfigure, "designConfigure"),
    reportName: parseJson(data.reportName, "reportName"),
    confPool: parseMaybeJson(basicData?.confPool, "confPool"),
    systemPool: parseMaybeJson(basicData?.systemPool, "systemPool"),
    sessionId: data.sessionId,
    subjectId: data.subjectId,
    theme: data.theme,
    title: data.title,
    lockedBy: data.lockedBy
  };
  return {
    BI: biProperties
  };
}
async function initDashboardCustomPoolEnv(dashboardId, serverUrl) {
  const token = getFineAuthToken();
  const url = `${serverUrl}/v5/design/report/pool/custom?reportId=${dashboardId}&entryType=1&fine_auth_token=${token}`;
  console.log(`[FineBI SDK] \u6B63\u5728\u83B7\u53D6\u4EEA\u8868\u677FPool`);
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error(`\u8BF7\u6C42 custom pool \u5931\u8D25: ${res.status} ${res.statusText}`);
  }
  const data = await res.json();
  return data.data;
}
async function loadDependencies(window, scripts, serverUrl) {
  console.log(`[FineBI SDK] \u5F00\u59CB\u52A0\u8F7D ${scripts.length} \u4E2A JS \u4F9D\u8D56\u6587\u4EF6...`);
  for (const scriptPath of scripts) {
    try {
      let code = "";
      const isUrl = scriptPath.startsWith("http://") || scriptPath.startsWith("https://") || scriptPath.startsWith("//");
      const isServerConfigured = serverUrl && !scriptPath.startsWith("./") && (serverUrl.startsWith("http://") || serverUrl.startsWith("https://"));
      if (isUrl) {
        const targetUrl = scriptPath.startsWith("//") ? `http:${scriptPath}` : scriptPath;
        console.log(`[FineBI SDK] \u6B63\u5728\u62C9\u53D6\u5728\u7EBF\u811A\u672C: ${targetUrl}`);
        const res = await fetch(targetUrl);
        if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
        code = await res.text();
        console.log(`[FineBI SDK] \u52A0\u8F7D\u6210\u529F: ${targetUrl}`);
      } else if (isServerConfigured) {
        const targetUrl = new URL(scriptPath, serverUrl).href;
        console.log(`[FineBI SDK] \u6B63\u5728\u62C9\u53D6\u62FC\u63A5\u811A\u672C: ${targetUrl}`);
        const res = await fetch(targetUrl);
        if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
        code = await res.text();
        console.log(`[FineBI SDK] \u52A0\u8F7D\u6210\u529F: ${targetUrl}`);
      } else {
        const basePath = "";
        const fullPath = basePath ? path2.resolve(basePath, scriptPath) : path2.resolve(scriptPath);
        console.log(`[FineBI SDK] \u6B63\u5728\u8BFB\u53D6\u672C\u5730\u811A\u672C: ${fullPath}`);
        if (fs.existsSync(fullPath)) {
          code = fs.readFileSync(fullPath, "utf-8");
          console.log(`[FineBI SDK] \u8BFB\u53D6\u6210\u529F: ${fullPath}`);
        } else {
          console.warn(`[Warning] Local script not found: ${fullPath}`);
          continue;
        }
      }
      const scriptEl = window.document.createElement("script");
      scriptEl.textContent = code;
      window.document.head.appendChild(scriptEl);
    } catch (error) {
      console.warn(`[Warning] Failed to load script ${scriptPath}:`, error);
    }
  }
  console.log(`[FineBI SDK] \u6240\u6709\u4F9D\u8D56\u52A0\u8F7D\u5E76\u6302\u8F7D\u5B8C\u6BD5\u3002`);
}

// src/api/query.ts
var QueryAPI = class {
  context;
  templateHelper;
  constructor(context, templateHelper) {
    this.context = context;
    this.templateHelper = templateHelper;
  }
  /**
   * 查询仪表板数据
   */
  async getDashboardData(options) {
    const { window } = this.context;
    if (!window.BI) {
      throw new Error("FineBI SDK (window.BI) not found in the simulated environment.");
    }
    try {
      console.log(`Querying data for dashboard: ${options.dashboardId}`);
      return { success: true, data: [] };
    } catch (error) {
      console.error("Error querying dashboard data:", error);
      throw error;
    }
  }
  /**
  * 查询仪表板组件数据
  */
  async getWidgetData(wId) {
    const { window } = this.context;
    const BI = window.BI;
    if (!window.BI) {
      throw new Error("FineBI SDK (window.BI) not found in the simulated environment.");
    }
    const templateHelper = this.templateHelper;
    const widgetHelper = templateHelper.getWidgetHelper(wId);
    const widgetBeanData = BI.Utils.getWidgetCalculationById(widgetHelper, {});
    const serverUrl = this.context.finebiServerUrl.replace(/\/$/, "");
    const reportId = templateHelper.getReportId();
    const token = process.env.FINE_AUTH_TOKEN;
    if (!token) {
      throw new Error("[FineBI SDK] \u7F3A\u5C11\u73AF\u5883\u53D8\u91CF FINE_AUTH_TOKEN");
    }
    const url = `${serverUrl}/v5/design/widget/data?reportId=${reportId}&fine_auth_token=${token}`;
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(widgetBeanData)
    });
    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`Request widget data failed: ${response.status} ${response.statusText}. ${errorText}`);
    }
    return response.json();
  }
};

// src/api/filter.ts
function isControlWidgetByWidgetType(BICst, widgetType) {
  if (widgetType == null) {
    return false;
  }
  return [
    BICst.DESIGN.WIDGET.STRING,
    BICst.DESIGN.WIDGET.STRING_LIST,
    BICst.DESIGN.WIDGET.NUMBER_DROP_DOWN,
    BICst.DESIGN.WIDGET.NUMBER,
    BICst.DESIGN.WIDGET.SINGLE_SLIDER,
    BICst.DESIGN.WIDGET.INTERVAL_SLIDER,
    BICst.DESIGN.WIDGET.DATE_INTERVAL,
    BICst.DESIGN.WIDGET.MONTH,
    BICst.DESIGN.WIDGET.QUARTER,
    BICst.DESIGN.WIDGET.TREE,
    BICst.DESIGN.WIDGET.TREE_LIST,
    BICst.DESIGN.WIDGET.TREE_LABEL,
    BICst.DESIGN.WIDGET.YEAR,
    BICst.DESIGN.WIDGET.DATE,
    BICst.DESIGN.WIDGET.DATE_PANE,
    BICst.DESIGN.WIDGET.YEAR_MONTH_INTERVAL,
    BICst.DESIGN.WIDGET.GENERAL_QUERY,
    BICst.DESIGN.WIDGET.TIME_GROUP,
    BICst.DESIGN.WIDGET.STRING_GROUP
  ].includes(widgetType);
}
var FilterAPI = class {
  context;
  templateHelper;
  constructor(context, templateHelper) {
    this.context = context;
    this.templateHelper = templateHelper;
  }
  /**
   * 应用过滤器
   */
  async applyFilter(filters) {
    const { window } = this.context;
    const BI = window.BI;
    const BICst = window.BICst;
    if (!window.BI) {
      throw new Error("FineBI SDK (window.BI) not found in the simulated environment.");
    }
    try {
      const filterArray = Array.isArray(filters) ? filters : [filters];
      const controlFilters = filterArray.filter((item) => {
        const widgetId = item.widgetId;
        const widgetHelper = widgetId ? this.templateHelper.getWidgetHelper?.(widgetId) : null;
        const widgetType = item.widgetType ?? widgetHelper?.getWidgetType?.();
        return Boolean(widgetId && isControlWidgetByWidgetType(BICst, widgetType));
      });
      const appliedWidgetIds = [];
      for (const item of controlFilters) {
        const widgetId = item.widgetId;
        if (!widgetId) {
          continue;
        }
        const helper = this.templateHelper.getWidgetHelper(widgetId);
        const widget = helper?.getWidget?.();
        if (!widget) {
          continue;
        }
        let value = item.filterValue ?? item.value;
        if (item.widgetType != null && widget.type !== item.widgetType) {
          value = null;
        } else if (widget.singleSelect === BICst.STRING_CONTROL.SINGLE && BI.isNotNull(value) && typeof value === "object") {
          const selectedValues = Array.isArray(value.value) ? value.value : [];
          if (value.type === 1 && selectedValues.length > 1 || value.type !== 1) {
            value = null;
          }
        }
        if (widget.useOptionRange && BI.isNull(value)) {
          continue;
        }
        if (widget.useCustom && BI.isNotEmptyArray(widget.customValue) && value && typeof value === "object") {
          let values = Array.isArray(value.value) ? value.value : [];
          let assist = Array.isArray(widget.customValue) ? [...widget.customValue] : [];
          let type = value.type;
          const incomingAssist = Array.isArray(value.assist) ? value.assist : [];
          if (Array.isArray(value.value) && value.value.length === 0 && widget.customValue.some((customValue) => !incomingAssist.includes(customValue))) {
            values = widget.customValue.filter((customValue) => incomingAssist.includes(customValue));
            type = 1;
          } else {
            values = values.filter((selectedValue) => widget.customValue.includes(selectedValue));
          }
          assist = assist.filter((customValue) => !values.includes(customValue));
          value = {
            ...value,
            type,
            value: values,
            assist
          };
        }
        if (widget.type === BICst.DESIGN.WIDGET.TIME_GROUP) {
          if (BI.Fix?.set) {
            BI.Fix.set(widget, "currentTimeTagId", value?.currentTimeTagId || "");
          } else {
            widget.currentTimeTagId = value?.currentTimeTagId || "";
          }
          value = value?.value ?? null;
        }
        if (BI.Fix?.set) {
          BI.Fix.set(widget, "value", value);
        } else {
          widget.value = value;
        }
        appliedWidgetIds.push(widgetId);
      }
      console.log("Applied filters:", appliedWidgetIds);
      return true;
    } catch (error) {
      console.error("Error applying filter:", error);
      throw error;
    }
  }
};

// src/api/linkage.ts
var LinkageAPI = class {
  context;
  templateHelper;
  constructor(context, templateHelper) {
    this.context = context;
    this.templateHelper = templateHelper;
  }
  setWidgetValue(target) {
    if (!target.widgetId) {
      return false;
    }
    const { window } = this.context;
    const BI = window.BI;
    const helper = this.templateHelper.getWidgetHelper?.(target.widgetId);
    const widget = helper?.getWidget?.();
    if (!widget) {
      return false;
    }
    if (target.widgetType != null && widget.type !== target.widgetType) {
      return false;
    }
    const value = target.filterValue ?? target.value ?? null;
    if (BI?.Fix?.set) {
      BI.Fix.set(widget, "value", value);
    } else {
      widget.value = value;
    }
    return true;
  }
  uniqCrossCellClickedValue(value) {
    if (!Array.isArray(value)) {
      return [];
    }
    return value.reduce((previousValue, currentValue) => {
      if (previousValue.length === 0) {
        return [currentValue];
      }
      const last = previousValue[previousValue.length - 1];
      if (last?.dId !== currentValue?.dId) {
        return [...previousValue, currentValue];
      }
      return previousValue;
    }, []);
  }
  clearDrillSequence(widgetHelper) {
    const widget = widgetHelper?.getWidget?.();
    if (!widget) {
      return;
    }
    const widgetMeasures = Array.isArray(widget.widgetMeasures) ? widget.widgetMeasures : [];
    for (const widgetMeasure of widgetMeasures) {
      const groups = Array.isArray(widgetMeasure?.group) ? widgetMeasure.group : [];
      for (const group of groups) {
        if (Array.isArray(group?.drillSequence)) {
          group.drillSequence = [];
        }
      }
    }
    widget.drillOrder = [];
  }
  /**
   * 应用联动结果到目标组件
   */
  async applyLinkage(wId, linkage) {
    const { window } = this.context;
    if (!window.BI) {
      throw new Error("FineBI SDK (window.BI) not found in the simulated environment.");
    }
    try {
      const payload = Array.isArray(linkage) ? linkage[0] : linkage;
      const BI = window.BI;
      const dId = payload?.dId;
      const value = Array.isArray(payload?.value) ? payload.value : [];
      const fieldId = payload?.fieldId;
      if (!wId) {
        return false;
      }
      const widgetHelper = this.templateHelper.getWidgetHelper?.(wId);
      const widget = widgetHelper?.getWidget?.();
      if (!widget) {
        return false;
      }
      const clicked = {
        dId,
        value: this.uniqCrossCellClickedValue(value),
        fieldId
      };
      if (BI?.Fix?.set) {
        BI.Fix.set(widget, "clicked", clicked);
      } else if (window.Fix?.set) {
        window.Fix.set(widget, "clicked", clicked);
      } else {
        widget.clicked = clicked;
      }
      const links = widgetHelper.getAllLinkageWidgets?.() || [];
      const widgets = this.templateHelper.getWidgets?.() || {};
      const currentClicked = widget.clicked;
      for (const linkWId of links) {
        this.clearDrillSequence(this.templateHelper.getWidgetHelper?.(linkWId));
        widgets[linkWId] = widgets[linkWId] || {};
        widgets[linkWId].linkage = widgets[linkWId].linkage || {};
        if (currentClicked == null || currentClicked.value == null) {
          delete widgets[linkWId].linkage[wId];
        } else {
          widgets[linkWId].linkage[wId] = {};
        }
      }
      return true;
    } catch (error) {
      console.error("Error applying linkage:", error);
      throw error;
    }
  }
  /**
   * 清除组件联动
   */
  cancelLinkage(wId) {
    const { window } = this.context;
    const BI = window.BI;
    const widgetHelper = this.templateHelper.getWidgetHelper(wId);
    const widget = widgetHelper.getWidget();
    BI.Fix.del(widget, "clicked");
    widgetHelper.updateLinkage();
  }
  /**
   * 清空联动目标值
   */
  async clearLinkage(widgetIds) {
    return true;
  }
};

// src/helper/templatehelper.ts
import { merge as merge2 } from "lodash-es";
function initTemplateHelper(context) {
  const { window } = context;
  if (!window.BI) {
    throw new Error("FineBI SDK (window.BI) not found in the simulated environment.");
  }
  const BI = window.BI;
  const { sessionId, subjectId, basePool = {}, pool = {}, designConfigure = {}, reportName = {} } = BI;
  const { confPool, systemPool } = pool;
  const { entryType, link } = basePool;
  const reportId = designConfigure.reportId;
  const reportWidgets = designConfigure.reportWidgets || [];
  designConfigure.reportWidgets = reportWidgets;
  BI.designData = merge2(
    {},
    merge2(BI.Constants.getConstant("bi.constant.design.template.conf")),
    designConfigure,
    { isEdit: false }
  );
  const templatehelperProps = {
    ...BI.designData,
    pool,
    basePool,
    entryType: 1,
    position: 0,
    subjectId
  };
  const templateHelper = new BI.TemplateHelper(templatehelperProps);
  templateHelper.syncWidgets();
  return templateHelper;
}

// src/index.ts
var FineBIQueryDataSDK = class _FineBIQueryDataSDK {
  context;
  templateHelper;
  query;
  filter;
  linkage;
  constructor(context, templateHelper) {
    this.context = context;
    this.templateHelper = templateHelper;
    this.query = new QueryAPI(this.context, this.templateHelper);
    this.filter = new FilterAPI(this.context, this.templateHelper);
    this.linkage = new LinkageAPI(this.context, this.templateHelper);
  }
  /**
   * 创建并初始化 SDK 实例
   * @param options 用于准备模拟运行环境的配置
   */
  static async create(options) {
    const env = await createBrowserEnvironment({
      scripts: [
        path3.resolve(__dirname, "../assets/fineui-base.min.js"),
        path3.resolve(__dirname, "../assets/BICst.js"),
        path3.resolve(__dirname, "../assets/i18n.js"),
        path3.resolve(__dirname, "../assets/static.min.js")
      ],
      ...options
    });
    const context = {
      window: env.window,
      document: env.document,
      dom: env.dom,
      finebiServerUrl: env.options.finebiServerUrl
    };
    const templateHelper = initTemplateHelper(context);
    console.log("FineBI Query Data SDK initialized successfully.");
    return new _FineBIQueryDataSDK(context, templateHelper);
  }
  /**
   * 销毁并释放资源
   */
  destroy() {
    this.context.window.close();
  }
};
export {
  FilterAPI,
  FineBIQueryDataSDK,
  LinkageAPI,
  QueryAPI,
  createBrowserEnvironment,
  initDashboardCustomPoolEnv,
  initDashboardDesignConfigure,
  loadDependencies
};
