import axios from 'axios';
import {Message,Loading,MessageBox} from "element-ui";
import router from "../routes";
let http = axios.create({
  //baseURL: 'http://www.yytp.com/',
  //withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  },
  transformRequest: [function (data) {
    let newData = '';
    for (let k in data) {
      if (data.hasOwnProperty(k) === true) {
        newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
      }
    }
    return newData;
  }]
});

http.interceptors.request.use(
    config => {
      let authKey = sessionStorage.getItem('authKey');//token
      if(authKey){
          config.headers.authKey = JSON.parse(authKey);
      }

      return config;
    },
    error => {
      return Promise.reject(error);
    }
);

http.interceptors.response.use(response => {
  let data = response.data;
  if(data.code == "103"){
    var loginParams = { is_reg: 0 };                                        //登录状态为未登录
      http.post('/api/index/base/logout',loginParams).then((response) => {
        
      })
      MessageBox.alert(data.error,"登录超时",{
        confirmButtonText:"跳转登录页面",
        callback:action=>{
         
          location.href = "/#/login";
         
        }
      });
  }else{
    
    return response;
  }
  
});
function apiAxios(method, url, params, response) {
    http({
      method: method,
      url: url,
      data: method === 'POST' || method === 'PUT' ? params : null,
      params: method === 'GET' || method === 'DELETE' ? params : null,
    }).then(function (res) {
      response(res);
    }).catch(function (err) {
      response(err);
    })
}

export default {
  get: function (url, params, response) {
    return apiAxios('GET', url, params, response)
  },
  post: function (url, params, response) {
    return apiAxios('POST', url, params, response)
  },
  put: function (url, params, response) {
    return apiAxios('PUT', url, params, response)
  },
  delete: function (url, params, response) {
    return apiAxios('DELETE', url, params, response)
  }
  
}