<template>
  <li :class="itemClasses" @click.stop="select" v-show="visible">
    {{label}}
    <slot></slot>
  </li>
</template>
<script>
import emitter from 'yt-ui/src/mixins/emitter'
export default {
  name: "YOption",
  mixins: [emitter],
  props: {
    value: { type: [String, Number], required: true },
    label: { type: [String, Number] },
    disabled: { type: Boolean, default: false }
  },
  data() {
    return {
      selected: false,
      index: 0,
      visible: true
    };
  },
  computed: {
    itemClasses() {
      return [
        "k-select-item",
        {
          ["k-select-item-selected"]: this.selected,
          ["k-select-item-disabled"]: this.disabled
        }
      ];
    }
  },
  methods: {
    select () {
      if (this.disabled) return;
      this.selected = true
      this.dispatch('YSelect', 'select-change', {
        value: this.value,
        label: this.label === undefined ? this.$el.innerText : this.label
      })
    },
    // 搜索到的结果高亮
    query (query) {
      if (!query && query !== 0) return
      // query 转义查询里面的正则
      let label = this.label === undefined ? this.$el.innerText : this.label
      let parsedQuery = String(query).replace(/(\^|\(|\)|\[|\]|\$|\*|\+|\.|\?|\\|\{|\}|\|)/g, "\\$1");
      this.visible = new RegExp(parsedQuery, "i").test(label);
      // 搜到的关键字高亮
      label = label.replace(new RegExp(query, 'g'), '<span class="k-select-item-high">' + query + '</span>')
      this.$el.innerHTML = label
    },
    // 重置高亮
    resetHight () {
      this.$el.innerHTML = this.$el.innerText
    }
  },
  mounted() {
    this.dispatch('YSelect', 'select-add', this)
  },
  beforeDestroy() {
    this.dispatch('YSelect', 'select-remove', this)
  }
};
</script>

