import Taro from "@tarojs/taro";
import { navigateTo } from "@tarojs/taro";
import config from "../config";

//添加拦截器
let isRefreshing = true;
let addSubscriber: any[] = [];
const request = async (params, callback?: any) => {
  return new Promise(async (resolve) => {
    let { url, data, method, headers, responseType } = params;
    const BASE_URL = config.API_BASE_URL;
    let contentType = "application/json;charset=UTF-8";
    contentType = headers?.contentType || contentType;

    const option = {
      url: BASE_URL + url, //地址
      data: data, //传参
      method: method, //请求方式
      timeout: 50000, // 超时时间
      responseType,
      header: {
        //请求头
        "content-type": contentType,
        Authorization: `Bearer ${Taro.getStorageSync("Authorization")}`,
      },
    };
    Taro.showLoading({ title: "加载中", mask: true });

    // 添加调试信息
    console.log("请求配置:", option);

    const res: any = await Taro.request(option).catch((error) => {
      Taro.hideLoading();
      console.error("请求失败:", error);
      Taro.showToast({
        title: "网络请求失败",
        icon: "none",
        duration: 2000,
      });
      throw error;
    });

    Taro.hideLoading();
    if (callback) return callback(res.data);

    if (res.data.code === "0") {
      addSubscriber.push((Authorization: string) => {
        request(
          {
            ...params,
            ...{
              header: { "content-type": contentType, Authorization },
            },
          },
          resolve
        );
      });
      if (isRefreshing) {
        isRefreshing = false;
        const result: any = await Taro.request({
          url: BASE_URL + "/school/userDo/refreshToken",
          method: "GET",
          header: {
            //请求头
            "content-type": contentType,
            Authorization: `Bearer ${Taro.getStorageSync("Authorization")}`,
          },
        });

        console.log("refreshToken", result);
        if (result.data.code === 500) {
          Taro.login().then(async (response) => {
            const loginRes = await Taro.request({
              url: BASE_URL + "/school/wx/wxCallback",
              method: "GET",
              data: { code: response.code },
            });
            Taro.setStorageSync("Authorization", loginRes.data.data.token);
            Taro.setStorageSync("User", loginRes.data.data.user);
            addSubscriber.forEach((callback) => {
              callback(loginRes.data.data.token);
              401;
            });
            addSubscriber = [];
            isRefreshing = true;
          });
        } else {
          Taro.setStorageSync("Authorization", result.data.data.token);
          Taro.setStorageSync("User", result.data.data.user);
          addSubscriber.forEach((callback) => {
            callback(result.data.data.token);
          });
          addSubscriber = [];
          isRefreshing = true;
        }
      }
    } else {
      if (res.data.code === 500) {
        Taro.showModal({
          title: "提示",
          content: res.data.message,
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log("用户点击确定");
            }
          },
          confirmColor: "#4d7ced",
        });
        return;
      }
      if (res.data.code === 401) {
        navigateTo({ url: "/pages/login/index" });
      }
      resolve(res.data);
    }
  });
};

export default request;
