<template>
  <div class="x-admin-sidebar-fav" ref="box">
    <div v-for="(item,index) in favorites"
         :key="`fav_${item.index}${item.id || ''}`"
         class="x-admin-sidebar-fav__item"
         :class="{'is-active': active === index}"
         @click="handleClick(item, index)">
      <XIcon v-if="item.icon" v-bind="getIconProps(item.icon)" :size="14" class="x-admin-sidebar-fav__icon"></XIcon>
      <span class="x-admin-sidebar-fav__text">{{item.text}}</span>
      <i class="x-admin-sidebar-fav__remove el-icon-close" @click.stop="handleRemove(item)"></i>
    </div>
    <div v-if="!favorites || favorites.length===0" class="empty">暂无数据</div>
  </div>
</template>

<script>
import { XIcon } from '@newpearl/ui';
import Sortable from 'sortablejs';

export default {
  inject: ['$admin'],
  components: {
    XIcon
  },
  props: {
    favorites: {
      type: Array,
      default() {
        return [];
      }
    },
    defaultActive: {
      type: String
    }
  },
  data() {
    return {
      active: null
    };
  },
  watch: {
    defaultActive: {
      immediate: true,
      handler(v) {
        this.active = this.favorites.findIndex(n => n.index === v);
      }
    }
  },
  methods: {
    handleClick(item) {
      this.$emit('click', item);
    },
    getIconProps(icon) {
      return typeof icon === 'string' ? { name: icon } : icon;
    },
    handleRemove(item) {
      this.$admin.$emit('remove-favorite', item);
    },
    onSort(e) {
      this.$admin.$emit('sort-favorite', e);
    }
  },
  mounted() {
    this.sortable = new Sortable(this.$refs.box, {
      animation: 150,
      direction: 'horizontal',
      onSort: this.onSort
    });
  },
  beforeDestroy() {
    if (this.sortable) {
      this.sortable.destroy();
      this.sortable = null;
    }
  }
};
</script>
