import axios from 'axios'
import store from './store'
// export const BASE_URL = 'https://api.xyyxt.net'   //release
// export const BASE_URL = 'http://42.192.164.187:19005'    //test
export const BASE_URL = 'http://api.xyyxt.net:19009'   //预发布
// export const BASE_URL = 'http://192.168.1.222:5055'    //dev
export const tenantId = '867735392558919680'


//图片上传api
// export const BASE_IMG_URL = 'https://file.xyyxt.net/'     //release
export const BASE_IMG_URL = 'https://file-dev.xyyxt.net/'  //test

import tools from './common/tools'
import router from './router'

// 创建 axios 实例
const request = axios.create({
  baseURL: BASE_URL,
  timeout: 10000 // 请求超时时间
})

// 错误处理函数
const err = (error) => {
  if (error.response) {
    const data = error.response.data
    // const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {

    }
    if (error.response.status === 401) {

    }
  }
  return Promise.reject(error)
}

// request interceptor(请求拦截器)
request.interceptors.request.use(config => {
  const token = tools.getToken()
  if (token && !config.noToken) {
    config.headers['AuthorizationToken'] = 'WX ' + token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  config.headers['TenantId'] = tenantId
  
  return config
}, err)

// response interceptor（接收拦截器）
request.interceptors.response.use(async (response) => {
  const res = response.data
  const code = res.code || 200;
  if (code !== 200) {

    if (code == 401) {
      let userAccount = tools.getUserAccount();

      if (!userAccount) {
        // Message({
        //   message: `登录失效，重新登录`,
        //   type: "error",
        // });

        // setTimeout(() => {
          console.log('1231231')
          store.commit('setCurrentRouter',router.currentRoute)
          localStorage.removeItem('user_account')
          localStorage.removeItem('token')
          router.push({
            path: '/login'
          })

          return Promise.reject(res)
        // }, 1000);
      } else {
        let res = await refreshToken(response.config)
        return res
      }
    } else if (code == 500) {
      // Message({
      //   message: res.msg,
      //   type: "error",
      // });
      // localStorage.removeItem('user_account')
      // localStorage.removeItem('token')
      // console.log('222222')
      // router.push({
      //   path: '/login'
      // })
      return Promise.reject(res)
    } else {
      return Promise.reject(res)
    }

  } else {
    return res
  }
}, err)

async function refreshToken(response) {
  let userAccount = tools.getUserAccount();

  var datas = {
    url: '/refreshToken/' + userAccount,
    method: 'get',
    noToken: true
  }
  const res = await request(datas)
  if (res.code === 200) {
    localStorage.setItem('token', res.data.token)

    var userInfo = {
      url: '/app/user/getInfo',
      method: 'get',
    }
    const resUser = await request(userInfo)
    if (resUser.data.code === 200) {
      store.state.userInfo = resUser.data
      localStorage.setItem('user_account', userAccount)
      num = 1;
    }
    let onset = await request(response)
    return onset
  } else {
    // Message({
    //   message: `登录失效，重新登录`,
    //   type: "error",
    // });

    // setTimeout(() => {
      
      localStorage.removeItem('user_account')
      localStorage.removeItem('token')
      console.log('33333')
      store.commit('setCurrentRouter',router.currentRoute)
      router.push({
        path: '/login'
      })
    // }, 1000);
  }
}

export default request