const defaultList = [
  {
    pagePath: '/pages/tabbar/index',
    iconPath: '/static/images/icon_sy.png',
    selectedIconPath: '/static/images/icon_syf.png',
    text: '首页'
  },
  {
    pagePath: '/pages/tabbar/sort',
    iconPath: '/static/images/icon_fl.png',
    selectedIconPath: '/static/images/icon_flf.png',
    text: '分类'
  },
  {
    pagePath: '/pages/tabbar/shop',
    iconPath: '/static/images/icon_gwc.png',
    selectedIconPath: '/static/images/icon_gwcf.png',
    text: '购物车'
  },
  {
    pagePath: '/pages/tabbar/me',
    iconPath: '/static/images/icon_wd.png',
    selectedIconPath: '/static/images/icon_wdf.png',
    text: '我的'
  }
]

const promotionList = [
  {
    pagePath: '/pages/tabbar/index',
    iconPath: '/static/images/icon_sy.png',
    selectedIconPath: '/static/images/icon_syf.png',
    text: '首页'
  },
  {
    pagePath: '/pages/tabbar/shop',
    iconPath: '/static/images/icon_gwc.png',
    selectedIconPath: '/static/images/icon_gwcf.png',
    text: '榜单'
  },
  {
    pagePath: '/pages/tabbar/sort',
    iconPath: '/static/images/icon_fl.png',
    selectedIconPath: '/static/images/icon_flf.png',
    text: '严选商城'
  },
  {
    pagePath: '/pages/category/category',
    iconPath: '/static/images/icon_fl.png',
    selectedIconPath: '/static/images/icon_flf.png',
    text: '分类'
  },
  {
    pagePath: '/pages/tabbar/me',
    iconPath: '/static/images/icon_wd.png',
    selectedIconPath: '/static/images/icon_wdf.png',
    text: '我的'
  }
]

function isPromotionUnlockedValue(value) {
  return value === true || value === 'true' || value === 1 || value === '1'
}

function normalizePagePath(path) {
  if (!path) {
    return ''
  }
  return path.charAt(0) === '/' ? path : `/${path}`
}

function isTabbarUnlocked() {
  return isPromotionUnlockedValue(wx.getStorageSync('promotionUnlocked'))
}

function getTabList(isPromotionUnlocked) {
  return isPromotionUnlocked ? defaultList : promotionList
}

function isKnownTabPath(path) {
  if (!path) {
    return false
  }
  return defaultList.some(item => item.pagePath === path) || promotionList.some(item => item.pagePath === path)
}

function setTabbarSelectedPath(path) {
  if (!path) {
    return
  }
  wx.setStorageSync('tabbarSelectedPath', path)
}

function getStoredTabbarSelectedPath() {
  return wx.getStorageSync('tabbarSelectedPath') || ''
}

function getCurrentStackPagePath() {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  if (currentPage && currentPage.route) {
    return normalizePagePath(currentPage.route)
  }
  return ''
}

function getCurrentTabBarInstance() {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  if (!currentPage || typeof currentPage.getTabBar !== 'function') {
    return null
  }
  return currentPage.getTabBar()
}

function syncCurrentTabBar(selectedPath = '') {
  const tabBar = getCurrentTabBarInstance()
  if (tabBar && typeof tabBar.syncPromotionStatus === 'function') {
    tabBar.syncPromotionStatus(selectedPath || getCurrentStackPagePath())
  }
}

let routeListenerRegistered = false

Component({
  data: {
    selected: '/pages/tabbar/index',
    list: defaultList,
    isPromotionUnlocked: false,
    isIphoneX: false
  },
  lifetimes: {
    attached() {
      this.registerRouteListener()
      this.syncPromotionStatus(this.getCurrentPagePath())
      this.syncSafeArea()
    }
  },
  pageLifetimes: {
    show() {
      this.syncPromotionStatus(this.getCurrentPagePath())
    }
  },
  methods: {
    registerRouteListener() {
      if (routeListenerRegistered || typeof wx.onAppRoute !== 'function') {
        return
      }
      routeListenerRegistered = true
      wx.onAppRoute((res) => {
        const path = normalizePagePath(res && res.path ? res.path : '')
        if (!isKnownTabPath(path)) {
          return
        }
        setTabbarSelectedPath(path)
        syncCurrentTabBar(path)
      })
    },
    getCurrentPagePath() {
      const currentPath = getCurrentStackPagePath()
      if (isKnownTabPath(currentPath)) {
        return currentPath
      }
      const storedPath = getStoredTabbarSelectedPath()
      if (isKnownTabPath(storedPath)) {
        return storedPath
      }
      return ''
    },
    syncSafeArea() {
      const systemInfo = wx.getSystemInfoSync()
      const safeArea = systemInfo.safeArea || {}
      const isIphoneX = !!safeArea.bottom && safeArea.bottom < systemInfo.screenHeight
      this.setData({ isIphoneX })
    },
    syncPromotionStatus(selectedPath = '') {
      const isPromotionUnlocked = isTabbarUnlocked()
      const list = getTabList(isPromotionUnlocked)
      const currentPath = this.getCurrentPagePath()
      let nextSelected = selectedPath || currentPath || this.data.selected
      const selectedExists = list.some(item => item.pagePath === nextSelected)
      if (!selectedExists) {
        const currentSelectedExists = list.some(item => item.pagePath === currentPath)
        if (currentSelectedExists) {
          nextSelected = currentPath
        } else {
          const storedPath = getStoredTabbarSelectedPath()
          const storedSelectedExists = list.some(item => item.pagePath === storedPath)
          nextSelected = storedSelectedExists ? storedPath : (list[0] ? list[0].pagePath : '')
        }
      }
      const nextData = {
        isPromotionUnlocked,
        list,
        selected: nextSelected
      }
      if (
        this.data.isPromotionUnlocked !== isPromotionUnlocked ||
        this.data.list !== list ||
        this.data.selected !== nextSelected
      ) {
        this.setData({
          ...nextData
        })
      }
      return nextData
    },
    setSelectedByPath(path) {
      const currentPath = path || ''
      const exists = this.data.list.some(item => item.pagePath === currentPath)
      if (exists && this.data.selected !== currentPath) {
        this.setData({ selected: currentPath })
      }
    },
    switchTab(e) {
      const isPromotionUnlocked = isTabbarUnlocked()
      const { index, pagePath } = e.currentTarget.dataset
      const currentList = getTabList(isPromotionUnlocked)
      let item = null
      let selectedPath = ''
      if (pagePath) {
        selectedPath = pagePath
        item = currentList.find(tab => tab.pagePath === pagePath) || null
      }
      if (!item && typeof index !== 'undefined') {
        const currentIndex = Number(index)
        item = currentList[currentIndex]
        selectedPath = item ? item.pagePath : ''
      }
      if (!item) {
        return
      }
      setTabbarSelectedPath(item.pagePath)
      this.setData({
        selected: selectedPath,
        isPromotionUnlocked,
        list: currentList
      })
      wx.switchTab({
        url: item.pagePath
      })
    }
  }
})
