<template>
    <div class="dict-selector">
        <el-select v-if="formType == 'select'" v-model="valueSync" :placeholder="placeholder" clearable :multiple="multiple">
            <el-option v-for="dict in dictList"
                        :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
        <el-radio-group  v-if="formType == 'radio'" v-model="valueSync">
            <el-radio v-for="dict in dictList" :label="dict.value" :key="dict.value">{{dict.label}}</el-radio>
        </el-radio-group>
        <el-checkbox-group  v-if="formType == 'checkbox'" v-model="valueSync">
            <el-checkbox v-for="dict in dictList" :label="dict.value" :key="dict.value">{{dict.label}}</el-checkbox>
        </el-checkbox-group>
    </div>
</template>
<script>
export default {
    props:{
        placeholder: {
            type: String,
            default: '请选择'
        },
        type: String,
        value: [String, Number, Array],
        multiple: Boolean,
        formType:{
            type: String,
            default: 'select'
        },
        forceString: {
            type: Boolean,
            default: true
        },
        defaultable: Boolean, // 是否默认选择第一个
    },
    data(){
        return {
            valueSync: this.multiple ? [] : null
        }
    },
    computed:{
        dictList(){
            return this.getList(this.type)
        }
    },
    watch:{
        valueSync(){
            this.$emit('input', this.forceString ? String(this.valueSync) : this.valueSync)
        },
        value(val){
            this.setValueSync()
        },
        dictList(){
            this.setDefault()
        }
    },
    created(){
        this.setValueSync()
        this.setDefault()
    },  
    methods:{
        setValueSync(){
            if(!this.value || this.value == '') return 
            if(this.forceString && this.multiple){
                this.valueSync = this.value.split(',')
            }else this.valueSync = this.forceString ? String(this.value) : this.value
        },
        getList(){
            return this.getDictDatas(this.type)
        },
        setDefault(){
            if(!this.defaultable) return 
            if(this.dictList.length && (this.valueSync === null || this.valueSync == '')){
                this.valueSync = this.dictList[0].value
            }
        }
    }
}
</script>
<style scoped>
.dict-selector{
    display: inline-block;
}
</style>