import type { AxiosResponse } from 'axios'
import axios from 'axios'
// import qs from 'qs'
import { ElLoading, ElMessage } from 'element-plus'
import router from '@/router/index'
import useSettingsStore from '@/store/modules/settings'
import useUserStore from '@/store/modules/user'
let loading: { close: () => void }

// 全局拦截请求发送前提交的参数
const settingsStore = useSettingsStore()

const toLogin = () => {
  useUserStore().logout().then(() => {
    router.push({
      path: '/login',
      query: {
        redirect: router.currentRoute.value.path !== '/login' ? router.currentRoute.value.fullPath : undefined,
      },
    })
  })
}

const apiRequest = axios.create({
  baseURL: import.meta.env.DEV ? settingsStore.settings.base.devServerUrl : settingsStore.settings.base.serverUrl,
  timeout: 1000 * 60,
  responseType: 'json',
})

apiRequest.interceptors.request.use(
  (request) => {
    // loading = ElLoading.service({ text: 'LOADING……' })
    const userStore = useUserStore()
    // 设置请求头
    if (request.headers) {
      request.headers['Accept-Language'] = settingsStore.settings.app.defaultLang
      request.headers.AppID = settingsStore.settings.base.appID
      request.headers.AppKey = settingsStore.settings.base.appKey
      request.headers.AppSecret = settingsStore.settings.base.appSecret
      if (userStore.isLogin) {
        request.headers.Authorization = `Bearer ${userStore.token}`
      }
    }
    // 是否将 POST 请求参数进行字符串化处理
    if (request.method === 'post') {
      // request.data = qs.stringify(request.data, {
      //   arrayFormat: 'brackets',
      // })
    }
    return request
  },
)

apiRequest.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    // loading.close()
    /**
     * 全局拦截请求发送后返回的数据，如果数据有报错则在这做全局的错误提示
     * 假设返回数据格式为：{ status: 0, error: '', data: '' }
     * 规则是当 status 为 0 时表示请求成功，为 0 时表示接口需要登录或者登录状态失效，需要重新登录
     * 请求出错时 error 会返回错误信息
     */
    if (response.config.responseType === 'blob') {
      // 如果是文件流，直接过
      return response
    }
    else if (response.data.code === 200) {
      return response.data
    }
    else {
      ElMessage.error(response.data.msg)
      if (response.data.code === 401) {
        toLogin()
        return Promise.reject(response.data)
      }
      else {
        return Promise.reject(response.data)
      }
    }
  },
  (error) => {
    loading.close()
    let message = error.message
    if (message === 'Network Error') {
      message = '后端网络故障'
    }
    else if (message.includes('timeout')) {
      message = '接口请求超时'
    }
    else if (message.includes('Request failed with status code')) {
      message = `接口${message.substr(message.length - 3)}异常`
    }
    ElMessage({
      message,
      type: 'error',
    })
    return Promise.reject(error)
  },
)

export default apiRequest
