<template>
  <div class="dashboard" :data-language="language">
    <div v-if="activeName">
      <el-tabs v-model="activeName">
        <el-tab-pane
          v-for="item in tablePermissions"
          :key="item.component"
          :label="item.title"
          :name="item.component"
        />
        <component :is="activeName" />
      </el-tabs>
    </div>
    <div v-else>
      <div class="welcome">
        <img src="@/assets/welcome.png" alt="">
        {{ $t('pages.dashboard.welcome') }}
      </div>
    </div>
  </div>
</template>

<script>
import Introduction from './introduction'
import DashboardCharts from './dashboard-charts'
import { mapGetters } from 'vuex'
import { deepClone } from '@/utils'

export default {
  name: 'Dashboard',
  components: { DashboardCharts, Introduction },
  data() {
    return {
      activeName: '',
      tables: {
        'dashboard:generalize': {
          titleKey: 'pages.dashboard.tabs.overview',
          component: 'Introduction',
          sort: 1
        },
        'dashboard:dashboard:charts': {
          titleKey: 'pages.dashboard.tabs.dataCharts',
          component: 'DashboardCharts',
          sort: 2
        }
      }
    }
  },
  computed: {
    ...mapGetters(['buttonPermissions', 'language']),
    tablePermissions() {
      const language = this.language
      if (!this.buttonPermissions || this.buttonPermissions.length <= 0) {
        return []
      }
      const buttonPermissions = deepClone(this.buttonPermissions)
      buttonPermissions.push('dashboard:generalize')
      const tabMap = {}
      for (let index = 0; index < buttonPermissions.length; index++) {
        const permission = buttonPermissions[index]
        if (!permission) {
          continue
        }
        const item = this.tables[permission]
        if (item) {
          tabMap[item.sort] = {
            ...item,
            title: this.$t(item.titleKey)
          }
        }
      }

      const sortKeys = Object.keys(tabMap).sort((a, b) => {
        return tabMap[a].sort - tabMap[b].sort
      })

      return sortKeys.map(index => {
        return tabMap[index]
      })
    }
  },
  watch: {
    tablePermissions(newVal) {
      if (!newVal || newVal.length <= 0) {
        this.activeName = ''
        return
      }
      this.activeName = newVal[0].component
    }
  },
  created() {
    if (this.tablePermissions && this.tablePermissions.length > 0) {
      this.activeName = this.tablePermissions[0].component
    }
  }
}
</script>

<style scoped lang="scss">
.welcome {
  width: 60%;
  padding: 100px 0;
  margin: auto;
  color: #666666;

  img {
    width: 100%;
  }
}
</style>
