<template>
  <el-tabs :value="active" v-bind="{...$attrs}" v-on="{...$listeners, 'tab-click': tab}">
    <slot/>
  </el-tabs>
</template>
<script>
import qs from 'qs'
export default {
  name: 'tab-router',
  props: {
    searchKey: {
      type: String,
      default: 'tabrouter'
    },
    lazy: {
      type: Boolean,
      defaule: true
    },
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      active: '',
      panels: [],
      panelsByName: {}
    }
  },
  methods: {
    getAllPanel() {
      const data = {}
      const routes = []
      this.panels = this.$slots.default.filter(item => {
        const isPanel = item.tag && item.tag.indexOf('ElTabPane') > -1
        if (isPanel && item.child) {
          data[item.child.name] = item.child
        }
        return isPanel
      })
      const search = qs.parse(location.hash.split('?')[1])
      if (this.panels.length) {
        this.$nextTick(() => {
          this.active= search[this.searchKey] || this.panels[0].child?.name
        })
      }
      this.panelsByName = data
    },
    tab(item, evt) {
      const { query } = this.$route
      const search = qs.stringify({
        ...query,
        [this.searchKey]: item.name
      })
      this.active = item.name
      history.replaceState(location.pathname, null, `#${this.$route.path}?${search}`)
      const parentClick = this.$listeners['tab-click']
      if (parentClick) {
        parentClick(item, evt)
      }
    }
  },
  beforeUpdate() {
    this.getAllPanel()
  },
  mounted() {
    this.getAllPanel()
  }
}
</script>
<style lang="less" scoped>

</style>
