import axios from "axios";

class HTTP {
  constructor() {
    this.jsessionid = uni.getStorageSync("JSESSIONID") || "";
    this.isLoad = false; // 用于是否显示登录提示
    // 创建 axios 实例
    this.instance = axios.create({
      baseURL: "/yos/rest",
      withCredentials: true
    });

    this.updateList = function (content, getList) {
      content.copyContent = JSON.parse(JSON.stringify(content));
      content.pageSize = (content.pageNumber - 1) * (content.pageSize || 20);
      content.pageNumber = 1;
      getList();
    }

    this.formatNumber = (num, decimalPlaces = 2) => {
      if (!num && num !== 0) return '';
      let [integer, decimal] = String(num.toFixed(decimalPlaces)).split('.');
      integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
      return decimal ? `${integer}.${decimal}` : integer;
    }

    this.getSpecifiedImage = function (obj, getType = false) {
      try {
        let type = getType ? "compressed" : "thumbnail";
        let imgObj = obj.subfiles.find((v) => v.type == type);
        return imgObj?.url || obj.url;
      } catch (error) {
        return obj.url;
      }
    }

    // 请求拦截器
    this.instance.interceptors.request.use((config) => {
      config.headers = config.headers || {};
      config.headers["content-type"] = "application/json";
      config.headers["accesstoken"] = uni.getStorageSync("userMsg")?.token || "";
      if (this.jsessionid) {
        config.headers["Cookie"] = `JSESSIONID=${this.jsessionid}`;
      }
      return config;
    });

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => {
        this._handleSessionCookies(response);
        this._checkSessionExpired(response);
        return response;
      },
      (error) => Promise.reject(error)
    );
  }

  /**
   * 发送请求
   */
  request({ url, data = {}, method = "POST", showLoading = "" }) {
    // 分页边界处理
    if (data.content?.pageNumber && data.content.pageTotal) {
      if (data.content.pageNumber > data.content.pageTotal) {
        return Promise.resolve({ code: 0 });
      }
    }

    if (showLoading) {
      uni.showLoading({ title: showLoading, mask: true });
    }

    return this.instance({ url, method, data })
      .then((res) => {
        let result = res.data;

        // 分页处理
        if (result.pageNumber) {
          result.firstPage = result.pageNumber === 1;
          if (data.content?.copyContent) {
            result.pageNumber = data.content.copyContent.pageNumber;
            result.pageTotal = data.content.copyContent.pageTotal;
            data.content.pageSize = data.content.copyContent.pageSize;
            delete data.content.copyContent;
          } else {
            result.pageNumber++;
          }
        }

        return result;
      })
      .catch((err) => {
        uni.showToast({ title: "网络异常，请稍后再试", icon: "none" });
        throw err;
      })
      .finally(() => {
        if (showLoading) uni.hideLoading();
      });
  }

  /**
   * 处理 JSESSIONID
   */
  _handleSessionCookies(res) {
    const setCookie = res.headers["set-cookie"] || res.headers["Set-Cookie"];
    if (setCookie) {
      const cookieArray = Array.isArray(setCookie) ? setCookie : [setCookie];
      for (const cookie of cookieArray) {
        const match = cookie.match(/JSESSIONID=([^;]+)/i);
        if (match && match[1]) {
          const newSessionId = match[1];
          if (newSessionId !== this.jsessionid) {
            this.jsessionid = newSessionId;
            uni.setStorageSync("JSESSIONID", newSessionId);
          }
          break;
        }
      }
    }
  }

  /**
   * 会话过期处理
   */
  _checkSessionExpired(res) {
    if (res.data?.msg === "登陆状态已过期，请重新登陆！") {
      this.isLoad = false;
    }
    return
    if (res.data?.msg === "登陆状态已过期，请重新登陆！") {
      this.jsessionid = "";
      uni.removeStorageSync("JSESSIONID");
      let currentPages = getCurrentPages();
      let currentPage = currentPages[currentPages.length - 1];
      if (currentPage.route !== "pages/login/login") {
        uni.showModal({
          title: "提示",
          content: "您的登录状态已过期，请重新登录。",
          showCancel: false,
          success: () => {
            uni.redirectTo({ url: "/pages/login/login" });
          }
        });
      }
    }
  }
}

export { HTTP };
