import axios from '@/utils/request/axios'
import qs from 'qs'
import { storage } from '@/utils'
import { ubmsConfig } from './config'
import { PendingManager } from './pendingManager'

const pendingManager = new PendingManager()

/**
 * 创建 axios 实例
 */
const instance = axios.create({
  baseURL: ubmsConfig.baseURL,
  timeout: 5000,
})

/**
 * 请求拦截器
 */
instance.interceptors.request.use((request) => {
  const accessToken = storage.get(`${ubmsConfig.storagePrefixKey}accessToken`, '')

  request.headers.deviceid = 'unknown'
  request.headers.Authorization = `Bearer ${accessToken}`

  return request
})

/**
 * 响应拦截器
 */
instance.interceptors.response.use(
  (response) => {
    if (Number(response.status) === 200) {
      const result = response.data
      result.msg = result.message // message

      if (Number(result.code) === 0) {
        return result
      } else {
        uni.showToast({
          icon: 'none',
          title: `${result.msg || result.code || 'Result Error'}`,
          duration: 3 * 1000,
        })

        return Promise.reject(result)
      }
    } else {
      httpErrorHandle(response)

      return Promise.reject(response)
    }
  },
  async (error) => {
    if (error.response.status === 410) {
      if (!pendingManager.isRefreshing) {
        pendingManager.isRefreshing = true
        await refreshAccessToken()
        pendingManager.isRefreshing = false
        pendingManager.removeAllPending()

        return instance(error.config)
      }

      return new Promise((resolve) => {
        pendingManager.addPending(() => {
          resolve(instance(error.config))
        })
      })
    } else {
      httpErrorHandle(error)
    }

    return Promise.reject(error)
  },
)

/**
 * HTTP 错误
 */
export function httpErrorHandle(error) {
  // console.log('[httpErrorHandle]', error)

  let msg = ''

  if (error.response && error.response.data) {
    const { code, message: msg } = error.response.data

    uni.showToast({
      icon: 'none',
      title: msg || code,
      duration: 3 * 1000,
    })
    return
  }

  if (msg) {
    uni.showToast({
      icon: 'none',
      title: '当前网络不可用，请检查你的网络设置',
      duration: 3 * 1000,
    })
  }
}

/**
 * 刷新AccessToken，通过登录接口
 */
async function refreshAccessToken() {
  try {
    const params = {
      username: ubmsConfig.username,
      password: ubmsConfig.password,
    }

    const response = await axios({
      url: `${ubmsConfig.baseURL}/ubms-foreign/authorize/login`,
      method: 'post',
      data: qs.stringify(params),
      headers: {
        deviceid: 'unknown',
        Authorization: ubmsConfig.authorization,
      },
    })

    const data = response.data
    const { access_token } = data
    storage.set(`${ubmsConfig.storagePrefixKey}accessToken`, access_token)

    return data
  } catch (error) {
    console.error('Failed to refresh access token:', error)
    throw error
  }
}

export default instance
