<template>
    <el-select
        v-model="surpriseBoxId"
        filterable
        :filter-method="filterCollection"
        :loading="collectionLoading"
        clearable=""
        :disabled="disabled"
        :multiple="isMultiple ? true : false"
        placeholder="请选择惊喜盒子"
    >
        <el-option v-for="item in filterOptions" :label="item.name" :value="item.id" :key="item.id">
            <span style="float: left">{{ item.name }}<el-badge :value="item.boxSum"></el-badge></span>
            <span style="float: right; color: #8492a6; font-size: 13px">
                #{{ item.id }}
            </span>
        </el-option>
    </el-select>
</template>
<script>

export default {
    props: ['projectId', 'value', 'isMultiple', 'disabled'],
    created() {
        if (this.value != null) {
            this.surpriseBoxId = this.value;
        }
        this.reloadData();
    },
    data() {
        return {
            options: [],
            filterOptions: [],
            surpriseBoxId: null,
            selected: null,
            collectionLoading: false,
        };
    },
    methods: {
        filterCollection(val) {
            this.filterOptions = this.options.filter(i => i.name.includes(val) || i.id == val);
        },
        reloadData() {
            this.collectionLoading = true;
            this.$http
                .post(
                    '/activitySurpriseBox/all',
                    {
                        size: 10000,
                        sort: 'createdAt,desc',
                        query: { 
                            del: false,
                            projectId: this.projectId,
                            createdAt: ''
                        }
                    },
                    { body: 'json' }
                )
                .then(res => {
                    this.filterOptions = this.options = res.content;
                })
                .finally(() => {
                    this.collectionLoading = false;
                });
        }
    },
    watch: {
        surpriseBoxId(val) {
            this.$emit('input', val);
            if (val) {
                this.selected = this.options.find(i => i.id === val);
                this.$emit('select', this.selected);
            }
            setTimeout(() => {
                this.filterOptions = [...this.options];
            }, 200);
        },
        value(val) {
            this.surpriseBoxId = val;
        },
        projectId() {
            //重新加载数据
            this.reloadData();
        }
    }
};
</script>
