<template>
  <n-options-container v-bind="{visible, hasArrow, builders}">
    <div class="n-options-search" v-if="hasSearch">
      <n-input-lite v-model="state.keyword" :placeholder="state.placeholder" :focusing="true" @u-update="onUserSearch"></n-input-lite>
    </div>
    <n-virtual-list :data-list="_options" id-key="value" :item-size="32" :virtual="virtual" :max-height="maxHeight" @scroll.native="onScroll">
      <template #default="{item}">
        <slot name="option" :option="item"></slot>
      </template>
      <template #after>
        <div v-if="state.loading" class="n-options-loading flex-center">
          <n-loading-icon size="20" color="#128eff"></n-loading-icon>
          <div>加载中...</div>
        </div>
        <div v-else-if="!state.loading && _options.length <= 0" class="n-options-empty">
          <n-builder v-if="builders.empty" :name="builders.empty"></n-builder>
          <div v-else class="n-options-empty-default">暂无数据</div>
        </div>
      </template>
    </n-virtual-list>
    <slot name="footer"></slot>
  </n-options-container>
</template>
<script>
import NBuilder from '@uif/next/lib/components/builder'
import NInputLite from '@uif/next/lib/components/input-lite'
import NLoadingIcon from '@uif/next/lib/components/loading-icon'
import NVirtualList from '@uif/next/lib/components/virtual-list'
import {loadMore, prop} from '@uif/next/lib/utils/tools'
import NOptionsContainer from './options-container'

export default {
  name: 'n-options-virtual-list',
  components: {
    NInputLite,
    NVirtualList,
    NLoadingIcon,
    NBuilder,
    NOptionsContainer
  },
  props: {
    // SearchState
    state: prop.object(),
    // 是否有搜索
    hasSearch: prop.boolean(),
    // 选项
    _options: prop.array(),
    // 开启虚拟滚动
    virtual: prop.boolean(),
    // 是否多选
    multiple: prop.boolean(),
    // 最大高度
    maxHeight: prop.number(270),

    /**
     * Container
     * **/
    visible: prop.boolean(),
    // 箭头
    hasArrow: prop.boolean(),
    // 自定义渲染
    builders: prop.object(() => ({
      header: null,
      footer: null,
      empty: null
    }))
  },
  methods: {
    // 加载更多
    onScroll (event) {
      if (loadMore(event.target, 20)) {
        return this.state.loadMore?.()
      }
    },
    // 用户正在输入
    onUserSearch () {
      this.state.doSearch()
    }
  }
}
</script>
