<template>
  <div>
    <div class="alert alert-info">
      <span class="mx-3" v-if="cur_item">
        {{ cur_item[display_field] }}
      </span>
      <span class="mx-3 none" v-else>
        (未选择)
      </span>
      <button class="btn btn-sm btn-secondary" @click="show_modal">修改</button>
    </div>
    <Modal ref="select_modal" close_only=1>
      输入名称查找:
      <input class="form-control" type="text" v-model="cur_input" @input="query_update"/>
      <ul>
        <li v-for="(s, i) in suggestions" :key="i">
          {{ s[display_field] }}
          <a href="javascript:void(0)" @click="select(s)">
            选择
          </a>
        </li>
      </ul>
      <div class="paging">
        <a v-if="prev_page_uri" href="javascript:void(0)" @click="load_suggestions(prev_page_uri)">
          &lt; 上一页
        </a>
        <a v-if="next_page_uri" href="javascript:void(0)" @click="load_suggestions(next_page_uri)">
          下一页 &gt;
        </a>
      </div>
    </Modal>
  </div>
</template>

<script>
export default {
  name: 'GenericSelector',
  props: ['uri', 'display_field', 'value'],
  emits: ['input'],
  components: {
  },
  data: function () {
    return {
      suggestions: [],
      cur_input: '',
      cur_item: null,
      next_page_uri: null,
      prev_page_uri: null,
      load_seq: 0,
    };
  },
  computed: {
  },
  methods: {
    show_modal: function() {
      this.$refs.select_modal.show();
      this.query_update();
    },
    query_update: function() {
      var ci = this.cur_input;
      var uri = this.uri + "?q=" + ci;
      this.load_suggestions(uri);
    },
    load_suggestions: async function(uri) {
      var seq = ++this.load_seq;
      var r = await this.$root.api_get(uri);
      if (seq == this.load_seq) {
        this.suggestions = r.data.objects;
        this.next_page_uri = r.data.meta.next;
        this.prev_page_uri = r.data.meta.previous;
      }
    },
    select: function(item) {
      this.cur_item = item;
      this.$emit('select', item);
      this.$refs.select_modal.hide();
    },
  },
  mounted() {
  },
}
</script>

<style scoped>
ul {
  padding: 0.5rem;
  list-style: none;
}
span.none {
  color: #666;
}
div.paging a {
  margin: 0.5rem;
}
</style>

