<script>
import { RecycleScroller } from 'vue-virtual-scroller'
import {prop, toNumber, isFunction} from '@uif/next/lib/utils/tools'

function renderSlot (h, scopedSlots, name) {
  return isFunction(scopedSlots[name]) ? h('template', {slot: name}, scopedSlots[name]()) : null
}

export default {
  name: 'n-virtual-list',
  props: {
    // 开启虚拟滚动
    virtual: prop.boolean(true),
    // 数据集合
    dataList: prop.array(),
    // 数据键
    idKey: prop.string('id'),
    // 最大高度
    maxHeight: prop.stringNumber('inherit'),
    // 最小高度
    itemSize: prop.stringNumber(32),
    // 其他参数
    options: prop.object()
  },
  computed: {
    styles ({maxHeight}) {
      return {maxHeight: toNumber(maxHeight) ? maxHeight + 'px' : maxHeight}
    }
  },
  render (h) {
    const {virtual, dataList, styles, $scopedSlots, itemSize, idKey, options} = this
    if (virtual) {
      return h(RecycleScroller, {
        props: {
          keyField: idKey,
          items: dataList,
          itemSize: toNumber(itemSize),
          ...options
        },
        staticClass: 'n-virtual-list n-small-scrollbar',
        style: styles,
        scopedSlots: $scopedSlots
      }, [
        renderSlot(h, $scopedSlots, 'before'),
        renderSlot(h, $scopedSlots, 'after')
      ])
    }
    return h('div', {
      staticClass: 'n-virtual-list n-small-scrollbar reality',
      style: styles
    }, [
      $scopedSlots.before?.(),
      ...dataList.map((item, index) => $scopedSlots.default?.({item, index})),
      $scopedSlots.after?.()
    ])
  }
}
</script>
