//  uniapp 返回 入参为堆栈
export function goBack(delta = 1) {
  console.log(delta)

  uni.navigateBack({ delta })
}

// uniapp 跳转页面 可携带参数
// 示例： toPage('/pages/productDetail/productDetail', { id: 123 })
export function toPage(url: string, params?: Record<string, any>, isRedirect = false) {
  let targetUrl = url
  const tabBarPages = ['/pages/index/index', '/pages/income/income', '/pages/mine/mine']

  if (params && Object.keys(params).length > 0) {
    const data = JSON.stringify(params)
    targetUrl = `${url}?params=${encodeURIComponent(data)}`
  }
  if (tabBarPages.includes(url)) {
    uni.switchTab({
      url: targetUrl,
    })
  }
  else {
    if (isRedirect) {
      uni.redirectTo({
        url: targetUrl,
      })
    }
    else {
      uni.navigateTo({
        url: targetUrl,
      })
    }
  }
}

// page参数解析方法
export function getPageParams(options: any) {
  if (options && options.params) {
    try {
      return JSON.parse(decodeURIComponent(options.params))
    }
    catch (e) {
      console.error('解析页面参数失败:', e)
      return {}
    }
  }
  return {}
}
