// import { serialize } from '../util/util'
// import { getStore } from '../util/store'
import NProgress from 'nprogress' // progress bar
import { Message,MessageBox } from 'element-ui'
import axios from 'axios'
import errorCode from '../util/errorCode'
import router from '../router/router'
import 'nprogress/nprogress.css'
import store from '../store' // progress bar style
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 30000
})
// service.defaults.timeout = 30000
// 返回其他状态吗
service.defaults.validateStatus = function(status) {
  return status >= 200 && status <= 500 // 默认的
}
// 创建axios实例
// axios.baseURL=process.env.VUE_APP_BASE_API, 
// 跨域请求，允许保存cookie
service.defaults.withCredentials = true
// NProgress Configuration
NProgress.configure({
  showSpinner: false
})

// HTTPrequest拦截
service.interceptors.request.use(config => {
  NProgress.start() // start progress bar
//   const TENANT_ID = getStore({ name: 'tenantId' })
  config.withCredentials = true; // 允许携带token ,这个是解决跨域产生的相关问题
  const isToken = (config.headers || {}).isToken === false
  const token = store.getters.token
  if (token && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + token// token
    // config.headers['Cookie']='Admin-Token=' + token
  }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?';
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName];
        // console.log('value---',value)
          var part = encodeURIComponent(propName) + "=";
          if (value !== null && typeof(value) !== "undefined" )  {
            if (typeof value === 'object') {
              for (const key of Object.keys(value)) {
                let params = propName + '[' + key + ']';
                var subPart = encodeURIComponent(params) + "=";
                url += subPart + encodeURIComponent(value[key]) + "&";
                // console.log('请求路径url',url)
              }
            } else {
              url += part + encodeURIComponent(value) + "&";
              // console.log('请求路径url1',url)
            }
          }
      }
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
      // console.log('请求路径',config.url)
    }
//   if (TENANT_ID) {
//     config.headers['TENANT-ID'] = TENANT_ID // 租户ID
//   }

  // headers中配置serialize为true开启序列化
//   if (config.method === 'post' && config.headers.serialize) {
//     config.data = serialize(config.data)
//     delete config.data.serialize
//   }
  return config
}, error => {
  // console.log('reject1',error)
  return Promise.reject(error)
})

// HTTPresponse拦截
service.interceptors.response.use(res => {
  NProgress.done()
  // console.log('res---',res)
  // const status = res.status || 200
  const status = Number(res.data.code) || 200
  const message = res.data.msg || errorCode[status] || errorCode['default']
  // console.log('status--',status,typeof(status),status.toString().length)
  //   &&  store.getters.token
  if (status === 401 ) {
    // Message({
    //   message: message,
    //   type: 'error'
    // })
    // return Promise.reject(new Error(message))
    Message({
      message:'无效登录',
      type: 'warning',
      duration:1000,
    })
    store.dispatch('LogOut').then(() => {
      router.push({ path: '/login?type=log' })
    })
    // MessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
    //     confirmButtonText: '重新登录',
    //     showCancelButton:false,
    //     showClose:false,
    //     type: 'warning'
    //   }
    // ).then(() => {
    //   store.dispatch('LogOut').then(() => {
    //     router.push({ path: '/login?type=log' })
    //   })
    // })
  }
  if (status === 500) {
    Message({
      message: message,
      type: 'error'
    })
    // console.log('reject2',message)
    return Promise.reject(new Error(message))
  }
  // if(status.toString().length==11){
  //   return res.data
  // }

  if (status !== 200 || status === 1) {
    // Message({
    //   message:'稍后重试',
    //   type: 'error'
    // })
    // console.log('reject3',message)
    return Promise.reject(new Error(message))
  }
  
  return res.data
}, error => {
  NProgress.done()
  let { message } = error;
  if (message == "Network Error") {
    message = "后端接口连接异常";
  }
  else if (message.includes("timeout")) {
    message = "系统接口请求超时";
  }
  else if (message.includes("Request failed with status code")) {
    message = "系统接口" + message.substr(message.length - 3) + "异常";
  }
  // console.log('reject4',error)
  return Promise.reject(new Error(error))
})

export default service
