import qs from "qs";
import axios from "axios";
import { Toast } from "vant";
import cleanDeep from "clean-deep";
import { sessionStorage as storage } from "js-storage";
import { postMessage } from "@/helpers/native-message";
import setLoading from "@/utils/loading";
const instance = axios.create({
  baseURL: "/api-teacher",
});

instance.interceptors.request.use((config) => {
  if (config.hideLoading !== true) {
    setLoading(true);
  }
  config.data = cleanDeep(config.data);
  config.params = cleanDeep(config.params);

  if (config.method.toLocaleUpperCase() === "POST" && config.requestType === "form") {
    config.data = qs.stringify(config.data);
  }
  let Authorization = storage.get("token") || localStorage.getItem("Authorization") || localStorage.getItem("userInfo");
  Authorization = Authorization ? Authorization[0].toUpperCase() + Authorization.slice(1) : Authorization;
  if (config.baseURL !== "/api-auth" && Authorization) {
    config.headers = {
      ...config.headers,
      Authorization,
    };
  }
  const tenantId = sessionStorage.getItem("tenantId");
  if (tenantId && tenantId != "undefined") {
    config.headers["tenantId"] = tenantId;
  }
  return config;
});

instance.interceptors.response.use(
  (res) => {
    if (res.config.hideLoading !== true) {
      setLoading(false);
    }
    if (!(res.status > 200 || res.status < 200)) {
      if (res.data.code === 200) {
        return res.data;
      } else if (res.data.code == 100 || res.data.code == 201) {
        // 支付时会用到的自定交code
        return res.data;
      } else if (res.data.code == 403) {
        storage.remove("token");
        window.localStorage.removeItem("userInfo"); // 删除用户信息
        window.localStorage.removeItem("Authorization"); // 删除用户信息
        // android ios 注册方法
        postMessage({
          api: "login",
        });
        return Promise.reject(res.data);
      } else {
        if (res.config.hint !== true) {
          Toast(res.data.msg || "接口返回错误");
        }
        return Promise.reject(res.data);
      }
    } else {
      if (res.config.hint !== true) {
        Toast(res.data.msg || "接口返回错误");
      }
      return Promise.reject("网络错误");
    }
  },
  () => {
    setLoading(false);
  }
);

export default instance;
