import { extend } from "umi-request";
import { showToast } from "vant";
import cleanDeep from "clean-deep";
import whiteUrl from "../constant/whiteUrl";
import { storeData } from "../store";
import { browser, getToken } from ".";
import { postMessage } from "./native-message";

const apiRouter = whiteUrl();
const browserInfo = browser();

const request = extend({
  requestType: "form",
  timeout: 30000,
});

request.interceptors.request.use(
  (url, options) => {
    const _prefix = storeData.proxy + storeData.platformApi;
    // 只有后台才去设置
    if (storeData.platformType === "WEB" && (apiRouter as any)[url]) {
      url = (apiRouter as any)[url];
    }
    const Authorization = getToken();
    const authHeaders: any = {};
    if (Authorization) {
      authHeaders.Authorization = Authorization;
    }
    return {
      url: _prefix + url,
      options: {
        ...options,
        params: options.params,
        data: options.data,
        headers: {
          ...options.headers,
          ...authHeaders,
        },
      },
    };
  },
  { global: false }
);

request.interceptors.response.use(
  async (res, options) => {
    console.log(options);
    if (res.status > 299 || res.status < 200) {
      const msg = res.statusText + ", 状态码" + res.status;
      showToast(msg);
      throw new Error(msg);
    }
    const data = await res.clone().json();
    if (data.code === 5000) {
      // 判断是否在应用中
      window.parent.postMessage(
        {
          api: "onLogin",
        },
        "*"
      );
      setTimeout(() => {
        window.location.href = `${/(192|localhost)/.test(location.origin) ? "https://test.lexiaoya.cn" : location.origin}/classroom`;
      }, 500);
      return;
    }
    if (data.code !== 200 && data.errCode !== 0) {
      const msg = data.msg || data.message || "处理失败，请重试";
      if (data.code === 5000) {
        return data;
      }
      if (!(data.code === 403 || data.code === 401)) {
        showToast(msg);
      }
      throw new Error(msg);
    }

    return data;
  },
  { global: false }
);

export default request;
