import Axios from 'axios'
import { getToken } from '@/utils/auth'
import Vue from 'vue'
import router from '@/router'

const axios = Axios.create({
  baseURL: window.apiHostSetting.VUE_APP_BASE_URL + '/api',
  timeout: 30 * 1000
})
let HTTPNUM = 0
axios.interceptors.request.use((config) => {
  if (config.data && typeof config.data === 'object') {
    const data = config.data
    for (const key in data) {
      if (data[key] === '') {
        data[key] = null
      }
    }
    config.data = data
  }
  config.headers['jwt-token'] = getToken()
  return config
})
axios.interceptors.response.use(
  (res) => {
    if (res.status === 200) {
      if (res.data.code === 401) {
        localStorage.clear()
        // token过期
        Vue.prototype.$message({
          type: 'error',
          message: res.data.message,
          offset: 200,
          duration: 1000
        })
        sessionStorage.setItem('active', 'true')
        // router
        //   .replace({
        //     name: 'login',
        //   })
        //   .catch((err) => {
        //     console.log(err)
        //   })
        return Promise.reject(res.data)
      } else if (res.data.code === 402) {
        Vue.prototype.$message({
          message: res.data.message,
          type: 'warning',
          offset: 200,
          duration: 1000
        })
        return Promise.reject(res.data)
      } else if (res.data.code === 403) {
        localStorage.clear()
        // token过期
        if (HTTPNUM === 0) {
          HTTPNUM++
          Vue.prototype.$message({
            type: 'error',
            message: res.data.message,
            offset: 200,
            duration: 1000
          })
          router
            .replace({
              name: 'login'
            })
            .catch((err) => {
              console.log(err)
            })
        }
        return Promise.reject(res.data)
      } else if (res.data.code === 500) {
        Vue.prototype.$alert(
          '<div style="max-height:500px;overflow:auto">' +
            res.data.message +
            '</div>',
          '错误提示',
          {
            dangerouslyUseHTMLString: true
          }
        )
      }
    } else {
      if (res.status === 400) {
        if (res.data) {
          const fileReader = new FileReader()
          fileReader.readAsText(res.data)
          fileReader.onload = function (ev) {
            console.log(ev.target.result)
            Vue.prototype.$alert(ev.target.result, '提示', {
              confirmButtonText: '确定',
              callback: () => {}
            })
          }
        } else {
          Vue.prototype.$alert('请求参数有误', '提示', {
            confirmButtonText: '确定',
            callback: () => {}
          })
        }
      } else if (res.status === 404) {
        Vue.prototype.$alert('请求不存在', '提示', {
          confirmButtonText: '确定',
          callback: () => {}
        })
      }
    }
    return res.data
  },
  // 服务器状态码不是200的情况
  (error) => {
    Vue.prototype.$alert(error.message, 'Error', {
      confirmButtonText: '确定',
      callback: () => {}
    })
    return Promise.reject(error)
  }
)

export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, { params })
      .then((res) => {
        if (res.status === 200 && res.data) {
          resolve(res.data)
        } else {
          resolve(res)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}

export function post(url, params, headers) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params, headers)
      .then((res) => {
        if (res.status === 200 && res.data) {
          resolve(res.data)
        } else {
          resolve(res)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}

export default axios
