"use strict";
const common_vendor = require("../common/vendor.js");
const config_env = require("../config/env.js");
const loadingManager = {
  loadingCount: 0,
  loadingTimer: null,
  isShowing: false,
  // 添加状态标记
  // 安全的隐藏toast方法
  safeHideToast() {
  },
  // 显示 loading
  show(options = {}) {
    const config = {
      title: "加载中...",
      mask: true,
      delay: 300,
      ...options
    };
    if (this.loadingCount > 0) {
      this.loadingCount++;
      return;
    }
    this.loadingTimer = setTimeout(() => {
      if (this.loadingCount > 0 && !this.isShowing) {
        try {
          common_vendor.index.showLoading({
            title: config.title,
            mask: config.mask
          });
          this.isShowing = true;
        } catch (error) {
          common_vendor.index.__f__("warn", "at utils/request.js:45", "showLoading failed:", error);
        }
      }
    }, config.delay);
    this.loadingCount++;
  },
  // 隐藏 loading
  hide() {
    this.loadingCount = Math.max(0, this.loadingCount - 1);
    if (this.loadingCount === 0) {
      if (this.loadingTimer) {
        clearTimeout(this.loadingTimer);
        this.loadingTimer = null;
      }
      if (this.isShowing) {
        try {
          common_vendor.index.hideLoading();
        } catch (error) {
          common_vendor.index.__f__("warn", "at utils/request.js:69", "hideLoading failed:", error);
        } finally {
          this.isShowing = false;
        }
      }
    }
  },
  // 强制隐藏所有 loading
  forceHide() {
    this.loadingCount = 0;
    if (this.loadingTimer) {
      clearTimeout(this.loadingTimer);
      this.loadingTimer = null;
    }
    if (this.isShowing) {
      try {
        common_vendor.index.hideLoading();
      } catch (error) {
        common_vendor.index.__f__("warn", "at utils/request.js:89", "forceHide failed:", error);
      } finally {
        this.isShowing = false;
      }
    }
  },
  // 安全显示toast（确保loading已隐藏）
  safeShowToast(options) {
    if (this.isShowing) {
      this.forceHide();
      setTimeout(() => {
        common_vendor.index.showToast(options);
      }, 100);
    } else {
      common_vendor.index.showToast(options);
    }
  }
};
const request = {
  async get(url, params = {}, options = {}) {
    return this.request(url, "GET", params, options);
  },
  async post(url, data = {}, options = {}) {
    return this.request(url, "POST", data, options);
  },
  async put(url, data = {}, options = {}) {
    return this.request(url, "PUT", data, options);
  },
  async delete(url, data = {}, options = {}) {
    return this.request(url, "DELETE", data, options);
  },
  async request(url, method, data, options = {}) {
    let loadingConfig;
    if (options.loading === false) {
      loadingConfig = false;
    } else {
      loadingConfig = {
        show: true,
        title: "加载中...",
        mask: true,
        delay: 300,
        timeout: 1e4,
        ...typeof options.loading === "object" ? options.loading : {}
      };
    }
    const requestConfig = {
      timeout: 15e3,
      // 默认网络超时 15 秒
      ...options.request
    };
    const shouldShowLoading = loadingConfig !== false && loadingConfig.show !== false;
    if (shouldShowLoading) {
      loadingManager.show(loadingConfig);
    }
    const deviceInfo = common_vendor.index.getStorageSync("deviceInfo") || {};
    const devId = deviceInfo.deviceId || "";
    const sbmc = deviceInfo.model || "";
    const separator = url.includes("?") ? "&" : "?";
    const finalUrl = `${url}${separator}devId=${devId}&sbmc=${sbmc}`;
    let timeoutTimer = null;
    if (shouldShowLoading && loadingConfig.timeout) {
      timeoutTimer = setTimeout(() => {
        loadingManager.hide();
        loadingManager.safeShowToast({
          title: "请求超时",
          icon: "none"
        });
      }, loadingConfig.timeout);
    }
    let requestData = data;
    if (options.formData && data && typeof data === "object") {
      requestData = Object.keys(data).map((key) => {
        const value = data[key];
        if (Array.isArray(value)) {
          return value.map((item) => `${encodeURIComponent(key)}=${encodeURIComponent(item)}`).join("&");
        } else {
          return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
        }
      }).join("&");
    }
    return new Promise((resolve, reject) => {
      common_vendor.index.request({
        url: `${config_env.env.baseUrl}${finalUrl}`,
        method,
        data: requestData,
        timeout: requestConfig.timeout,
        // 设置网络超时
        header: (() => {
          const headers = {};
          if (options.formData) {
            headers["content-type"] = "application/x-www-form-urlencoded";
          } else {
            headers["content-type"] = "application/json";
          }
          const jsessionId = common_vendor.index.getStorageSync("JSESSIONID");
          if (jsessionId) {
            headers["Cookie"] = `JSESSIONID=${jsessionId}`;
          }
          return headers;
        })(),
        success: (res) => {
          if (timeoutTimer) {
            clearTimeout(timeoutTimer);
          }
          const headers = res.header;
          const setCookie = headers["set-cookie"] || headers["Set-Cookie"];
          if (setCookie) {
            const match = setCookie.match(/JSESSIONID=([^;]+)/);
            if (match && match[1]) {
              common_vendor.index.setStorageSync("JSESSIONID", match[1]);
            }
          }
          if (res.statusCode === 200) {
            if (res && typeof res.data === "string" && res.data.includes("页面执行时错误")) {
              reject({
                message: "服务器处理错误" + res.data
              });
              loadingManager.safeShowToast({
                title: "服务器处理错误",
                icon: "none"
              });
              return;
            }
            if (res.data && (res.data.errorcode === 1 || res.data.msg === "登录已失效，请重新登录" || res.data.message === "登录过期" || res.data.error === "UNAUTHORIZED")) {
              common_vendor.index.__f__("log", "at utils/request.js:266", "🔒 检测到登录过期，跳转自动登录");
              common_vendor.index.__f__("log", "at utils/request.js:267", "过期响应数据:", res.data);
              handleLoginExpired();
              reject({ code: 401, message: res.data.msg || "登录过期" });
              return;
            }
            const responseData = {
              data: res.data
            };
            resolve(responseData);
          } else {
            reject(res);
          }
        },
        fail: (err) => {
          if (timeoutTimer) {
            clearTimeout(timeoutTimer);
          }
          loadingManager.safeShowToast({
            title: "网络请求失败",
            icon: "none"
          });
          reject(err);
        },
        complete: () => {
          if (shouldShowLoading) {
            loadingManager.hide();
          }
        }
      });
    });
  }
};
const handleLoginExpired = async () => {
  let userInfo = common_vendor.index.getStorageSync("userInfo") || {};
  if (typeof userInfo === "string") {
    userInfo = JSON.parse(userInfo);
  }
  let yhsbToken = userInfo.yhsbToken;
  common_vendor.index.__f__("log", "at utils/request.js:318", "🔒 处理登录过期 request.js:", userInfo);
  if (yhsbToken) {
    common_vendor.index.__f__("log", "at utils/request.js:321", "🔄 有token，跳转自动登录");
    common_vendor.index.navigateTo({
      url: `/pages/common/webview?dest=autoLogin&title=自动登录&from=expired&yhsbToken=${yhsbToken}`
    });
  } else {
    common_vendor.index.__f__("log", "at utils/request.js:327", "⚠️ 无token，获取微信授权码并跳转手动登录");
    try {
      const loginRes = await common_vendor.index.login({
        provider: "weixin"
      });
      common_vendor.index.__f__("log", "at utils/request.js:335", "获取到微信授权码:", loginRes.code);
      common_vendor.index.navigateTo({
        url: `/pages/common/webview?dest=login&title=登录&from=expired&wechatCode=${loginRes.code}`
      });
    } catch (error) {
      common_vendor.index.__f__("error", "at utils/request.js:342", "获取微信授权码失败:", error);
      common_vendor.index.navigateTo({
        url: "/pages/common/webview?dest=login&title=登录&from=expired"
      });
    }
  }
};
request.loadingManager = loadingManager;
request.silent = {
  get: (url, params = {}) => request.get(url, params, { loading: false }),
  post: (url, data = {}) => request.post(url, data, { loading: false }),
  put: (url, data = {}) => request.put(url, data, { loading: false }),
  delete: (url, data = {}) => request.delete(url, data, { loading: false })
};
request.withLoading = (title) => ({
  get: (url, params = {}) => request.get(url, params, { loading: { title } }),
  post: (url, data = {}) => request.post(url, data, { loading: { title } }),
  put: (url, data = {}) => request.put(url, data, { loading: { title } }),
  delete: (url, data = {}) => request.delete(url, data, { loading: { title } })
});
exports.request = request;
//# sourceMappingURL=../../.sourcemap/mp-weixin/utils/request.js.map
