import Qs from 'qs';
import axios from 'axios';
import { Toast } from 'vant';
import router from '../router';

// 处理跨域问题
axios.defaults.paramsSerializer = function (params) {
  return Qs.stringify(params, {arrayFormat: 'comma'})
}
// http://120.25.151.99:49002/PAY-SERVER
// http://120.25.151.99:49002/ORDER-SERVER
// http://120.25.151.99:49002/SZWL-SERVER
const service = axios.create({ baseURL: 'http://120.25.151.99:49002/' });

// 请求拦截器
service.interceptors.request.use(config => {
  // 把localStorage的token放在Authorization里
  let loginUser = localStorage.getItem('loginUser');
  if (loginUser && loginUser !== '') {
    loginUser = JSON.parse(loginUser);
    config.headers.Authorization = loginUser.currentToken;
  }
  return config;
}, (err) => { console.log("失败信息" + err); });

// 响应拦截器
service.interceptors.response.use(res => {
  if (res.config.url.indexOf('/tAdmin/getRelationAdminUsername') > -1) {
    return Promise.resolve(res);
  }
  if (typeof res.data !== 'object') {
    if (res.headers['content-type'] === 'application/vnd.ms-excel;charset=utf-8') {
      return Promise.resolve(res);
    }
    Toast.fail('服务端异常！')
    return Promise.reject(res)
  }
  if (res.status != 200) {
    // 请求错误时弹窗提示错误信息
    if (res.data.message) Toast.fail(res.data.message)
    // 请求状态416时为登陆问题跳转登陆界面
    // if (res.data.resultCode == 416) {
    //   router.push({ path: '/login' })
    // }
    // 登陆接口存储token及修改请求时默认token参数
    // if (res.data.data && window.location.hash == '#/login') {
    //   setLocal('token', res.data.data)
    //   axios.defaults.headers['token'] = res.data.data
    // }
    return Promise.reject(res.data);
  } else {
    // 后台反馈错误时展示错误信息
    if (!res.data.code && res.data.message) {
      Toast.fail(res.data.message)
    }
    if (res.data.code === 'L0006') {
      router.push({ path: '/login' });
    }
  }
  return Promise.resolve(res);
})

export default service;
