<template>
  <div class="x-admin-sidebar-search-list">
    <div v-for="(item,index) in matchList"
         :key="`search-list-${item.index}${item.id || ''}`"
         class="x-admin-sidebar-search-list__item"
         :class="{'is-active': active === index}"
         @click="handleClick(item)">
      <XIcon v-if="item.icon"
             :size="14"
             class="x-admin-sidebar-search-list__icon"
             v-bind="getIcon(item.icon)"></XIcon>
      <span class="x-admin-sidebar-search-list__text" v-html="showKeyword(item.text)"></span>
    </div>
    <div v-if="!matchList.length" class="empty">暂无数据</div>
  </div>
</template>

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

export default {
  components: {
    XIcon
  },
  props: {
    list: Array,
    keyword: String,
    defaultActive: String
  },
  data() {
    return {
      active: null
    };
  },
  computed: {
    matchList() {
      if (!this.list || !this.keyword) return [];
      return this.list.filter(n => n.text.includes(this.keyword));
    }
  },
  watch: {
    defaultActive: {
      immediate: true,
      handler(v) {
        this.active = this.matchList.findIndex(n => n.index === v);
      }
    }
  },
  methods: {
    handleClick(item) {
      this.$emit('click', item);
    },
    showKeyword(text) {
      return text.replace(new RegExp(this.keyword, 'gi'), `<span class="is-keyword">${this.keyword}</span>`);
    },
    getIcon(icon) {
      return typeof icon === 'string' ? { name: icon } : icon;
    }
  }
};
</script>
