/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios';
import store from '@/store/';
import router from '@/router/router';
import {serialize} from '@/util/util';
import {getToken} from '@/util/auth';
import {Message} from 'element-ui';
import website from '@/config/website';
import {Base64} from 'js-base64';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import error from "../views/monitor/log/error";
import Bus from "../util/bus";
import {dateFormat} from "../util/date";

//默认超时时间
axios.defaults.timeout = 10000;
//返回其他状态码
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500;
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress 配置
NProgress.configure({
  showSpinner: false
});
//http request拦截
axios.interceptors.request.use(config => {
  //开启 progress bar
  NProgress.start();
  const meta = (config.meta || {});
  const isToken = meta.isToken === false;
  config.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
  //让每个请求携带token
  let flag = true;
  let tokenDatetime = JSON.parse(localStorage.getItem('saber-token-datetime'))
  let expiresIn = localStorage.getItem('saber-expires-in');
  // 因为不刷新token，也还有对应的有效时间，并不是立即失效的，所以这里把失效时长减半，这样就对应上了
  if (tokenDatetime && expiresIn){
    flag = new Date(tokenDatetime + (expiresIn * 1000)) > new Date().getTime();
    console.log('flag-' + flag)
  }
  if (getToken() && !isToken && flag) {
    config.headers[website.tokenHeader] = 'bearer ' + getToken()
  }
  //headers中配置text请求
  if (config.text === true) {
    config.headers["Content-Type"] = "text/plain";
  }
  //headers中配置serialize为true开启序列化
  if (config.method === 'post' && meta.isSerialize === true) {
    config.data = serialize(config.data);
  }
  //把所有搜索参数的前后空格去掉
  let params = config.params;
  if (params && Object.keys(params).length > 0){
    Object.keys(params).forEach(item => {
      if (typeof params[''+item] == 'string'){
        params[''+item] = params[''+item].trim();
      }
    })
  }

  return config
}, error => {
  return Promise.reject(error)
});
//http response 拦截
axios.interceptors.response.use(res => {
  //关闭 progress bar
  NProgress.done();
  //获取状态码
  const status = res.data.code || res.status;
  const statusWhiteList = website.statusWhiteList || [];
  const message = res.data.msg || res.data.error_description || '未知错误';
  //如果在白名单里则自行catch逻辑处理
  if (statusWhiteList.includes(status)) return Promise.reject(res);
  //如果是401则跳转到登录頁面
  if (status === 401) store.dispatch('FedLogOut').then(() => router.push({path: '/login'}));
  // 如果请求为非200否者默认统一处理
  if (status !== 200) {
    Message({
      message: message,
      type: 'error',
    });
    return Promise.reject(new Error(message))
  }

  if (res.config.url != '/api/blade-auth/oauth/logout'){
    //十分鐘內的請求，都是同一個值傳過去
    Bus.$emit('notice', Math.floor(new Date().getTime() / (1000 * 10)));
  }
  if (res.config.url == '/api/blade-auth/oauth/token'){
    if (res.config.params && res.config.params.refresh_token){
    }else{
      localStorage.setItem('saber-token-datetime', new Date().getTime())
    }
  }else if (res.config.url == '/api/blade-desk/notice/myNoticePage'){
  }else{
    localStorage.setItem('saber-token-datetime', new Date().getTime())
  }


  //
  return res;
}, error => {
  NProgress.done();
  return Promise.reject(new Error(error));
});

export default axios;
