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 = "https://coldlogistics.coldbaozhida.com/Cold_Logistic"
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.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.method === 'post' && config.url != "/api/waybill/import") {
    let data = config.data
    config.data = JSON.stringify(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];
      if (fileName) {
        //fileName = decodeURIComponent(filename);//对filename进行转码
        fileName = decodeURI(fileName);
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(new Blob([response.data]), fileName);
        } else {
          let url = window.URL.createObjectURL(new Blob([response.data]));
          let link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
          return;
        }
      } else {
        return response.data;
      }
    }
  }
  if (response.data.Code || response.data.code) {
    const res = response.data
    if (res.code == 6401) {
      return refreshToken().then(res => {
        // 更新本地存储的 Token
        if (res != undefined) {
          localStorage.setItem("T_tokey", res.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) {
      return res
    } else {
      Message.error(res.msg || res.message)
    }
    return response.data
  } else {
    return response.data
  }
}, errorHandler)

export default request

export {
  request as axios
}
