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'
// 创建 axios 实例
const Url = process.env.VUE_APP_BASE_API
// const Url = "https://colddelivery.coldbaozhida.com/cold_delivery"
// const Url = "http://colddeliverytest.coldbaozhida.com:9090/cold_delivery" //测试
const token = localStorage.getItem('T_tokey')
// const Url = "http://192.168.11.77:6280" //测试
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.NODE_ENV === 'production' ? Url : '/api',
  timeout: 10000, // 请求超时时间
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
    'Access-Control-Allow-Origin': '*'
  }
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.message == 'timeout of 10000ms exceeded') {
    return Message.error('当前网络不稳定,请更换网络重试')
  } else {
    if (error.response) {
      const data = error.response.data
      if (error.response.status != 401 || error.response.status != 6401) {
        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.url != '/api/upload') {
    if (config.method === 'post') {
      let data = config.data
      config.data = data
    }
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  // 文件下载（主要看这块）
  if (response.headers['content-disposition']) {
    let downLoadMark = response.headers['content-disposition'].split(';');
    if (downLoadMark[0] === 'attachment') {
      // 执行下载
      let fileName = downLoadMark[1].split('filename=')[1];
      const arr = {
        data: response.data,
        fileName: fileName,
      }
      return arr
    }
  }
  if (response.data.Code || response.data.code) {
    // console.log(response,1)
    const res = response.data
    // console.log(res,2)
    if (res.code == 6401) {
      return refreshToken().then(resil => {
        // 更新本地存储的 Token
        if (resil != undefined) {
          localStorage.setItem("T_tokey", resil.token);
          // 重新发送原请求
          return request(response.config);
        }
      })
    } else if (res.Code == 401 || res.code == 401) {
      localStorage.removeItem('T_tokey');
      localStorage.removeItem('username');
      store.dispatch('Logout').then(() => {
        router.push('/login');
      })
      return
    }
    if (res.Code == 200 || res.code == 200 || res.code == 404 || res.code == 401 || res.code == 6401 || res.code ==
      2000 || res.code == 1201) {
      return res
    } else {
      Message.error(res.msg || res.message)
    }
    return response.data
  } else {
    return response.data
  }
}, errorHandler)

export default request

export {
  request as axios
}
