import { CustomRequestOptions } from '@/interceptors/request'
import { useUserStore } from '@/store/user'
import { useAppStore } from '@/store/app'
import { formatBackendJson } from '@/utils'

export const http = <T>(options: CustomRequestOptions & { formatData?: boolean }) => {
  const userStore = useUserStore()
  const appStore = useAppStore()

  // 1. 返回 Promise 对象
  return new Promise<IResData<T>>((resolve, reject) => {
    uni.request({
      ...options,
      header: Object.assign(
        {
          token: `${appStore.appInfo.token}`,
        },
        options.header,
      ),
      dataType: 'json',
      // #ifndef MP-WEIXIN
      responseType: 'json',
      // #endif
      // 响应成功
      success(res) {
        console.log('响应成功:', options, res)

        const { Status, Message, Data } = res.data as any

        // 2. http的状态码 状态码 2xx，参考 axios 的设计
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // 3. 业务状态码
          switch (Status) {
            case 0: // 请求成功
              // 如果不需要格式化数据，则直接返回
              if (!options.formatData) {
                resolve(res.data as IResData<T>)
              } else {
                // 如果需要格式化数据，则格式化数据
                resolve({
                  Status: (res.data as any).Status,
                  Message: (res.data as any).Message,
                  Data: formatBackendJson((res.data as any).Data),
                  OtherData: (res.data as any).OtherData,
                } as IResData<T>)
              }
              break
            case -1: // 请求失败
              uni.showToast({
                icon: 'none',
                title: Message || '请求错误',
                duration: 3000,
              })
              break
            case -2: // token过期
              // 判断是否已登录
              if (appStore.isLogined) {
                uni.showToast({
                  icon: 'none',
                  title: Message || '请求错误',
                  duration: 3000,
                  success: () => {
                    userStore.clearUserInfo()
                    appStore.clearAppInfo()
                    uni.navigateTo({ url: '/pages-sub/auth/index' })
                  },
                })
              }
              break
            default:
              break
          }
        } else if (res.statusCode === 401) {
          // 401错误  -> 清理用户信息，跳转到登录页
          userStore.clearUserInfo()
          appStore.clearAppInfo()
          uni.navigateTo({ url: '/pages-sub/auth/index' })
          reject(res)
        } else {
          // 其他错误 -> 根据后端错误信息轻提示
          !options.hideErrorToast &&
            uni.showToast({
              icon: 'none',
              title: (res.data as IResData<T>).Message || '请求错误',
              duration: 3000,
            })
          reject(res)
        }
      },
      // 响应失败
      fail(err) {
        uni.showToast({
          icon: 'none',
          title: '网络错误，换个网络试试',
          duration: 3000,
        })
        reject(err)
      },
    })
  })
}

/**
 * GET 请求
 * @param url 后台地址
 * @param query 请求query参数
 * @returns
 */
export const httpGet = <T>(
  url: string,
  query?: Record<string, any>,
  options?: {
    formatData?: boolean // 是否格式化数据  带label的数据转json
  },
) => {
  return http<T>({
    url,
    query,
    method: 'GET',
    ...options,
  })
}

/**
 * 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
