<template>
  <div class="ibps-toolbar">
    <ul
      v-if="moreActions && moreActions.length >0"
      v-show="showMore"
      class="ibps-toolbar-group-more"
    >
      <ibps-toolbar-sheet
        v-model="showMore"
        :title="moreTitle"
        :options="moreActions"
        :cancel-text="moreCancelText"
        @select="onClick"
        @cancel="onCancel"
      />
    </ul>
    <ul class="ibps-toolbar-group">
      <ibps-toolbar-item
        v-for="(action, index) in basicActions"
        :key="index"
        :icon-prefix="iconPrefix"
        :action="action"
        @click.native="onClick(action)"
      />
    </ul>
  </div>
</template>

<script>
import IbpsToolbarItem from './toolbar-item.vue'
import IbpsToolbarSheet from './toolbar-sheet.vue'

const EVENT_MORE_CLICK = 'more-click'
const EVENT_CANCEL = 'cancel'
const EVENT_ACTION = 'action-event'

export default {
  name: 'ibps-toolbar',
  components: {
    IbpsToolbarItem,
    IbpsToolbarSheet
  },
  props: {
    iconPrefix: String,
    actions: {
      type: Array,
      default: () => {
        return []
      }
    },
    moreActions: {
      type: Array
    },
    moreTitle: {
      type: String,
      default: '请进行以下操作'
    },
    moreCancelText: {
      type: String,
      default: '取消'
    }
  },
  data() {
    return {
      showMore: false
    }
  },
  computed: {
    basicActions() {
      const basicActions = this.actions.slice()
      this.moreActions && this.moreActions.length > 0 && basicActions.push({
        icon: this.iconPrefix === 'ibps-icon' ? 'ellipsis-h' : 'ellipsis',
        $vanMore: true,
        callback: () => {
          this.$emit(EVENT_MORE_CLICK, this.showMore)
        }
      })
      return basicActions
    }
  },
  methods: {
    onClick(action) {
      if (action.disabled) {
        return
      }
      if (action.$vanMore) {
        this.showMore = !this.showMore
      }
      if (action.callback) {
        action.callback(action)
      } else {
        this.$emit(EVENT_ACTION, action)
      }
    },

    onCancel() {
      this.$emit(EVENT_CANCEL)
    },
    closeMoreAction() {
      this.showMore = false
    }
  }
}
</script>
