import axios from 'axios'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
import qs from 'qs'
import storage from '@/utils/storage'
// import { Loading } from 'element-ui';
class Request {
  constructor(baseURL = '/re') {
    this.request = axios.create({
      baseURL,
      headers: {
        'content-type': 'application/json;charset=utf-8'
      },
      withCredentials: true
    })
    // 在全局请求和响应拦截器中添加请求状态
    // let loading = null
    // request interceptor
    this.request.interceptors.request.use(
      config => {
        // do something before request is sent
        // if (!loading) {
        //   loading = Loading.service(options);
        // }
        if (store.getters.token) {
          // let each request carry token
          // ['X-Token'] is a custom headers key
          // please modify it according to the actual situation
          config.headers['Authorization'] = 'Bearer ' + getToken()
          config.headers['Content-Type'] = 'application/json'
        }
        return config
      },
      error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
      }
    )
    // response interceptor
    this.request.interceptors.response.use(
      /**
       * If you want to get http information such as headers or status
       * Please return  response => response
       */

      /**
       * Determine the request status by custom code
       * Here is just an example
       * You can also judge the status by HTTP Status Code
       */
      response => {
        const code = response.data.code
        // if (loading) {
        //   loading.close()
        //   loading = null
        // }
        if (code === 401) {
          // store.dispatch('user/resetToken')
          if (location.href.indexOf('login') !== -1) {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          } else {
            MessageBox.confirm(
              '登录状态已过期，您可以继续留在该页面，或者重新登录',
              '系统提示', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
              }
            ).then(() => {
              clearInterval(window.refreshTime)
              window.refreshTime = null
              storage.clear()
              location.reload() // 为了重新实例化vue-router对象 避免bug
            })
          }
        } else if (code === 6401) {
          // store.dispatch('user/resetToken')
          MessageBox.confirm(
            '登录状态已过期，您可以继续留在该页面，或者重新登录',
            '系统提示', {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            storage.clear()
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
          return false
        } else if (code === 400 || code === 403) {
          Message({
            message: response.data.msg,
            type: 'error',
            duration: 5 * 1000
          })
        } else if (code > 200) {
          // Message({
          //   message: response.data.msg,
          //   type: 'error'
          // })
          return Promise.reject('error')
        } else {
          return response.data
        }
      },
      error => {
        // if (loading) {
        //   loading.close()
        //   loading = null
        // }
        if (error.message === 'Network Error') {
          Message({
            message: '服务器连接异常，请检查服务器！',
            type: 'error',
            duration: 5 * 1000
          })
          return
        }
        return Promise.reject(error)
      }
    )
  }
  get(url, params) {
    this.url = url
    return this.request.get(url, {params})
  }

  post(url, data) {
    this.url = url
    return this.request.post(url, data)
  }

  delete(url, data) {
    return this.request.delete(url, {
      data: data
    })
  }
  form(url, body) {
    return this.request.post(url, qs.stringify(body), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  }

  postForm(url, params) {
    return this.request.post(url, params, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
  getFileTem(url) {
    return this.request.get(url, {
      responseType: 'blob'
    })
  }

  postFileDown(url, params) {
    return this.request.post(url, params, {
      responseType: 'blob'
    })
  }

  getFileDown(url) {
    return this.request.get(url, {
      responseType: 'blob'
    })
  }
}
export default Request
