<template>
  <ToolBarButton v-if="isType('button')"
                 class="x-toolbar__item"
                 v-bind="$props">
  </ToolBarButton>

  <ElDivider v-else-if="isType('divider')"
             class="x-toolbar__divider"
             v-bind="props"></ElDivider>

  <ElButtonGroup v-else-if="isType('group') && children && visible"
                 class="x-toolbar__item x-toolbar__group">
    <ToolBarButton v-for="item in children"
                   :key="item.name"
                   :mode="mode"
                   :size="size"
                   v-bind="getButtonProps(item)">
    </ToolBarButton>
  </ElButtonGroup>

  <Dropdown v-else-if="isType('dropdown') && children && visible"
            class="x-toolbar__item"
            :disabled="disabled"
            @command="handleCommand">
    <ElButton :size="size" v-bind="props">
      {{label}} <i class="el-icon-arrow-down"></i>
    </ElButton>
    <DropdownMenu v-if="children.length" slot="dropdown">
      <DropdownItem v-for="item in children"
                    :key="item.name"
                    :mode="mode"
                    v-bind="getButtonProps(item)"></DropdownItem>
    </DropdownMenu>
  </Dropdown>

  <div v-else-if="isType('custom')"
       class="x-toolbar__item x-toolbar__custom">
    <slot :name="name"
          :disabled="disabled"
          :visible="visible"
          :isAccess="isAccess"
          v-bind="$props"></slot>
  </div>

</template>

<script>
import {
  Divider as ElDivider,
  ButtonGroup as ElButtonGroup,
  Button as ElButton,
  Dropdown,
  DropdownMenu
} from 'element-ui';
import merge from 'lodash-es/merge';
import ToolBarButton from './Button';
import DropdownItem from './DropdownItem';
import common from '../common';

export default {
  name: 'XToolbarItem',
  mixins: [common],
  components: {
    ToolBarButton,
    ElDivider,
    ElButtonGroup,
    ElButton,
    Dropdown,
    DropdownMenu,
    DropdownItem
  },
  props: {
    children: Array
  },
  methods: {
    isType(type) {
      return this.type === type;
    },
    getButtonProps(item) {
      const { props, $toolbar } = this;
      if (this.type === 'dropdown') {
        return merge({}, $toolbar.getValue(item), { props: item.props });
      }
      return merge({}, $toolbar.getValue(item), { props });
    },
    handleCommand(props) {
      const { name, handler } = props;
      const $toolbar = this.$toolbar;
      if (handler) {
        handler(props);
      }
      $toolbar.$emit('click', props);
      $toolbar.$emit(name, props);
    }
  }
};
</script>
