const commonTabs = [
  { pagePath: 'pages/home/home', text: '首页', icon: '/static/tabbar/home.png', activeIcon: '/static/tabbar/home-active.png' },
  { pagePath: 'pages/task/task', text: '任务', icon: '/static/tabbar/task.png', activeIcon: '/static/tabbar/task-active.png' },
  { pagePath: 'pages/my/my', text: '我的', icon: '/static/tabbar/my.png', activeIcon: '/static/tabbar/my-active.png' },
]

const dispatchTabs = [
  { pagePath: 'pages/home/home', text: '首页', icon: '/static/tabbar/home.png', activeIcon: '/static/tabbar/home-active.png' },
  { pagePath: 'pages/schedule/schedule', text: '排班', icon: '/static/tabbar/schedule.png', activeIcon: '/static/tabbar/schedule-active.png' },
  { pagePath: 'pages/task/task', text: '任务', icon: '/static/tabbar/task.png', activeIcon: '/static/tabbar/task-active.png' },
  { pagePath: 'pages/my/my', text: '我的', icon: '/static/tabbar/my.png', activeIcon: '/static/tabbar/my-active.png' },
]

const constructionTabs = [
  { pagePath: 'pages/home/home', text: '首页', icon: '/static/tabbar/home.png', activeIcon: '/static/tabbar/home-active.png' },
  { pagePath: 'pages/task/task', text: '任务', icon: '/static/tabbar/task.png', activeIcon: '/static/tabbar/task-active.png' },
  { pagePath: 'pages/my/my', text: '我的', icon: '/static/tabbar/my.png', activeIcon: '/static/tabbar/my-active.png' },
]

function getRole() {
  try {
    const userStr = wx.getStorageSync('user')
    if (userStr) {
      const user = JSON.parse(userStr)
      return user.role || ''
    }
  } catch (e) {
    // ignore
  }
  return ''
}

Component({
  data: {
    selected: 0,
    tabs: commonTabs,
  },

  lifetimes: {
    attached() {
      const role = getRole()
      let tabs = commonTabs
      if (role === 'dispatch') tabs = dispatchTabs
      else if (role === 'construction') tabs = constructionTabs
      this.setData({ tabs })
      this.updateSelected()
    },
  },

  pageLifetimes: {
    show() {
      this.updateSelected()
    },
  },

  methods: {
    switchTab(e) {
      const { index, pagepath } = e.currentTarget.dataset
      const url = '/' + pagepath
      this.setData({ selected: index })
      wx.switchTab({ url })
    },

    updateSelected() {
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      const route = currentPage ? currentPage.route : ''
      const idx = this.data.tabs.findIndex(t => t.pagePath === route)
      if (idx >= 0) {
        this.setData({ selected: idx })
      }
    },

    setSelected(index) {
      this.setData({ selected: index })
    },
  },
})
