<template>
  <ul class="qf-list" ref="items">
    <li :class="[selected === index ? 'selected' : '']" v-for="(item, index) in list" :key="index"
        @click="onSelect(item)">
      <template v-if="!!itemRenderer">　 <!-- 按子组件模板渲染 -->
        <component :is="itemRenderer" :value="list[index]"/>
      </template>
      <template v-else-if="!!list">　 <!-- 使用template scope -->
        <slot :item="list[index]"></slot>
      </template>
    </li>
  </ul>
</template>

<script>
import KeydownMgr from '../../util/KeydownMgr';
import ScrollUtil from '../../util/scroll';

export default {
  name: 'QfList',
  props: {
    value: {
      type: Number,
      default: -1
    },
    autoSelect: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array
    },
    itemRenderer: {
      default: null
    }
  },
  data() {
    return {
      selected: this.value
    };
  },

  created() {
    KeydownMgr.bind(this, this.onKeydown);
  },

  beforeDestroy() {
    KeydownMgr.unbind(this, this.onKeydown);
  },

  watch: {
    list(newVal) {
      if (this.autoSelect && newVal.length > 0) {
        this.selected = 0;
      } else {
        this.selected = -1;
      }
    },
    selected(val) {
      this.$emit('input', val);
      this.$nextTick(() => {
        ScrollUtil.scrollIntoView(this.$el, this.$el.querySelector('li.selected'));
      });
    }
  },

  methods: {
    onSelect(item) {
      this.selected = this.list.indexOf(item);
      this.$emit('select', item);
    },

    onKeydown(event) {
      if (event.keyCode === 13) {
        if (this.selected > -1 && this.selected < this.list.length) {
          this.$emit('select', this.list[this.selected]);
        }
      } else if (event.keyCode === 38) {
        if (this.selected - 1 < 0) {
          this.selected = this.list.length - 1;
        } else {
          this.selected -= 1;
        }
      } else if (event.keyCode === 40) {
        if (this.selected + 1 > this.list.length - 1) {
          this.selected = 0;
        } else {
          this.selected += 1;
        }
      }
    }
  }
};
</script>
