import axios from "axios";
import Taro from "@tarojs/taro";
import { Toast } from "@nutui/nutui-react-taro";

const request = axios.create({
  baseURL: process.env.TARO_API_DOMAIN,
});

// 创建全局的axios实例，并安装请求拦截器
request.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    const saToken = Taro.getStorageSync("saToken");
    if (saToken) {
      config.headers.saToken = saToken;
    }

    const slug = Taro.getStorageSync("userRoleVO")?.slug;
    if (slug) {
      config.headers["Xh-Role-Slug"] = slug;
    }

    config.headers["Xh-Platform-Id"] = "1991353387274342401";

    return config;
  },
  (error) => {
    // 处理请求错误
    return Promise.reject(error);
  },
);

// 在获取到响应后，安装响应拦截器
request.interceptors.response.use(
  async (response) => {
    console.log("response", response);
    const {
      data: { success, data },
    } = response;
    // 处理响应成功的情况
    if (success) {
      const saToken = data?.meta?.accessToken;
      if (saToken) {
        Taro.setStorageSync("saToken", saToken);
        Taro.setStorageSync("user", data.userVO);
        let platformId = "1991353387274342401";
        Taro.setStorageSync(
          "userRoleVO",
          data.userRoleVOList?.find((item) => item.platformId === platformId),
        );
      }
    } else {
      // 异常处理
      if (response.data.errCode === "403") {
        Toast.show("toast", {
          icon: "fail",
          title: "暂无权限",
          content: response.data.errMessage,
        });
      }

      // 如果是401则重新登录，然后重新发起请求
      if (response.data.errCode === "401") {
        // 移除缓存
        Taro.removeStorageSync("saToken");
        Taro.removeStorageSync("user");
        Taro.removeStorageSync("userRoleVO");
        // const { code } = await Taro.login();
        // const data = await wxMaLogin(code);
        // if (data) {
        //   response.config.headers.saToken = `${Taro.getStorageSync("saToken")}`;
        //   return request(response.config);
        // }
        // 跳转到登录页面
        Taro.navigateTo({
          url: "/pages/public/login/index",
        });
        return response;
      }

      console.log("response.data.errCode", response.data.errCode);
      if (response.data.errCode === "400") {
        Toast.show("toast", {
          icon: "fail",
          title: "请求失败",
          content: response.data.errMessage,
        });
      }

      if (response.data.errCode === "500") {
        Toast.show("toast", {
          icon: "fail",
          title: "服务器错误",
          content: response.data.errMessage,
        });
      } else {
        Toast.show("toast", {
          icon: "fail",
          title: "请求失败",
          content: response.data.errMessage,
        });
      }
    }

    return response;
  },
  (error) => {
    // 处理响应错误的情况
    if (!error.response) {
      // 网络错误，断网情况
      Toast.show("toast", {
        icon: "fail",
        title: "网络连接失败",
        content: "请检查您的网络设置",
      });
    }
    return Promise.reject(error);
  },
);

export default request;
