<template>
    <el-select v-model="valueSync" :multiple="multiple" :disabled="disabled" :filterable="filterable" :placeholder="$t('请选择')">
        <el-option v-for="item in optionsFormated" :key="item.key" :label="item.label" :value="item.value" />
    </el-select>
</template>
<script>
export default {
    data(){
        return {
            valueSync: null
        }
    },
    props:{
        options: Array,
        value: [String, Number, Boolean, Object],
        labelField: {
            type: [String, Function],
            default: 'label'
        },
        valueField: {
            type: String,
            default: 'value'
        },
        keyField:{
            type: String,
            default: 'value'
        },
        filterable: Boolean,
        multiple: Boolean,
        clearable: Boolean,
        defaultable: Boolean, // 没有值的时候是否选择第一项
        disabled: Boolean,
        test: String
    },
    computed:{
        optionsFormated(){
            let arr = []
            this.options.forEach((item, index) => {
                arr.push({
                    label: typeof this.labelField == 'string' ? item[this.labelField] : (this.labelField)(item, index),
                    value: item[this.valueField],
                    key: item[this.keyField]
                })
            })
            return arr
        }
    },
    watch:{
        valueSync(val){
            this.$emit('input', val)
        },
        value(value){
            this.valueSync = value
        },
        optionsFormated(){
            this.setDefault()
        },
        test(val, old){
            console.warn('test变化', val, old)
        }
    },
    created(){
        if(this.test == 'allPriceUnit'){
            console.log('allPriceUnit selector', this.value, this.defaultable)
        }
        this.valueSync = this.value
        this.setDefault()
    },
    methods:{
        setDefault(){
            if(!this.defaultable){
                return false
            }
            if(this.optionsFormated.length && (this.valueSync == null || this.valueSync == '')){
                this.valueSync = this.optionsFormated[0].value
            }
        }
    }
}
</script>