import { useMemberStore } from '@/stores'

// const baseUrl = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
const baseUrl = 'https://test.jue-ming.com:8084'
export const imgUrl = 'https://test.jue-ming.com:8084/file/show?filePath='
export const mediaUrl = 'https://test.jue-ming.com:8084/file/show/media?filePath='
// const baseUrl = 'http://10.113.248.3:8080'
// export const imgUrl = 'http://10.113.248.3:8080/file/show?filePath='
const httpInterceptor = {
  //拦截前触发
  invoke(options: UniApp.RequestOptions) {
    //拼接地址
    if (!options.url.startsWith('http')) {
      options.url = baseUrl + options.url
    }
    //请求时间
    options.timeout = 10000
    options.header = {
      ...options.header,
      'source-client': 'miniapp',
    }
    //添加 token 请求头标识
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
  },
}

uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

// export default baseUrl

//请求函数
/**
 * @param  UniApp.RequestOptions
 * @returns Promise
 */

interface Data<T> {
  code: string
  msg: string
  data: T
}

export const http = <T>(option: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...option,
      success(res) {
        //获取状态码
        // res.ststusCode
        if (res.statusCode >= 200 && res.statusCode < 300) {
          //访问成功
          // eslint-disable-next-line no-debugger
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          //清理用户信息
          //跳转到登录页
          const memberStore = useMemberStore()
          memberStore.clearProfile()
          uni.navigateTo({
            url: '/src/pages/index/index',
          })
          reject(res)
        } else {
          // (res.data as Data<T>).msg
          uni.showToast({
            icon: 'none',
            title: (res.data as Data<T>).msg || '请求错误请稍后再试',
          })
          reject(res)
        }
      },
      //响应失败，网络断开
      fail(err) {
        console.log(err)
        uni.showToast({
          icon: 'none',
          title: '网络错误',
        })
        //网络错误
      },
    })
  })
}
