/* eslint-disable no-param-reassign */
import db from '../utils/db'
import dict from '../utils/dict'
import page from '../utils/page'
import qs from 'qs'

// 页面路径常量
export const route_login = '/pages/login/index'
export const route_home = '/pages/home/index'

// 免token的路由
const noTokenRoutes = [route_login]

export interface _RouterNoPathOptions {
  query?: any
}

export type _RouterOptions = {
  path: string
} & _RouterNoPathOptions

export type RouterOptions = _RouterOptions | string

// 封装 navigateTo
function navigateTo(options: RouterOptions) {
  const to = beforeEach(options)
  if (!to) return
  uni.navigateTo(to)
}

// 封装 redirectTo
function redirectTo(options: RouterOptions) {
  const to = beforeEach(options)
  if (!to) return
  uni.redirectTo(to)
}

// 封装 switchTab
function switchTab(options: RouterOptions) {
  const to = beforeEach(options)
  if (!to) return
  uni.switchTab(to)
}

// 封装 reLaunch
function reLaunch(options: RouterOptions) {
  const to = beforeEach(options)
  if (!to) return
  uni.reLaunch(to)
}

// 封装 navigateBack
function navigateBack(options?: any) {
  // const to = beforeEach(options)
  // if (!to) return
  uni.navigateBack(options)
}

// 去登录页面
function toLogin(options?: _RouterNoPathOptions) {
  // db.pop('token')
  reLaunch({
    ...options,
    path: route_login,
  })
}

// 去首页
function toHome(options?: _RouterNoPathOptions) {
  reLaunch({
    ...options,
    path: route_home,
  })
}

interface RouterBeforeOptions {
  from: _RouterOptions
  to: _RouterOptions
}

// 自定义路由守卫函数
function beforeEach(options: RouterOptions) {
  const beforeOptions: RouterBeforeOptions = {} as any
  if (typeof options === 'string') {
    // 对字符串参数进行处理
    options = {
      path: options,
    }
  }
  if (options.path) {
    beforeOptions.to = options
  }
  // 对from进行处理
  beforeOptions.from = {
    path: page.getPagePath(),
  }

  // 最终封装成options = {from:{url}, to:{url}}
  const { from, to } = beforeOptions

  // 登录页面下跳转登录页面，跳转到首页
  if (from.path === to.path && to.path === route_login) {
    return false
  }

  console.log('beforeEach', from, to)

  // 执行跳转
  const token = db.get('token')
  if (!noTokenRoutes.includes(to.path) && !token) {
    console.log('token 过期')
    toLogin(to)
    return false
  }

  let toUrl = to.path
  if (to.query) {
    toUrl += '?' + qs.stringify(to.query)
  }
  const pageObj = {
    ...to,
    url: toUrl,
  }
  console.log('跳转', pageObj)
  return pageObj
}

// 导出封装的方法
export default {
  navigateTo,
  redirectTo,
  switchTab,
  reLaunch,
  navigateBack,
  toLogin,
  toHome,
}
