<template>
  <div class="ui-toolbar" :class="['is-' + align]">
    <slot />
    <div
      v-for="(item, index) in items"
      :key="index"
      class="ui-toolbar__item"
    >
      <component :is="handleRenderItem(item)" :data-key="item.info.count" />
    </div>
  </div>
</template>
<script>
export default {
  name: 'UiToolbar',
  provide() {
    return {
      UiToolbar: this
    }
  },
  props: {
    align: {
      type: String,
      default: 'left',
      validator(value) {
        return ['left', 'center', 'right'].includes(value)
      }
    },
    bindClose: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      items: []
    }
  },
  methods: {
    handleRenderItem(item) {
      return {
        functional: true,
        render: (h, c) => {
          return item.render(h, c)
        }
      }
    },
    addItem(item) {
      if (!item || !item.id) {
        return
      }
      let index = -1
      this.items.some((v, i) => {
        if (v.id === item.id) {
          index = i
          return true
        }
      })
      if (index >= 0) {
        this.items.splice(index, 1, item)
      } else {
        this.items.push(item)
      }
    },
    removeItem(id) {
      this.items = this.items.filter(v => v.id !== id)
    }
  }
}
</script>
<style lang="less">
.ui-toolbar{
  display: flex;
  flex-direction: row;
  align-items: center;
  &.is-center {
    justify-content: center;
  }
  &.is-right {
    justify-content: flex-end;
  }
}
.ui-toolbar__item{
  margin-left: 16px;
}
.ui-toolbar__item:first-child{
  margin-left: 0;
}
</style>
