const init = () => new Promise(resolve => {
  const {axios, $glob} = window
  let getAuthing = false
  const getToken = () => {
    getAuthing = true
    return axios.post("http://10.0.97.209/data-boot/na/sys/login", {
      t: Date.now(),
      userAcc: "kengee",
      password: "kengee@123",
      uuid: "",
      captcha: ""
    }).then(res => {
      if (res?.data?.data) {
        $glob.token = res.data.data.token
      }
    }).finally(() => getAuthing = false)
  }
  const http = axios.create({baseURL: '/'})
  const addToken = (config) => {
    config.headers['h-token'] = $glob.token
    return config
  }
  http.interceptors.request.use(async config => {
    await $waitFor(!getAuthing)
    if (!$glob.token && !getAuthing) {
      await getToken()
    }
    return addToken(config)
  })
  http.interceptors.response.use(res => {
    if (res?.data) {
      if (res.data?.code == 6004) {
        return getToken().then(() => http.request(res.config))
      }
      return res.data
    } else if (res?.code == 401) {
      return getToken().then(() => http.request(res.config))
    }
    return res
  })
  window.$http = http
  resolve()
})
export default init()
