<template>
  <v-combobox
    v-model="modelValue"
    :loading="loading"
    :items="items"
    :search-input.sync="searchInput"
    flat
    dense
    multiple
    outlined
    clearable
    v-bind="$attrs"
    @change="handleChange"
  >
    <template v-slot:append-item>
      <div class="d-flex justify-center">
        <v-btn
          text
          color="primary"
          :loading="loading"
          :disabled="total <= items.length"
          @click="handleMore">
          查看更多
        </v-btn>
      </div>
    </template>
    <template #item="{ item, on, attrs }">
      <v-list-item v-bind="attrs" v-on="on">
        <v-list-item-content>
          <v-list-item-title>[{{ item.type === 'resource' ? '资源' : '模型' }}] {{ item.name }}</v-list-item-title>
        </v-list-item-content>
      </v-list-item>
    </template>
  </v-combobox>
</template>

<script>

// 节点检索
import { debounce } from 'lodash'
import { api } from '@/api/dataGovernance'
export default {
  name: 'search-nodes',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    searchValue: {
      type: String,
      default: null
    }
  },
  data () {
    return {
      modelValue: [],
      loading: false,
      items: [],
      searchInput: null,
      pageInfo: {
        current: 1,
        size: 10
      },
      total: 0,
      query: {
        name: null
      }
    }
  },
  async mounted () {
    this.query.name = this.searchValue
    await this.init()
    this.modelValue = this.value
    // 禁止多次访问
    setTimeout(() => {
      const debouncedCallback = debounce(async (newValue, old) => {
        this.querySearch(newValue)
      }, 500)
      this.$watch(() => this.searchInput, debouncedCallback)
    })
  },
  methods: {
    handleChange (val) {
      this.$emit('input', val)
    },
    handleMore () {
      this.pageInfo.current++
      this.init()
    },
    async querySearch (name) {
      this.query.name = name
      this.pageInfo.current = 1
      this.items = []
      await this.init()
    },
    async init () {
      this.loading = true
      try {
        const { data } = await api.getResourceAndModelList({ ...this.query, ...this.pageInfo })
        this.items.push(...data.records.map(e => {
          return {
            text: e.name,
            value: e.id,
            ...e
          }
        }))
        this.total = data.total
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .v-select__selection--comma{
  margin: 0;
  padding: 3px 5px 2px 0;
}
</style>
