<template>
  <Dropdown class="x-admin-size-dropdown" @command="handleCommand">
    <XIcon :icon="icon" :size="12" class="x-admin-icon-button"></XIcon>
    <DropdownMenu slot="dropdown">
      <DropdownItem v-for="item in items"
                    :key="item.sizeHeight"
                    :command="item"
                    class="x-admin-size-dropdown__item"
                    :class="{'is-active':active === item.size}">
        <XIcon class="x-admin-size-dropdown__icon" :name="item.icon" :size="14"></XIcon>
        <span class="x-admin-size-dropdown__text">{{item.name}}</span>
      </DropdownItem>
    </DropdownMenu>
  </Dropdown>
</template>

<script>
import { Dropdown, DropdownMenu, DropdownItem } from 'element-ui';
import { XIcon } from '@newpearl/ui';
import { Rows } from '@newpearl/icons';

export default {
  inject: ['$admin'],
  components: {
    XIcon,
    Dropdown,
    DropdownMenu,
    DropdownItem
  },
  props: {
    items: Array,
    defaultSize: String
  },
  data() {
    return {
      icon: Rows,
      active: null
    };
  },
  watch: {
    defaultSize: {
      immediate: true,
      handler(v) {
        this.active = v;
      }
    },
    active: {
      immediate: true,
      handler(n, o) {
        this.setClass(n, o);
        const sizes = { mini: 28, tiny: 22 };
        const ElSelectCaches = this.$admin.$options.ElSelectCaches;
        this.$nextTick(() => {
          const selectArray = Object.values(ElSelectCaches);
          selectArray.forEach(instance => {
            instance.initialInputHeight = sizes[n];
            instance.resetInputHeight();
          });
        });
      }
    }
  },
  methods: {
    handleCommand(item) {
      this.active = item.size;
      this.$admin.$emit('size-change', item);
    },
    setClass(n, o) {
      const el = document.documentElement;
      if (!el) return;
      el.setAttribute('data-size', n);
    }
  }
};
</script>
