import { RecycleScroller } from 'vue-virtual-scroller';
import ElOption from 'mars-pro/packages/option';
import ElScrollbar from 'mars-pro/packages/scrollbar';

export default {
    name: 'ProSelectOptionList',
    componentName: 'ProSelectOptionList',
    inheritAttrs: false,
    components: {
        RecycleScroller,
        ElScrollbar,
        ElOption
    },
    inject: ['proselect'],
    computed: {
        labelKey() {
            return this.proselect.labelKey
        },
        valueKey() {
            return this.proselect.valueKey
        },
        filterDatas() {
            return this.proselect.filterDatas || []
        },
        datas() {
            return this.proselect.selectDatas || []
        },
        isEnableVirtualList() {
            return this.proselect.isEnableVirtualList
        }
    },
    methods: {
        renderOption(data) {
            if (this.proselect.$scopedSlots.optionItem) {
                return this.proselect.$scopedSlots.optionItem(data)
            }
            const _datas = {
                props: {
                    value: data[this.valueKey],
                    label: data[this.labelKey],
                    disabled: data.disabled
                },
                key: data[this.valueKey]
            }
            return (
                <ElOption {..._datas}>
                    {this.renderLabel(data)}
                </ElOption>
            )
        },
        renderLabel(data) {
            if (this.proselect.$scopedSlots.content) {
                return this.proselect.$scopedSlots.content(data)
            } else {
                return data[this.labelKey || 'label'] || data[this.valueKey || 'value']
            }
        },
    },
    render() {
        if (this.isEnableVirtualList) {
            const recycleScrollerSlots = {
                default: ({ item }) => this.renderOption(item)
            }
            return (<RecycleScroller
                ref="scroller"
                scopedSlots={recycleScrollerSlots}
                itemsLimit={1000}
                items={this.filterDatas}
                item-size={34}
                class='el-select-dropdown__wrap el-select-dropdown__list'
                buffer={100}
                key-field={this.valueKey}
            />)
        }
        return (
            <ElScrollbar
                tag="ul"
                wrap-class="el-select-dropdown__wrap"
                view-class="el-select-dropdown__list"
            >
                {
                    (this.filterDatas || []).map(r => this.renderOption(r))
                }
            </ElScrollbar>
        )
    }
}