import axios from 'axios'; // 引入axios
import { Message } from 'element-ui';
import store  from '@/store/index'
import context from '@/main.js'
import { authDB } from '@/db'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 99999
})
let acitveAxios = 0
// let timer
// const showLoading = () => {
//     acitveAxios++
//     if (timer) {
//         clearTimeout(timer)
//     }
//     timer = setTimeout(() => {
//         if (acitveAxios > 0) {
//             context.$bus.emit("showLoading")
//         }
//     }, 400);
// }

// const closeLoading = () => {
//         acitveAxios--
//         if (acitveAxios <= 0) {
//             clearTimeout(timer)
//             context.$bus.emit("closeLoading")
//         }
//     }
    //http request 拦截器
service.interceptors.request.use(
    config => {
        // if (!config.donNotShowLoading) {
        //     showLoading()
        // }
        config.data = JSON.stringify(config.data);
        config.headers = {
            'Content-Type': 'application/json',
            'x-token': authDB.get('token'),
            'x-user-id': authDB.get('uid')
        }
        return config;
    },
    error => {
        // closeLoading()
        Message({
            duration:2000,
            showClose: true,
            message: error,
            type: 'error'
        })
        return error;
    }
);


//http response 拦截器
service.interceptors.response.use(
    response => {
        // closeLoading()
        if (response.headers["new-token"]) {
            store.commit('user/setToken', response.headers["new-token"])
        }
        // 下载文件
        if ( response.headers.success == "true"){
          return  response
        } else if (response.data.code == 200 ) {
            return response.data
        } else {
          if (response.data.data && response.data.data.reload) {
              store.commit('user/Logout')
              return
          }
          Message({
              duration:2000,
              showClose: true,
              message: response.data.msg || decodeURI(response.headers.msg),
              type: response.headers.msgtype||'error',
          })
          return response.data.msg ? response.data : response
        }
    },
    error => {
        Message({
          duration:2000,
            showClose: true,
            message: error,
            type: 'error'
        })
        return error
    }
)

export default service
