<template>
  <div class="ui-filter">
    <slot />
    <div class="ui-filter__left">
      <div
        v-for="(item, index) in leftItems"
        :key="index"
        class="ui-filter__item"
      >
        <span class="ui-filter__label" v-if="item.props.label">{{item.props.label}}</span>
        <div class="ui-filter__target">
          <component :is="handleRenderItem(item)" :data-key="item.info.count" />
        </div>
      </div>
    </div>
    <div class="ui-filter__right">
      <div
        v-for="(item, index) in rightItems"
        :key="index"
        class="ui-filter__item"
      >
        <span class="ui-filter__label" v-if="item.props.label">{{item.props.label}}</span>
        <div class="ui-filter__target">
          <component :is="handleRenderItem(item)" :data-key="item.info.count" />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'UiFilter',
  provide() {
    return {
      UiFilter: this
    }
  },
  props: {
    value: {
      type: Object
    },
    ready: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      items: []
    }
  },
  computed: {
    leftItems() {
      return this.items.filter(v => v.props.position === 'left')
    },
    rightItems() {
      return this.items.filter(v => v.props.position === 'right')
    }
  },
  watch: {
    value: {
      handler() {
        if (this.ready) {
          this.handleChange()
        }
      },
      deep: true
    }
  },
  methods: {
    handleChange() {
      this.$emit('change')
    },
    getFilters() {
      return this.value
    },
    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>
.ui-filter{
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.ui-filter__left,
.ui-filter__right{
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap;
}
.ui-filter__item{
  margin-right: 24px;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 4px;
  margin-bottom: 4px;
}
.ui-filter__item:last-child{
  margin-right: 0;
}
.ui-filter__label{
  color: #999;
  padding-right: 9px;;
}
</style>
