import { extend } from 'umi-request';
import cleanDeep from 'clean-deep';
import { setLogout, setLoginError } from '@/state';
import { postMessage } from './native-message';

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

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

// 是否是初始化接口
let initRequest = false;

request.interceptors.request.use(
  (url, options: any) => {
    initRequest = options.initRequest || false;
    const Authorization = sessionStorage.getItem('Authorization') || '';
    const authHeaders: any = {};
    if (
      Authorization &&
      ![
        '/api-oauth/userlogin',
        // `${state.platformApi}/user/getUserInfo`,
        '/api-oauth/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 => {
    if (res.status > 299 || res.status < 200) {
      const msg = '服务器错误，状态码' + res.status;
      throw new Error(msg);
    }
    const data = await res.clone().json();
    // 999 为特殊code码
    if (data.code !== 200 && data.errCode !== 0 && data.code !== 999) {
      const msg = data.msg || data.message || '处理失败，请重试';
      if (initRequest) {
        if (data.code === 403 || data.code === 5000) {
          setLogout();
        } else {
          setLoginError();
        }
      }
      console.log(data.code, '5104');
      if (!(data.code === 403 || data.code === 5000)) {
        // showToast(msg);
      }
      throw new Error(msg);
    }
    return res;
  },
  { global: false }
);

export default request;
