<template>
  <zj-page-container>
    <el-tabs v-model="activeKey" type="card" @tab-click="tabClick" closable @tab-remove="removeTab">
      <el-tab-pane v-for="(item, index) in activeList" :key="item.key" :label="item.label || item.key"
        :name="item.key"></el-tab-pane>
    </el-tabs>
    <zj-page-fill>
      <slot :activeKey="showActiveKey" />
    </zj-page-fill>
  </zj-page-container>
</template>

<script>
export default {
  name: "TabPage",
  props: {
    defaultActives: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      activeKey: this?.defaultActives?.length ? this?.defaultActives?.[0]?.key : "",
      oldActiveKey: this?.defaultActives?.length ? this?.defaultActives?.[0]?.key : "",
      activeList: [...this.defaultActives]
    };
  },
  computed: {
    showActiveKey() {
      var data = this.activeList.find(item => item.key == this.oldActiveKey)
      return data?.activeKey || data?.key || ""
    }
  },
  methods: {
    // 点击
    tabClick(tab) {
      if (this.oldActiveKey != (tab.name || tab)) {
        this.activeList.find(item => item.key == this.oldActiveKey)?.closeEvent?.()
        this.$nextTick(() => {
          this.activeList.find(item => item.key == (tab.name || tab))?.triggerEvent?.()
          this.$nextTick(() => {
            this.activeKey = (tab.name || tab)
            this.oldActiveKey = this.activeKey
          })
        })
      }
    },
    // 添加
    addTab(tabObj) {
      if (tabObj.key === undefined) {
        console.error("缺少")
        return
      }
      for (var i = 0; i < this.activeList.length; i++) {
        if (this.activeList[i].key === tabObj.key) {
          this.activeList.splice(i, 1, tabObj);
          this.$nextTick(() => {
            this.tabClick(tabObj.key)
          })
          return
        }
      }
      this.activeList.push(tabObj)
      this.$nextTick(() => {
        this.tabClick(tabObj.key)
      })
    },
    // 删除
    removeTab(tab) {
      var i;
      for (i = 0; i < this.activeList.length; i++) {
        if (this.activeList[i].key === tab) {
          if (this.activeList[i].essential) {
            this.$message.warning(`${this.activeList[i].label || this.activeList[i].key}是必须页面不能删除！`)
            return
          }
          this.activeList[i]?.closeEvent?.()
          this.activeList.splice(i, 1);
          break
        }
      }
      if (this.activeList[i]) {
        this.tabClick(this.activeList[i].key)
        return
      }
      if (this.activeList[i - 1]) {
        this.tabClick(this.activeList[i - 1].key)
        return
      }
      this.tabClick("")
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-tabs__header{
  margin: 0 0 0 0 !important;
}
</style>