import axios from 'axios'
// import storage from 'store'
import router from '../router'
import store from '../store'
import {
  Message
} from 'element-ui';
import {
  refreshToken
} from '@/api/login'
import Cookies from "js-cookie";
// 创建 axios 实例
const Url = "https://gascylinder.baozhida.cn/gas_cylinder"
// const Url = "http://gascylindertest.baozhida.cn/gas_cylinder"
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.NODE_ENV === 'production' ? Url : '/api',
  timeout: 10000, // 请求超时时间
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*'
  }
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.message == 'timeout of 10000ms exceeded') {
    Message.error('当前网络不稳定,请更换网络重试')
    return error
  } else {
    if (error.response) {
      const data = error.response.data
      if (error.response.status === 403) {
        Message.error(data.message)
      }
      if (error.response.status === 401) {
        Message.error(data.message)
      }
    }
    return Promise.reject(error)
  }
}

// request interceptor
request.interceptors.request.use(config => {
  const token = localStorage.getItem('T_tokey')
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }
  if (config.method === 'post' && config.url != "/api/upload") {
    let data = config.data
    config.data = JSON.stringify(data)
  }
  return config
}, errorHandler)

let is404AlertShown = false;
// response interceptor
request.interceptors.response.use((response) => {
  if (response.data.Code || response.data.code) {
    const res = response.data
    if (res.code == 6401) {
      return refreshToken().then((itmds) => {
        // 更新本地存储的 Token
        localStorage.setItem("T_tokey", itmds.token);
        // 重新发送原请求
        return request(response.config);
      })
    }
    if (res.code == 401 && !is404AlertShown) {
      is404AlertShown = true;
      localStorage.removeItem('T_tokey');
      localStorage.removeItem('username');
      return store.dispatch('Logout').then(() => {
        router.push('/login');
        Message.error(res.msg || res.message)
      })
    }
    if (res.code == 200 || res.code == 404) {
      is404AlertShown = false;
      return res
    } else {
      Message.error(res.msg || res.message)
    }
    return response.data
  } else {
    return response.data
  }
}, errorHandler)

export default request

export {
  request as axios
}
