import Axios from 'axios';
import qs from 'qs';
const axios = Axios.create();
console.log(`========API_ROOT:${API_HOST}========`);

export const API_ROOT = API_HOST;
const tokenMode='header';//header,cookie
const tokenName='token';

let Modal = {
  error: (options) => {
    alert(options.content);
  },
};

let jwt = '';
export const logout = ()=>{
  localStorage.removeItem('jwt');
  jwt='';
}
export const setJwt = (value) => {
  localStorage.setItem('jwt', value);
  jwt = value;
};


axios.interceptors.request.use(function (config) {
  const header = { 'X-Requested-With': 'XMLHttpRequest' };
  if(tokenMode=='header'){
    if (jwt) {
      header[tokenName] = jwt;
    }
  }
  if (config.headers) {
    config.headers = { ...config.headers, ...header };
  } else {
    config.headers = header;
  }

  // 在发送请求之前做些什么
  return config;
});

/**
 * 统一拦截异常消息弹屏报错处理
 * 如果希望某条消息不拦截，可以再发送消息时带上 noInterceptors:true|'all'
 */
axios.interceptors.response.use(
  function (response) {
    // setJwt(response?.headers['set-token'] || jwt);
    if (response.config.noInterceptors) {
      return response;
    }
    if (Number(response.data.code) !== 0) {
      console.log(`${JSON.stringify(response.data)}`);
      Modal.error({ title: `注意`, content: `${response.data.msg}(${response.data.code})` });
    }
    return response;
  },
  function (error) {
    if (error.response.config.noInterceptors === 'all') {
      return Promise.reject(error.response);
    }
    // jwt失效
    if (error.response.status === 401) {
      if(logout)logout();
      return;
    } else if (error.response.status === 403) {
      Modal.error({
        title: '提示',
        content: `${error.response.data.msg}`,
      });
      return;
    }
    Modal.error({
      title: `网络错误${error.response.status}`,
      content: `${error.response.config.url}`,
    });
    return null;
  }
);




let buffer = {};
export async function GET_DEFAULT(url, param, options) {
  if (param) param = qs.stringify(param, { arrayFormat: 'indices' });
  let now = Date.now();

  let bufferItem;
  if (options?.ttl) {
    if (buffer[url]) {
      bufferItem = buffer[url];
      if (bufferItem.param == param && now <= bufferItem.endTime) {
        return bufferItem?.response?.data || null;
      }
    }
  }
  let response = await axios({
    method: 'GET',
    url: param ? `${url}?${param}` : url,
    ...options,
  });

  if (options?.ttl) {
    if (!buffer[url]) {
      buffer[url] = {};
    }
    buffer[url].param = param;
    let ttl = options.ttl === true ? 1000 * 2 : options.ttl;
    buffer[url].endTime = Date.now() + ttl;
    buffer[url].response = response;
  }

  return response && response.data ? response.data : null;
}

export async function GET_DEFAULT_CROSS(url, param) {
  if (param) param = qs.stringify(param, { arrayFormat: 'indices' });

  let response = await axios({
    method: 'GET',
    xsrfCookieName: '',
    xsrfHeaderName: '',
    withCredentials: true,
    url: param ? `${url}?${param}` : url,
  });
  return response && response.data ? response.data : null;
}

export async function POST_DEFAULT(url, params, method, options) {
  let data = params;
  // if (params) params = qs.stringify(params, { arrayFormat: 'indices' });
  // if (typeof params === 'string') {
  //   data = params;
  // } else {
  //   data = { ...params };
  // }

  let response = await axios({
    method: method || 'POST',
    url: url,
    data,
    ...options,
    // headers: { 'content-type': 'application/x-www-form-urlencoded' },
  });
  return response && response.data ? response.data : null;
}

export async function POST_DEFAULT_CROSS(url, params) {
  let data = {};
  // if (params) params = qs.stringify(params, { arrayFormat: 'indices' });

  if (typeof params === 'string') {
    data = params;
  } else {
    data = { ...params };
  }
  let response = await axios({
    method: 'POST',
    url: url,
    xsrfCookieName: '',
    xsrfHeaderName: '',
    withCredentials: true,
    data,
  });

  return response && response.data ? response.data : null;
}
