import { useMemberStore } from '@/stores'
import { Decrypt, Encrypt } from './utils'
import { userLoginApi } from '@/services/home'

//引入 pinia 。。登录后将信息储存到pinia

// const baseUrl = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
// const baseUrl = 'https://test.jue-ming.com:8084'
// const baseUrl = 'http://10.113.248.3:8086'

// const baseUrl = 'http://g9yv4d.natappfree.cc'
//服务器
// const baseUrl = 'http://i9p32r.natappfree.cc'
const baseUrl = 'http://n823va.natappfree.cc'
export const imgUrl = 'http://10.113.248.3:8086/file/show?filePath='
export const appId = 'wx658b72887c56f6b4'
// 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='

let temp_request: any[] = [],
  is_freshing = false
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',
    }
    //判断如果请求体里有data//且data不为空
    if ('data' in options) {
      //如果包含data属性
      // options.data = { data: Encrypt(JSON.stringify(options.data)) }
      options.data = { data: options.data }
    }
    console.log(options)
    //添加 token 请求头标识
    const memberStore = useMemberStore()
    // const token = memberStore.profile?.token
    const token = memberStore.token
    options.header.Authorization = token ? `Bearer ${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) => {
  let params_ = option
  // console.log(option?.data)
  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(JSON.parse(Decrypt(res.data)))
          // const a: any = res.data
          // resolve(a)

          // debugger
          // resolve(a)

          // resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          //当token过期后弹出确认再次登录的提示框
          //如果点击确定再次调用登录接口
          if (!is_freshing) {
            //调用登录接口
            refresh()
          } else {
            resolve(
              new Promise((resol) => {
                temp_request.push(() => {
                  resol(http(params_))
                })
              }),
            )
          }

          //清理用户信息
          //跳转到登录页
          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: '网络错误',
        })
        //网络错误
      },
    })
  })
}

const refresh = () => {
  is_freshing = true
  uni.login({
    success: (res) => {
      if (res.errMsg === 'login:ok') {
        //调用登录接口
        //获取到code后
        loginHttp(res.code)
      }
    },
  })
}

const loginHttp = async (code: string) => {
  const res = await userLoginApi({ code: code })

  //登录成功后需要将 is_refresh 状态改为false
  //然后回调
  if (res.data) {
    console.log(res.data)
  } else {
    is_freshing = false
    temp_request.map((cb) => cb())
    // 清空temp_request
    temp_request = []
  }
}
