import { extend } from 'umi-request';
import cleanDeep from 'clean-deep';
import { useUserStore } from '../store/modules/users';
import router from '@/router';
import { eventGlobal, getAuthForAdmin } from '.';
import { storage } from './storage';
import { ACCESS_TOKEN_ADMIN } from '../store/mutation-types';

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

let hideErrorMesage = false; // 是否显示错误信息

const request = extend({
  // requestType: 'form',
  hideLoading: true, // 默认都不显示加载
  timeout: 20000,
  timeoutMessage: '请求超时'
});

request.interceptors.request.use(
  (url, options: any) => {
    hideErrorMesage = options.hideErrorMesage || false;
    if (!options.hideLoading) {
      window.$message.loading('加载中...');
    }

    const userStore = useUserStore();

    let Authorization = userStore.getToken || '';
    const authHeaders: any = {};
    // if (
    //   userStore.getUserInfo &&
    //   userStore.getUserInfo.schoolInfos &&
    //   userStore.getUserInfo.schoolInfos[0]?.id &&
    //   options.data
    // ) {
    //   options.data['schoolId'] =
    //     (userStore.getUserInfo && userStore.getUserInfo.schoolInfos[0]?.id) ||
    //     '';
    // }
    if (
      userStore.getUserInfo &&
      (userStore.getUserInfo.schoolInfos as any) &&
      userStore.getUserInfo.schoolInfos[0]?.id
    ) {
      // console.log(
      //   userStore.getUserInfo && userStore.getUserInfo.schoolInfos[0]?.id,
      //   ' userStore.getUserInfo && userStore.getUserInfo.schoolInfos[0]?.id',
      //   options
      // );

      options.headers['schoolId'] =
        (userStore.getUserInfo && userStore.getUserInfo.schoolInfos[0]?.id) ||
        '';
    }
    if (
      Authorization &&
      !['/api-oauth/userlogin', '/api-auth/open/sendSms'].includes(url)
    ) {
      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: any) => {
    const userStore = useUserStore();
    if (res.status > 299 || res.status < 200) {
      const msg = '服务器错误，状态码' + res.status;
      // 判断是否有资源需要证书，不提示错误信息
      if (res.status === 511) {
        eventGlobal.emit('auth-not-installed');
      } else {
        !hideErrorMesage && window.$message.error(msg);
      }

      throw new Error(msg);
    }
    const data = await res.clone().json();

    if (
      data.code === 401 ||
      data.code === 4001 ||
      data.code == 403 ||
      data.code == 5000
    ) {
      userStore.logout(); // 删除登录 - 清除缓存
      router.replace('/login');
      location.reload();
      return;
    }
    // if (
    //   (((data.code < 200 && data.code != 100) ||
    //     (data.code >= 300 && data.code != 100)) &&
    //     data.code != 0 &&
    //     data.code == 5200) ||
    //   data.code == 5400 ||
    //   (data.code >= 5000 && data.code < 6000) ||
    //   data.code == -1
    // ) {
    //   const str = res.message || `请求失败code码为${data.code}`;
    //   window.$message.error(str);
    //   throw new Error(str);
    // }

    if (data.code !== 200 && data.errCode !== 0) {
      const msg = data.msg || data.message || '处理失败，请重试';
      if (!(data.code === 403 || data.code === 401)) {
        window.$message.error(msg);
      }
      throw new Error(msg);
    }
    return res;
  },
  { global: false }
);

export default request;
