import { extend } from 'umi-request';
import cleanDeep from 'clean-deep';
import { showLoadingToast, showToast, closeToast } from 'vant';
import { createStorage } from '@/helpers/storage';
import { ACCESS_TOKEN } from '@/store/mutation-types';
const storage = createStorage({ prefixKey: '', storage: sessionStorage });
import { useStudentRegisterStore } from '@/store/modules/student-register-store';
const studentRegisterStore = useStudentRegisterStore();

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 toast: 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;
    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) {
      clearTimeout(toast);
      const msg = '服务器错误，状态码' + res.status;
      showToast(msg);
      throw new Error(msg);
    }
    const data = await res.clone().json();
    // 999 为特殊code码
    if (data.code !== 200 && data.errCode !== 0 && data.code !== 999) {
      let msg = data.msg || data.message || '处理失败，请重试';
      if (!(data.code === 403 || data.code === 5000)) {
        clearTimeout(toast);
        showToast(msg);
      }
      if (data.code === 5000 || data.code === 403) {
        msg += ' authentication ' + data.code;
        studentRegisterStore.studentLoutOut();
      }
      throw new Error(msg);
    }
    return res;
  },
  { global: false }
);

export default request;
