const App = getApp()
Component({
  data: {
    selected: App.globalData.selectedIndex,
    color: '#3D3D3D',
    selectedColor: '#3D3D3D',
    list: [
      {
        pagePath: '/pages/index/index',
        iconPath: '/static/tabbar/home_icon.png',
        selectedIconPath: '/static/tabbar/home_active.png',
        text: '首页'
      },
      {
        pagePath: '/pages/ai/index',
        iconPath:
          'https://pay-prod-1369486729.cos.ap-guangzhou.myqcloud.com/uploads/cs-test/01KN63WTGSX2T5X8N233CJ5K0Q.png',
        selectedIconPath:
          'https://pay-prod-1369486729.cos.ap-guangzhou.myqcloud.com/uploads/cs-test/01KN63WTGSX2T5X8N233CJ5K0Q.png',
        text: '管家在线'
      },
      {
        pagePath: '/pages/me/index',
        iconPath: '/static/tabbar/news_icon.png',
        selectedIconPath: '/static/tabbar/news_active.png',
        text: '我的'
      }
    ]
  },
  lifetimes: {
    attached: function () {
      // 监听路由变化，自动更新tab-bar选中状态
      const updateTabBar = () => {
        let _this = this
        const pages = getCurrentPages()
        const currentPage = pages[pages.length - 1]
        console.log('currentList', getApp().globalData, currentPage)
        if (currentPage && this.data.list) {
          const currentPath = currentPage.route
          const index = this.data.list.findIndex(item => item.pagePath === `/${currentPath}`)
          if (index !== -1) {
            this.setData({
              selected: index,
              list: this.data.list
            })
            App.globalData.selectedIndex = index
          }
          if (!getApp().globalData.menuList) {
            getApp().globalData.menuList = this.data.list
          }
        }
      }
      // 初始化时执行一次
      updateTabBar()
      // 注册路由监听
      wx.onAppRoute(updateTabBar)
    }
  },
  ready() {
    this.setData({
      list: getApp().globalData.menuList,
      selected: App.globalData.selectedIndex || 0
    })
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      App.globalData.selectedIndex = data.index
      console.log('App.globalData.selectedIndex', data)
      this.setData({
        selected: data.index,
        list: getApp().globalData.menuList
      })
      console.log('switchTab fail', url)
      wx.switchTab({
        url,
        fail: res => {
          // wx.navigateTo({url})
          console.log('switchTab fail', res)
        }
      })
    }
  }
})
