<template>
    <el-select
        v-model="value"
        :filterable="properties.filterable"
        :clearable="properties.clearable"
        :disabled="properties.disabled"
        @change="change"
        :placeholder="properties.placeholder"
        :multiple="properties.multiple"
        :collapse-tags="properties.collapseTags"
        reserve-keyword
        :remote="properties.remote"
        :remote-method="remoteMethod">
        <el-option
            v-for="(_o, index) in data"
            :key="index"
            :label="_o.label"
            :value="_o.value"
        ></el-option>
    </el-select>
</template>

<script>

import mixin from "./mixin";
import * as ObjUtil from "../../../util/pattern/object";
import MapUtil from "../../../util/pattern/map";
export default {
    name: "filterSelect",
    mixins: [mixin],
    data() {
        return {
            /**
             * 是否正在加载远程数据
             */
            ifShowLoading: false,
            data: [],
        };
    },
    created() {
        this.initProperties({
            filterable: true,
            clearable: true,
            collapseTags: true,
            placeholder: '请选择',
            disabled: false,
            /* 是否多选 */
            multiple:false,
            /* 筛选是否获取远程数据 */
            remote: false,
            props:{
                label: 'name',
                value: 'id',
            },
            /* 筛选远程数据执行回调 */
            remoteMethod(query){
            }
        });

    },
    methods: {
        async init(value) {
           this.value = value;
            let data = await this.getData();
            this.data = this.getSelectData(data||[]);

        },
        getSelectData(data){
            let vm = this
            let isArray = ObjUtil.isArray(data);
            let arr = [];
            if (isArray) {
                data.forEach(function (item) {
                    arr.push({
                        label: item.label?item.label:item[vm.properties.props.label],
                        value: item.value?item.value:item[vm.properties.props.value],
                    })
                })
            } else {
                arr = Object.keys(data).map(_i => {
                    return {
                        value: _i,
                        label: data[_i]
                    };
                })
            }
            if((this.properties.clearable==false)&&(this.value=='')&&(arr.length>0)){
                this.value = this.properties.multiple==false?arr[0].value:[arr[0].value];
                this.change()
            }
            return arr;
        },
        /* 筛选远程数据执行回调 */
        async remoteMethod(query){
            if(!query)return;
            this.ifShowLoading = true;
            this.value = this.properties.multiple ? [] : "";
            let data = await this.properties.remoteMethod(query);
            this.ifShowLoading = false;

            this.data = this.getSelectData(data);
        }
    }
};
</script>
