<template>
  <div class="button-group-collapse">
    <el-button-group>
      <RenderDom
        v-for="(btn, index) in visibleButtons"
        :key="index"
        :v-node="btn"
        :custom-style="{'marginRight':`${offset}px`}"
      >
      </RenderDom>

      <el-dropdown v-if="collapse" ref="dropdown" trigger="click" placement="bottom">
        <el-button type="text" :style="{'margin-left': `${offset}px`}">...</el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="(btn,index) in collapseButtons" :key="index" :ref="`dom-${index}`" @click.native="handleItemClick($event,index)">
            <RenderDom
              :v-node="btn"
            >
            </RenderDom>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

    </el-button-group>
  </div>
</template>

<script>
import RenderDom from './RenderDom'
export default {
  name: 'YCollapseButtonGroup',
  components: {
    RenderDom
  },
  props: {
    // buttons: {
    //   type: Array,
    //   required: true
    // },
    maxVisible: {
      type: Number,
      default: 2
    },
    offset: {
      type: Number,
      default: 6
    }
  },
  data() {
    return {
      buttons: []
    }
  },
  computed: {
    collapse() {
      return this.buttons.length > this.maxVisible
    },
    visibleButtons() {
      return this.buttons.slice(0, this.maxVisible)
    },
    // 被折叠的按钮
    collapseButtons() {
      const len = this.buttons.length
      return this.maxVisible < len ? this.buttons.slice(this.maxVisible - len) : []
    }

  },
  mounted() {
    this.buttons = this.$slots.default
  },
  updated() {
    // 由于无法监听$slots.default变化，所以只有在updated中动态修改buttons
    if (this.buttons !== this.$slots.default) {
      this.buttons = this.$slots.default
    }
  },
  methods: {
    // 解决点击按钮外区域无法响应点击事件&&解决点击事件会响应两次
    handleItemClick(e, index) {
      if (e.target.className === 'el-dropdown-menu__item') {
        const dropdownItem = this.$refs[`dom-${index}`][0]
        if (dropdownItem) {
          const click = this.getClickEvent(dropdownItem.$children)
          if (click) {
            click()
          } else {
            console.log('未找到点击事件')
          }
        }
      }
    },
    // 查找点击事件
    getClickEvent(children) {
      if (children?.length) {
        const targetChild = children.find(c => c.$listeners.click)
        if (targetChild) {
          return targetChild.$listeners.click
        } else {
          return this.getClickEvent(children[0].$children)
        }
      }
    }
  }
}
</script>

<style scoped>
.button-group-collapse {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
