/*
 * @Author: wjc
 * @Date: 2024-06-05 10:21:23
 * @LastEditors: wjc
 * @LastEditTime: 2024-06-25 15:12:03
 * @Description:
 */
import type { App } from 'vue'
import qs from 'qs'
import type { ILogin } from '@/models/userTypes'
import { useUserStore } from '@/stores/modules/userStore'
import { checkStatus } from './checkStatus'

export type IRequestOptions = UniApp.RequestOptions & {
  query?: Record<string, any>
}

const interceptor = {
  //  请求前拦截
  invoke(options: IRequestOptions) {
    const userStore = useUserStore()
    // api 处理
    options.url = `${import.meta.env.VITE_APP_BASE_API}${options.url}`
    // 查询参数处理
    if (options.query) {
      const query = qs.stringify(Object.assign({}, options.query), {
        addQueryPrefix: true,
      })
      options.url += query
    }
    // 10 秒请求超时
    options.timeout = 100000
    // 请求头标识符
    const sysInfo = uni.getSystemInfoSync()
    const storageLoginInfo: ILogin = userStore.storageLoginInfo
    options.header = {
      ...options.header,
      version: sysInfo.appVersion, // 版本号
      platform: sysInfo.osName ?? 'app', // 所用系统
    }
    // entCode
    if (storageLoginInfo && storageLoginInfo.entCode) {
      options.header.entcode = storageLoginInfo.entCode
    }
    // token
    if (userStore.token) {
      options.header.Authorization = `Bearer ${userStore.token}`
    }
  },
}

export function setupInterceptor(app: App) {
  app.use({
    install() {
      uni.addInterceptor('request', interceptor)
    },
  })
}

export const request = <T>(options: IRequestOptions) => {
  return new Promise<T>((resolve, reject) => {
    uni.request({
      responseType: 'json',
      ...options,
      success(res) {
        if (res.statusCode === 200 || res.statusCode === 201) {
          resolve(res.data as T)
        } else {
          checkStatus(res)
          reject(res)
        }
      },
    })
  })
}
