import { CustomRequestOptions } from '@/interceptors/request'
import type { IResData } from '@/typings'
import NProgress from '@/utils/nprogress'
import { SmCrypto } from '@/utils/crypto'

const smCrypto = new SmCrypto(import.meta.env.VITE_PRIVATE_KEY, import.meta.env.VITE_PUBLIC_KEY)
export const http = <T>(options: CustomRequestOptions) => {
  // let resdata = options.data
  // console.info('🚀 ~ 请求数据', resdata)
  // options.data = smCrypto.doEncrypt(options.data)
  NProgress.start()
  // 1. 返回 Promise 对象
  return new Promise<IResData<T>>((resolve, reject) => {
    // console.log('当前语言：', uni.getStorageSync('lang'))
    uni.request({
      ...options,
      header: {
        Authorization: `Bearer ${uni.getStorageSync('token')}` || '',
        lang: uni.getStorageSync('lang') || 'en',
      },
      timeout: 50000,
      //
      dataType: 'json',
      // #ifndef MP-WEIXIN
      responseType: 'json',
      // #endif
      // 响应成功
      success(res) {
        // res.data = smCrypto.doDecrypt(res.data)
        NProgress.done()
        // 状态码 2xx，参考 axios 的设计
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // 2.1 提取核心数据 res.data
          resolve(res.data as IResData<T>)
        } else if (res.statusCode === 401) {
          // 401错误  -> 清理用户信息，跳转到登录页
          // userStore.clearUserInfo()
          // uni.navigateTo({ url: '/pages/login/login' })
          reject(res)
        } else {
          // 其他错误 -> 根据后端错误信息轻提示
          !options.hideErrorToast &&
            uni.showToast({
              icon: 'none',
              title: (res.data as IResData<T>).msg || 'inter error',
            })
          reject(res)
        }
      },
      // 响应失败
      fail(err) {
        NProgress.done()
        uni.showToast({
          icon: 'none',
          title: 'inter error please try again',
        })
        reject(err)
      },
    })
  })
}

/**
 * GET 请求
 * @param url 后台地址
 * @param query 请求query参数
 * @returns
 */
export const httpGet = <T>(url: string, query?: Record<string, any>) => {
  return http<T>({
    url,
    query,
    method: 'GET',
  })
}

/**
 * POST 请求
 * @param url 后台地址
 * @param data 请求body参数
 * @param query 请求query参数，post请求也支持query，很多微信接口都需要
 * @returns
 */
export const httpPost = <T>(
  url: string,
  data?: Record<string, any>,
  query?: Record<string, any>,
) => {
  return http<T>({
    url,
    query,
    data,
    method: 'POST',
  })
}

http.get = httpGet
http.post = httpPost
