<template>
  <div>
    <el-button v-for="item in notDropdownList" :disabled="typeof item.disabled === 'function' ? item.disabled(scopeData) : item.disabled" v-bind="{ type: 'text', ...item.props }" :key="item.text" @click="handleCommand(item)">{{ item.text }}</el-button>
    <el-dropdown v-if="buttonArray.length > max" v-bind="{ type: 'text', ...dropdownProps }" @click="() => emitEventHandler('click')" @command="handleCommand" @visible-change="bool => emitEventHandler('visible-change', bool)">
      <span class="el-dropdown-link">
        <i class="iconfont icon-more"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item v-for="item in dropdownList" :class="{ 'item-disabled': typeof item.disabled === 'function' ? item.disabled(scopeData) : item.disabled }" :command="item" :key="item.text">
          <el-button :disabled="typeof item.disabled === 'function' ? item.disabled(scopeData) : item.disabled" v-bind="{ type: 'text', ...item.props }">{{ item.text }}</el-button>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>

<script>
export default {
  name: 'dm-dropdown',
  components: {},
  props: {
    dropdownProps: {
      //Dropdown Attributes
      type: Object,
      default: () => {}
    },
    configs: {
      type: Array,
      default: () => []
    },
    max: {
      type: [Number, String],
      default: 3
    },
    scopeData: Object
  },
  methods: {
    emitEventHandler(event) {
      this.$emit(event, ...Array.from(arguments).slice(1));
    },
    handleCommand(config) {
      if (typeof config.disabled == 'function' ? config.disabled(this.scopeData) : config.disabled) return;
      config.handler && config.handler(this.scopeData);
      this.emitEventHandler('command', { config, data: this.scopeData });
    }
  },
  computed: {
    buttonArray() {
      return this.configs.filter(item => {
        let visible = item.visible;
        if (typeof visible === 'boolean') {
          return item.visible;
        } else if (typeof visible === 'function') {
          return item.visible(this.scopeData);
        } else {
          return true;
        }
      });
    },
    notDropdownList() {
      return this.buttonArray.length > this.max ? this.buttonArray.slice(0, this.max - 1) : this.buttonArray;
    },
    dropdownList() {
      return this.buttonArray.length > this.max ? this.buttonArray.slice(this.max - 1) : [];
    }
  }
};
</script>
<style lang="scss" scoped>
.el-dropdown-link {
  cursor: pointer;
  color: #2f54eb;
}
.el-button--text + .el-dropdown {
  margin-left: 8px;
}
.item-disabled {
  cursor: not-allowed;
}
</style>
