<template>
    <el-select v-model="collectionId" filterable remote :remote-method="search" :loading="loading">
        <el-option v-for="item in options" :label="item.name" :value="item.id" :key="item.id">
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">#{{ item.id }}</span>
        </el-option>
    </el-select>
</template>
<script>
export default {
    props: ['value'],
    created() {
        this.collectionId = this.value;
        this.$http
            .post(
                '/collection/all',
                {
                    sort: 'sort,desc;createdAt,desc',
                    query: { del: false, source: 'OFFICIAL' }
                },
                { body: 'json' }
            )
            .then(res => {
                this.options = res.content;
            });
    },
    data() {
        return {
            options: [],
            collectionId: null,
            selected: null,
            loading: false
        };
    },
    methods: {
        search(query) {
            this.$http
                .post(
                    '/collection/all',
                    {
                        sort: 'sort,desc;createdAt,desc',
                        search: query,
                        query: { del: false, source: 'OFFICIAL' }
                    },
                    { body: 'json' }
                )
                .then(res => {
                    this.options = res.content;
                });
        }
    },
    watch: {
        collectionId(val) {
            this.$emit('input', val);
            if (val) {
                this.selected = this.options.find(i => i.id === val);
                this.$emit('select', this.selected);
            }
        },
        value(val) {
            this.collectionId = val;
        }
    }
};
</script>