<template>
  <div>
    <v-autocomplete
      :search-input.sync="searchInput"
      full-width
      :items="items"
      v-model="modelValue"
      v-bind="$attrs"
      v-on="$listeners"
      @change="$emit('update', value)"
    >
      <template v-slot:append-item>
        <div class="d-flex align-center justify-center">
          <v-btn v-if="items.length < total" :loading="loading" text color="primary" @click="handleMore">加载更多</v-btn>
          <no-more v-else></no-more>
        </div>
      </template>
    </v-autocomplete>
  </div>
</template>

<script>
import NoMore from '@/components/NoMore'
import { debounce } from 'lodash'

export default {
  name: 'search-select',
  components: { NoMore },
  props: {
    value: {
      type: [String, Number, Array],
      default: null
    },
    init: {
      type: Function,
      default: () => {
        return Promise.resolve({ data: [], total: 0 })
      }
    },
    filterSearch: {
      type: Function,
      default: (val) => {
        return val
      }
    }
  },
  data () {
    return {
      modelValue: null,
      searchInput: null,
      loading: false,
      items: [],
      total: 0,
      pageInfo: {
        size: 50,
        current: 1
      }
    }
  },
  watch: {
    value (val) {
      this.modelValue = val
    },
    searchInput: {
      handler: debounce(function (val, oldVal) {
        this.handleSearch()
      }, 500),
      immediate: true
    }
  },
  methods: {
    // 通过id回显初始化
    setInitialize (id) {
      this.pageInfo.current = 1
      this.init({
        id,
        pageInfo: this.pageInfo
      }).then(({ data, total }) => {
        this.items = [...data]
        this.total = total
      })
    },
    // 重置
    reset () {
      this.modelValue = null
      this.pageInfo.current = 1
      this.init({
        searchInput: null,
        pageInfo: this.pageInfo
      }).then(({ data, total }) => {
        this.items = [...data]
        this.total = total
      })
    },
    handleSearch () {
      this.pageInfo.current = 1
      this.init({
        searchInput: this.filterSearch(this.searchInput),
        pageInfo: this.pageInfo
      }).then(({ data, total }) => {
        this.items = [...data]
        this.total = total
      })
    },
    handleMore () {
      this.loading = true
      this.pageInfo.current++
      this.init({
        searchInput: this.filterSearch(this.searchInput),
        pageInfo: this.pageInfo
      }).then(({ data, total }) => {
        this.items.push(...data)
        this.total = total
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
