<template>
  <el-dropdown
    ref="dropDown"
    class="th-dropdown"
    :class="{'th-dropdown-visable': dropdownVisable}"
    v-bind="props"
    @visible-change="handleChangeDropdown"
    @command="handleCommand"
  >
    <el-button
      :disabled="disabled"
      v-bind="{
        size: 'mini',
        type: 'primary',
        ...btnProps
      }"
    >{{ text }}<i v-if="options.length" class="el-icon-arrow-down el-icon--right"></i>
    </el-button>
    <el-dropdown-menu slot="dropdown" :style="{'min-width':dropdownWidth}">
      <el-dropdown-item
        v-for="(item, index) in options"
        :key="index"
        :command="item.value"
        :disabled="item.disabled"
      >{{ item.label }}</el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
export default {
  name: 'ThDropdown',
  props: {
    // 是否带图标显示
    icon: {
      type: String,
      default: ''
    },
    // 按钮显示文本
    text: {
      type: String,
      default: ''
    },
    // 下拉菜单属性
    props: {
      type: Object,
      default: () => ({
        placement: 'bottom-start',
        trigger: 'hover'
      })
    },
    // 触发按钮属性
    btnProps: {
      type: Object,
      default: () => ({})
    },
    // 下拉菜单项列表
    options: {
      type: Array,
      default: () => [
        // {
        //   label: '菜单名称',
        //   value: 'menu_key'
        //   disabled: false
        // }
      ]
    },
    // 是否禁用整个
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dropdownVisable: false,
      dropdownWidth: 0
    }
  },
  methods: {
    // 改变下拉显示框宽度
    handleChangeDropdown(val) {
      if (val) {
        this.$nextTick(() => {
          const el = this.$refs.dropDown
          if (el) {
            this.dropdownWidth = el.$el.offsetWidth + 'px'
          }
        })
      }
      this.dropdownVisable = val
    },
    // 点击菜单项
    handleCommand(val) {
      this.$emit('handleCommand', val)
    }
  }
}
</script>
