import { useAppStore } from '../../store'
import {useUserStore} from '../../store'

import errorCode from './errorCode'
import Qs from '@/common/utils/qs'

console.log('useAppStore',useAppStore())
const appStore = useAppStore()
const userStore = useUserStore()

let count = 0
let timer = null

export const isRelogin = { show: false }
// 封装请求wx.request
export default (
   {
    url = '',
    data = null,
    params = null,
    method = 'POST',
    loading = true, // 显示加载动画
    errorReject = true, // res.data.httpStatusCode !== 1
    errorToast = false, // res.data.httpStatusCode !== 1
    header = {}
  } = {}
) => {
  if (loading) {
    count++
    clearTimeout(timer)
    // uni.showNavigationBarLoading()
    // uni.showLoading({ title: '加载中', mask: true })
  }
  // 序列化前 携带memberid 不用在业务代码上手写了
  // if (Object.prototype.toString.call(data) === '[object object]') {
  //   data[Object.keys(data)[0]].token = store.state.token
  // }

  return new Promise((resolve, reject) => {
    const preAuth = userStore.accessToken ? 'Bearer ' : 'Basic YXBwOmFwcA=='
    uni.request({
      url: appStore.API_PREFIX + url,
      // data: Qs.stringify(data, {allowDots: true}), // 序列化
      // data: Qs.stringify(data),
      data: data ?? params,
      method: method,
      header: {
        Authorization: preAuth + userStore.accessToken,
        'TENANT-ID': '1534731312360464386',
        ['Content-Type']: 'application/json;charset=UTF-8',
        ...header
      },
      success(res) {

        
        // 未设置状态码则默认成功状态
        const code = res.data.code || 200
        // 获取错误信息
        const msg = errorCode[code] || res.data.msg || errorCode['default']

        // if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
        //   resolve(res.data)
        // }

            if (code === 5002) {
              uni.showToast({
                title: msg,
                icon: 'none'
              })
              setTimeout(()=> {
                uni.switchTab({
                  url:'/pages/mine/index',
                })
              }, 1000);
       
              
              return reject(res.data)
            }
            if (code === 401) {
              if (!isRelogin.show) {
                isRelogin.show = true
                // 强制获取用户信息
                userStore.getInfo(true).then(() => {
                  // const searchParam = Qs.parse(decodeURIComponent(location.search.replace(/\?/, ''))) // urlParams {object}
                  // searchParam.rand = Math.round(Math.random() * 100000000)
                  // const paramsResult = Qs.stringify(searchParam)
                  // location.replace(`${location.origin}${location.pathname}?${paramsResult}`)
                   // 获取当前页面路径和参数
                    const pages = getCurrentPages()
                    const currentPage = pages[pages.length - 1]
                    const currentRoute = currentPage.route
                    const currentOptions = currentPage.options
                    
                    // 解析并修改参数
                    const searchParam = Qs.parse(currentOptions)
                    searchParam.rand = Math.round(Math.random() * 100000000)
                    
                    // 重新跳转（保留路径栈）
                    uni.redirectTo({
                      url: `/${currentRoute}?${Qs.stringify(searchParam)}`
                    })
                  resolve(res.data)
                })
              }
              // location.replace(`${location.origin}${import.meta.env.BASE_URL}login`)
              // return reject('无效的会话，或者会话已过期，请重新登录。')
              return reject(res.data)
            } else if (code === 500) {
              uni.showToast({
                title: msg,
                icon: 'none',
                duration: 1500
              })
              console.log(123)
              setTimeout(() => {
               reject(new Error(msg))
              }, 1500);
              
              
            } else if (code === 601) {
              uni.showToast({
                title: msg,
                icon: 'none',
              })
              reject(new Error(msg))
            } else if (code !== 200) {
              console.log('12345')
              uni.showToast({
                title: msg,
                icon: 'none'
              })
             
              reject('error')
            }
            resolve(res.data)
      },
      fail(err) {

        reject(err)
      },
      complete: () => {
      //  uni.hideLoading()
      }
    })
  })
}

