import { extend } from 'umi-request';
import cleanDeep from 'clean-deep';
import { browser } from '@/helpers/utils';
import { setLogout, setLoginError } from '@/state';
import { postMessage } from './native-message';
import { showLoadingToast, showToast, closeToast } from 'vant';
import { storage } from '@/helpers/storage';
import { ACCESS_TOKEN } from '@/store/mutation-types';

export interface SearchInitParams {
  rows?: string | number;
  page?: string | number;
}

const request = extend({
  // requestType: 'form',
  noAuthorization: false, // 默认添加token，在有的情况下
  hideLoading: true, // 默认都不显示加载
  timeout: 20000,
  timeoutMessage: '请求超时'
});

// 是否是初始化接口
let initRequest = false;
let isPc = false;
let toast: ReturnType<typeof setTimeout>;
let toastMsg: ReturnType<typeof setTimeout>;

request.interceptors.request.use(
  (url, options: any) => {
    if (!options.hideLoading) {
      clearTimeout(toast);
      showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      });
    }

    initRequest = options.initRequest || false;
    isPc = options.isPc || false;
    const Authorization = storage.get(ACCESS_TOKEN) || '';
    const authHeaders: any = {};

    if (
      Authorization &&
      ![
        '/edu-app/userlogin',
        '/edu-app/smsLogin',
        '/edu-app/open/sendSms'
      ].includes(url) &&
      !options.noAuthorization
    ) {
      authHeaders.Authorization = Authorization;
    }

    return {
      url,
      options: {
        ...options,
        params: cleanDeep(options.params),
        data: cleanDeep(options.data),
        headers: {
          ...options.headers,
          ...authHeaders
        }
      }
    };
  },
  { global: false }
);

request.interceptors.response.use(
  async res => {
    toast = setTimeout(() => {
      closeToast();
    }, 100);

    if (res.status > 299 || res.status < 200) {
      const msg = '服务器错误，状态码' + res.status;
      clearTimeout(toast);
      clearTimeout(toastMsg);
      toastMsg = setTimeout(() => {
        showToast(msg);
      }, 60);
      throw new Error(msg);
    }
    const data = await res.clone().json();
    // 999 为特殊code码
    const otherCode = [999, 5435, 5436, 5437, 5439, 5442, 5443, 5408, 5427, 980, 981, 982,983, 984];
    if (
      data.code !== 200 &&
      data.errCode !== 0 &&
      !otherCode.includes(data.code)
    ) {
      let msg = data.msg || data.message || '处理失败，请重试';
      if (initRequest && !isPc) {
        if (data.code === 403 || data.code === 5000) {
          setLogout();
        } else {
          setLoginError();
        }
      }
      if (!(data.code === 403 || data.code === 5000)) {
        clearTimeout(toast);
        clearTimeout(toastMsg);
        toastMsg = setTimeout(() => {
          showToast(msg);
        }, 60);
      }
      const browserInfo = browser();
      if (data.code === 5000 || data.code === 403) {
        msg += ' authentication ' + data.code;
        if (browserInfo.isApp) {
          postMessage({
            api: 'login'
          });
        } else {
          if (!isPc) setLogout();
        }
      }
      throw new Error(msg);
    }
    return res;
  },
  { global: false }
);

export default request;
