import axios from 'axios'
import router from '@/router'
import {
  ElLoading,
  ElMessage
} from 'element-plus'
import {
  setNotLoggedIn
} from '@/utils/auth'

export default class Request {
  http
  isMock = false
  isJWT = false
  loadingInstance
  loading = true
  constructor() {
    const apiVersion = process.env.VUE_APP_API_VERSION.replace(/\./g, '_')
    this.http = axios.create({
      baseURL: process.env.VUE_APP_API_BASEURL + apiVersion + '/',
      timeout: 2000000,
      withCredentials: true
    })

    this.interceptors()
  }

  mock(mock) {
    this.isMock = mock
    return this
  }

  JWT() {
    this.isJWT = true
    // this.http.defaults.headers.common['isJWT'] = true;
  }

  showLoading(show) {
    this.loading = show
    return this
  }

  post(path, params) {
    let config = {}
    if (this.isMock) config = {
      baseURL: process.env.VUE_APP_API_MOCK
    }
    return new Promise((resolve, reject) => {
      this.http
        .post(path, params, config)
        .then(r => {
          resolve(r)
        })
        .catch(e => {
          reject(e.message)
        })
    })
  }

  get(path, params) {
    const data = {
      params: params
    }
    if (this.isMock) data.baseURL = process.env.VUE_APP_API_MOCK
    return new Promise((resolve, reject) => {
      this.http
        .get(path, data)
        .then(r => {
          resolve(r)
        })
        .catch(e => {
          reject(e.message)
        })
    })
  }

  put(path, params) {
    let config = {}
    if (this.isMock) config = {
      baseURL: process.env.VUE_APP_API_MOCK
    }
    return new Promise((resolve, reject) => {
      this.http
        .put(path, params, config)
        .then(r => {
          resolve(r)
        })
        .catch(e => {
          reject(e.message)
        })
    })
  }

  delete(path) {
    let config = {}
    if (this.isMock) config = {
      baseURL: process.env.VUE_APP_API_MOCK
    }
    return new Promise((resolve, reject) => {
      this.http
        .delete(path, config)
        .then(r => {
          resolve(r)
        })
        .catch(e => {
          reject(e.message)
        })
    })
  }

  interceptors() {
    this.http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
    // 添加请求拦截器
    this.http.interceptors.request.use(
      config => {
        // 显示loading
        if (this.loading) {
          this.loadingInstance = ElLoading.service({
            fullscreen: true
          })
        }

        if (this.isJWT) {
          config.headers.Authorization = 'token'
        }
        return config
      },
      error => {
        // 请求错误
        return Promise.reject(error)
      }
    )

    // 添加响应拦截器
    this.http.interceptors.response.use(
      response => {
        // 关闭loading
        if (this.loading) this.loadingInstance.close()
        if (response.status === 200) {
          if (response.data.status !== 200 && response.data.status !== 99999 && response.data.status !== 202) {
            if (response.data.message) {
              ElMessage.error(response.data.message)
            }
          }
          if (response.data.errno === 2003) {
            setNotLoggedIn() // 设置未登录
            router.replace('/login')
            return
          }
          return response.data
        } else {
          console.error(response)
        }
      },
      error => {
        // 关闭loading
        setTimeout(() => {
          if (this.loading) this.loadingInstance.close()
        }, 3000)
        // 响应错误
        return Promise.reject(error)
      }
    )
  }
}