import axios from 'axios';//引入axios

export function fetch(options) {
  if (process.env.NODE_ENV === 'production') {
    if (!window['userData']) {
      let user_data_str = localStorage.getItem('walk_userData');
      if (user_data_str) {
        window['userData'] = JSON.parse(user_data_str);
      }
    }
    if (!window['userData']) {
      localStorage.setItem('last_url', location.hash.slice(1));
      location.replace('#/Author');
    }
  }
  return new Promise((resolve, reject) => {
    const instance = axios.create({  //instance创建一个axios实例，可以自定义配置，可在 axios文档中查看详情
      //所有的请求都会带上这些配置，比如全局都要用的身份信息等。
      headers: {
        'Content-Type': 'application/json',
        'Authorization': process.env.NODE_ENV === 'production' ? (window['userData']?window['userData'].token:'') : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAiLCJvcGVuX2lkIjoiMTExMTExMTExMTExMTExMTExMTExMTExMTExMSIsInVuaW9uX2lkIjoiMTExMTExMTExMTExMTExMTExMTExMTExMTExMSIsImV4cCI6MTU1NDU2MjA2Mn0.eHkAuqQpoZb34KbCAyVzNaunn4Knn77jfC0N5DG5JD0"
        // 'token_in_header': global_.token,//token从全局变量那里传过来
      },
      timeout: 30 * 1000 // 30秒超时
    });
    instance(options)
      .then(response => { //then 请求成功之后进行什么操作
        console.log('raw response',response);
        response.data['date'] = response.headers.date;
        resolve(response.data);//把请求到的数据发到引用请求的地方
      })
      .catch(error => {
        console.log('请求异常信息：', error);
        if (process.env.NODE_ENV === 'production') {
          if (error.response.status == 401) {
            localStorage.setItem('last_url', location.hash.slice(1));
            localStorage.setItem('walk_userData', '');
            location.replace('#/Author');
          } else {
            reject(error);
          }
        }
      });
  });
}
