import { reactive } from "vue";
import { parseRouteParams } from "./parseRouteParams.mjs";
import "../../../../node_modules/element-plus/es/index.mjs";
/* empty css                                                          */
/* empty css                                                              */
/* empty css                                                                */
/* empty css                                                                */
import { ElLoading } from "../../../../node_modules/element-plus/es/components/loading/index.mjs";
import { ElMessage } from "../../../../node_modules/element-plus/es/components/message/index.mjs";
class DataSourceManager {
  constructor(options = {}) {
    this.templateId = options.templateId;
    this.http = options.http;
    this.params = options.params || {};
    this.initSearchData = options.initSearchData || {};
    this.dataSources = options.dataSources || [];
    this.currentDataSourceId = options.currentDataSourceId;
    this.pagination = options.pagination || false;
    this.sortRules = reactive(options.sortRules || []);
    this.originalSortRules = JSON.parse(
      JSON.stringify(options.sortRules || [])
    );
    this.showSuccessMessage = options.showSuccessMessage || false;
    this.loading = false;
    this.error = null;
    this.data = reactive({});
    this.contextData = options.data || null;
    this.fields = options.fields || [];
    this.notShowMessage = options.notShowMessage || false;
    this.events = {
      loaded: [],
      error: []
    };
    this.LoadingInstance = {
      target: null,
      // 保存Loading实例
      count: 0
    };
  }
  /**
   * 获取当前数据源配置
   */
  getCurrentDataSource() {
    if (!this.currentDataSourceId || !this.dataSources.length) return null;
    return this.dataSources.find((ds) => ds.id == this.currentDataSourceId);
  }
  /**
   * 构建请求参数
   */
  buildRequestParams(extraParams = {}) {
    const currentDs = this.getCurrentDataSource();
    if (!currentDs) return {};
    const params = { ...this.params };
    if (this.templateId) {
      params.tableId = this.templateId;
    }
    if (currentDs.params && Array.isArray(currentDs.params)) {
      const parsedParams = parseRouteParams(
        currentDs.params,
        this.contextData,
        this.fields
      );
      Object.assign(params, parsedParams);
    }
    if (this.pagination) {
      params.pageNo = this.pagination.pageNo;
      params.pageSize = this.pagination.pageSize;
    }
    if (this.sortRules && this.sortRules.length > 0) {
      params.sortRules = JSON.stringify(this.sortRules);
    }
    return { ...this.initSearchData, ...params, ...extraParams };
  }
  /**
   * 根据内容类型处理请求数据
   */
  prepareRequestData(params, contentType) {
    switch (contentType) {
      case "formData":
        const formData = new FormData();
        Object.keys(params).forEach((key) => {
          formData.append(key, params[key]);
        });
        return formData;
      case "formUrlencoded":
        const urlencoded = new URLSearchParams();
        Object.keys(params).forEach((key) => {
          urlencoded.append(key, params[key]);
        });
        return urlencoded;
      case "json":
      default:
        return JSON.stringify(params);
    }
  }
  /**
   * 获取请求配置
   */
  getRequestConfig() {
    const currentDs = this.getCurrentDataSource();
    if (!currentDs) return {};
    const config = {
      url: `/${currentDs.serverName}${currentDs.url}`,
      method: currentDs.method
    };
    if (currentDs.contentType === "formData") {
      config.headers = {
        "Content-Type": "multipart/form-data"
      };
    } else if (currentDs.contentType === "formUrlencoded") {
      config.headers = {
        "Content-Type": "application/x-www-form-urlencoded"
      };
    } else {
      config.headers = {
        "Content-Type": "application/json"
      };
    }
    return config;
  }
  /**
   * 发起请求
   */
  async fetch(extraParams = {}) {
    const currentDs = this.getCurrentDataSource();
    if (!currentDs) {
      console.warn("未找到当前数据源配置");
      return;
    }
    if (!this.http) {
      console.warn("未配置 HTTP 实例");
      return;
    }
    this.loading = true;
    this.error = null;
    this.LoadingInstance.count++;
    if (this.LoadingInstance.count === 1) {
      this.LoadingInstance.target = ElLoading.service({
        fullscreen: true,
        lock: true,
        text: "拼命加载中",
        // spinner: loadingSvg,
        background: "rgba(0, 0, 0, 0)",
        customClass: "h-loading"
      });
    }
    try {
      const params = this.buildRequestParams(extraParams);
      const requestConfig = this.getRequestConfig();
      let response;
      const { url, method } = requestConfig;
      switch (method.toLowerCase()) {
        case "get":
          response = await this.http.get(url, { params });
          break;
        case "post":
          if (this.notShowMessage) {
            response = await this.http.postNoMessage(url, params);
          } else if (currentDs.contentType === "formData") {
            response = await this.http.postForm(url, params);
          } else if (currentDs.contentType === "download") {
            await this.http.download(url, params);
          } else if (currentDs.contentType === "upload") {
            response = await this.http.upload(url, params);
          } else {
            response = await this.http.post(url, params);
          }
          break;
        case "put":
          if (currentDs.contentType === "formData") {
            response = await this.http.putForm(url, params);
          } else {
            response = await this.http.put(url, params);
          }
          break;
        case "delete":
          response = await this.http.delete(url, { params });
          break;
        default:
          response = await this.http.get(url, { params });
      }
      if (response && typeof response === "object" && "code" in response) {
        if (response.code == 0) {
          const responseData = response.data;
          const responseMessage = response.message;
          if (this.pagination) {
            this.data.list = (responseData == null ? void 0 : responseData.records) || responseData;
            this.data.total = (responseData == null ? void 0 : responseData.total) || (responseData == null ? void 0 : responseData.length);
          } else {
            this.data = responseData;
          }
          this.emit("loaded", this.data);
          if (this.showSuccessMessage && responseMessage) {
            ElMessage.success(responseMessage);
          }
          return this.data;
        } else {
          this.error = response.message || "请求失败";
          this.emit("error", this.error);
          throw new Error(this.error);
        }
      } else {
        const responseData = response;
        if (this.pagination) {
          this.data.list = (responseData == null ? void 0 : responseData.records) || responseData;
          this.data.total = (responseData == null ? void 0 : responseData.total) || (responseData == null ? void 0 : responseData.length);
        } else {
          this.data = responseData;
        }
        this.emit("loaded", this.data);
        return this.data;
      }
    } catch (err) {
      this.error = err.message || "请求失败";
      this.emit("error", err);
      throw err;
    } finally {
      this.closeLoading();
    }
  }
  /**
   * 事件监听
   */
  on(event, callback) {
    if (this.events[event]) {
      this.events[event].push(callback);
    }
  }
  /**
   * 移除事件监听
   */
  off(event, callback) {
    if (this.events[event]) {
      const index = this.events[event].indexOf(callback);
      if (index > -1) {
        this.events[event].splice(index, 1);
      }
    }
  }
  /**
   * 触发事件
   */
  emit(event, data) {
    if (this.events[event]) {
      this.events[event].forEach((callback) => {
        callback(data);
      });
    }
  }
  /**
   * 更新分页
   */
  updatePagination(pageNo, pageSize) {
    this.pagination.pageNo = pageNo;
    this.pagination.pageSize = pageSize;
  }
  /**
   * 更新排序
   */
  updateSort(field, order) {
    const existingIndex = this.sortRules.findIndex((rule) => rule.field === field);
    if (!order) {
      if (existingIndex > -1) {
        this.sortRules.splice(existingIndex, 1);
      }
    } else {
      if (existingIndex > -1) {
        this.sortRules.splice(existingIndex, 1);
      }
      this.sortRules.unshift({ field, order });
    }
  }
  /**
   * 清空排序规则 - 重置为原始配置
   */
  clearSort() {
    this.sortRules.splice(0, this.sortRules.length);
    this.originalSortRules.forEach((rule) => {
      this.sortRules.push({ ...rule });
    });
  }
  /**
   * 切换数据源
   */
  switchDataSource(dataSourceId) {
    this.currentDataSourceId = dataSourceId;
  }
  /**
   * 获取当前数据
   */
  getData() {
    return this.data;
  }
  /**
   * 获取加载状态
   */
  getLoading() {
    return this.loading;
  }
  closeLoading() {
    if (this.LoadingInstance.count > 0) {
      this.LoadingInstance.count--;
    }
    if (this.LoadingInstance.count === 0 && this.LoadingInstance.target) {
      this.LoadingInstance.target.close();
      this.LoadingInstance.target = null;
    }
  }
  /**
   * 获取错误信息
   */
  getError() {
    return this.error;
  }
  /**
   * 获取分页信息
   */
  getPagination() {
    return this.pagination;
  }
  /**
   * 获取当前请求参数
   */
  getParams() {
    return this.params;
  }
  /**
   * 更新请求参数
   */
  updateParams(newParams) {
    this.params = { ...this.params, ...newParams };
  }
  updateInitSearchData(newParams) {
    this.initSearchData = newParams;
  }
  /**
   * 清空请求参数
   */
  clearParams() {
    this.params = {};
  }
  /**
   * 销毁
   */
  destroy() {
    this.events.loaded = [];
    this.events.error = [];
  }
}
function createDataSource(options = {}) {
  return new DataSourceManager(options);
}
export {
  DataSourceManager,
  createDataSource,
  DataSourceManager as default
};
