import Request from "luch-request";
import {
  v4 as uuidv4
} from 'uuid'
import store from '@/store'
import throttle from 'uview-ui/libs/function/throttle.js'
const http = new Request()
 
http.setConfig((config) => {
  config.baseURL = process.env.VUE_APP_BASE_API
  config.header = {
    ...config.header,
    Accept: 'application/json;version=1.2.0'
  }
  // 是否显示加载状态
  config.custom = {
    loading: false,
    toast: true,
    silence:false
  }
  return config
})


http.interceptors.request.use(async (config) => {
  config.header = {
    ...config.header,
    // 'X-Request-ID': uuidv4(),
    'client-app': process.env.VUE_APP_LANGUAGE,
    'client-version': process.env.VUE_APP_VERSION,
    'client-platform': store.getters.platform,
    'client-os': store.getters.system
  }
  if (store.getters.token) {
    config.header['Authorization'] = 'Bearer ' + store.getters.token
  }

  if (config.custom.loading) {
    uni.showLoading({
      title: '加载中',
      mask: true
    });
  }

  return config
}, (config) => {
  return Promise.reject(config)
})


http.interceptors.response.use(async (response) => {
  if (response.config.custom.loading) {
    uni.hideLoading()
  }

  const {
    data
  } = response
  return data
}, (response) => {
  if (response.config.custom.loading) {
    uni.hideLoading()
  }
  const {
    statusCode,
    data
  } = response

  if ([2000].includes(data?.errcode)) {
    return Promise.reject(response)
  }

  if (statusCode == 422) {
    const {
      errors,
      errcode
    } = data
    for (const key in errors) {
      if(response.config.custom.toast){
        uni.showToast({
          title: errors[key][0],
          icon: 'none',
          duration: 1500
        })
      }
      break
    }
    return Promise.reject(data)
  } else if (statusCode == 401) {
    store.dispatch('user/resetToken')

    if(!response.config.custom.silence){
      if(response.config.custom.toast){
        uni.showToast({
          title: '登录已过期，请重新登录',
          icon: 'none',
          duration: 1500
        })
      }
      throttle(() => uni.navigateTo({ url: '/pages/login/index' }), 2000)
    }
    return Promise.reject(data)
  }

  if(response.config.custom.toast){
    uni.showToast({
      title: data?.message ?? '系统繁忙，请稍后再试',
      icon: 'none',
      duration: 1500
    })
  }

  return Promise.reject(data)
})

export {
  http
}
