<template>
  <el-tabs
    :value="active"
    v-bind="{ ...$attrs }"
    v-on="{ ...$listeners, 'tab-click': tab }"
  >
    <slot />
  </el-tabs>
</template>
<script>
import qs from "qs";
import merge from 'webpack-merge'
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: {},
    };
  },
  watch: {
    active() {
      this.$emit('change', this.active)
    }
  },
  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(() => {
          const names = this.panels.map(item => item.child?.name)
          const sk = search[this.searchKey]
          let key = sk && names.includes(sk) ? sk : names[0]
          this.active = key;
        });
      }
      this.panelsByName = data;
    },
    tab(item, evt) {
      let { query } = this.$route;
      const search = qs.stringify({
        ...query,
        [this.searchKey]: item.name,
      });
      this.active = item.name;
      this.$router.replace({
        query: merge(this.$route.query, {
            ...query,
          [this.searchKey]: item.name,
        }),
      });
      this.$store.dispatch("addVisitedViews",  this.$route);
      const parentClick = this.$listeners["tab-click"];
      if (parentClick) {
        parentClick(item, evt);
      }
    },
  },
  beforeUpdate() {
    this.getAllPanel();
  },
  mounted() {
    this.getAllPanel();
  },
};
</script>
<style lang="less" scoped>
</style>
