<template>
  <div class="kole-autocomplete" v-click-outside="close">
    <input
      class="kole-autocomplete-input"
      :value="value"
      :placeholder="placeholder"
      @input="onInput"
      @keydown.down.prevent="move(1)"
      @keydown.up.prevent="move(-1)"
      @keydown.enter="enter"
      @keydown.esc="close"
    />
    <div v-show="open && list.length" class="kole-autocomplete-pop">
      <div
        v-for="(it, i) in list"
        :key="i"
        class="kole-autocomplete-item"
        :class="{ 'is-active': i === active }"
        @click="choose(i)"
        v-html="highlight(it)"
      ></div>
    </div>
    <div v-show="open && value && !list.length" class="kole-autocomplete-pop"><div class="kole-autocomplete-empty">无匹配结果</div></div>
  </div>
</template>

<script>
export default {
  name: 'KoleAutoComplete',
  directives: {
    clickOutside: {
      bind(el, b) { el.__d = (e) => { if (!el.contains(e.target)) b.value(); }; document.addEventListener('click', el.__d); },
      unbind(el) { document.removeEventListener('click', el.__d); }
    }
  },
  props: {
    value: { type: String, default: '' },
    options: { type: Array, default: () => ['北京', '上海', '广州', '深圳', '杭州', '成都', '重庆', '武汉', '西安', '南京', '苏州', '天津'] },
    placeholder: { type: String, default: '输入关键字…' }
  },
  data() {
    return { open: false, active: -1, list: [] };
  },
  methods: {
    onInput(e) {
      var q = e.target.value;
      this.$emit('input', q);
      this.active = -1;
      this.list = q ? this.options.filter(function (d) { return d.indexOf(q) >= 0; }) : [];
      this.open = true;
    },
    highlight(it) {
      var q = this.value.trim();
      if (!q) return it;
      return it.replace(new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'g'), '<mark>$1</mark>');
    },
    move(d) { this.open = true; this.active = Math.max(-1, Math.min(this.list.length - 1, this.active + d)); },
    enter() { if (this.active >= 0) this.choose(this.active); },
    choose(i) { this.$emit('input', this.list[i]); this.$emit('select', this.list[i]); this.close(); },
    close() { this.open = false; }
  }
};
</script>

<style src="./AutoComplete.css"></style>
