<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;
    },
    async tab(item, evt) {

      if(this.$attrs['before-leave']){
        try{

            await this.$attrs['before-leave']().then(res=>{
              console.log(res)
            })

        }catch(e){
          console.log(e)
        }


      }
      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>
