<template>
  <ui-popover
    ref="popover"
    class="ui-grid-more-toolbar"
    trigger="click"
    v-model="popoverVisible"
    :visible-arrow="true"
    v-if="visible"
  >
    <ui-button class="ui-grid-more-toolbar__icon" slot="reference" size="mini" plain icon="more-line"></ui-button>
    <ul class="ui-grid-more-toolbar__menu">
      <li
        v-for="(item, index) in visibleItems"
        class="ui-grid-more-toolbar__item"
        :class="{'is-loading': loadingMap[index]}"
        :key="index"
        @click="handleItemClick(item, index)"
      >
        <span class="ui-grid-more-toolbar__item-icon">
          <ui-icon v-if="loadingMap[index]" name="loading"></ui-icon>
          <ui-icon v-else-if="item.icon" :name="item.icon"></ui-icon>
        </span>
        <span class="ui-grid-more-toolbar__item-label">
          {{item.label}}
        </span>
      </li>
    </ul>
  </ui-popover>
</template>
<script>
export default {
  name: 'UiGridMoreToolbar',
  props: {
    items: {
      type: Array,
      default: () => []
    },
    extendItems: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      popoverVisible: false,
      loadingMap: {}
    }
  },
  computed: {
    visible() {
      return !!this.visibleItems.length
    },
    visibleItems() {
      return this.allItems.filter(v => {
        if (typeof v.visible === 'function') {
          return v.visible()
        }
        return v.visible !== false
      })
    },
    allItems() {
      return [].concat(this.items || [], this.extendItems || [])
    }
  },
  methods: {
    handleItemClick(item, index) {
      if (typeof item.click === 'function') {
        const rs = item.click()
        if (rs && rs.then) {
          this.$set(this.loadingMap, index, true)
          rs.then(() => {
            this.$set(this.loadingMap, index, false)
            this.checkClickVisible()
          }, () => {
            this.$set(this.loadingMap, index, false)
            this.checkClickVisible()
          })
        } else {
          this.popoverVisible = false
        }
      }
    },
    checkClickVisible() {
      if (!Object.keys(this.loadingMap).some(v => this.loadingMap[v])) {
        this.popoverVisible = false
      }
    }
  }
}
</script>
<style>
.ui-grid-more-toolbar{
  line-height: 1;
}
.ui-grid-more-toolbar__icon .ui-icon{
  font-weight: bold;
}
.ui-grid-more-toolbar__menu{
  list-style: none;
  margin: 0;
  padding: 6px 0;
  min-width: 120px;
}
.ui-grid-more-toolbar__item-icon{
  display: inline-block;
  width: 16px;
  height: 16px;
  line-height: 16px;
  margin-right: 3px;
  vertical-align: top;
  margin-top: 1px;
}
.ui-grid-more-toolbar__item{
  padding: 6px 12px;
  cursor: pointer;
  transition: all .3s;
}
.ui-grid-more-toolbar__item:hover:not(.is-loading){
  background-color: #f0f8fc;
  color: #00A0EB;
}
.ui-grid-more-toolbar__item.is-loading{
  cursor: not-allowed;
  color: #999;
}
</style>
