import Request from './luch-request/index.js'
import jwt from './jwt.js'
import { toast } from '@/com/utils.js'

const baseApi = process.env.VUE_APP_BASE_API;
//测试地址
// const baseApi = 'http://lcny.sk797.cn';
const http = new Request();

http.setConfig((config) => { /* 设置全局配置 */
  config.baseURL = baseApi
  config.header = {
    ...config.header,
    'Accept': 'application/json'
  }
  config.custom = {
    auth: true, // 是否传token
    // loading: false // 是否使用loading
  }
  config.imeout = 30000

  return config
})
/* 请求之前拦截器 */
http.interceptors.request.use((config, cancel) => {
  if (config.custom.auth) {
    // 需要权限认证的路由 需携带自定义参数 {custom: {auth: true}}
    config.header.Authorization = 'Bearer ' + jwt.getAccessToken();
  }
  return config
})

/* 请求之后拦截器 */
let isRefreshing = false;//多次锁

http.interceptors.response.use((response) => { /* 请求之后拦截器*/
  const { code } = response.data
  if (code != 200) {
    if (code == 4024) {
      
      toast(response.data.msg)
    } else if (code == 401) {
      toast('请关闭，重新进入')
    } else {
      toast(response.data.msg ?? response.data.message)
    }
    return Promise.reject(response)
  }

  return response
}, (err) => { // 请求错误
  const { code } = err.data
  console.log(code)
  if (code == 401) {//过期未登录
    const config = err.config
    if (!isRefreshing) {
      isRefreshing = true

    } else {

    }
  } else {

  }
  console.log(err, '======')
  return Promise.reject(err)
})
const getFullUrl = (url, params, header) => {
  return http.post(url, params, { ...header });
};
export {
  http,
  getFullUrl
}