<template>
    <el-checkbox
        class="w100p"
        v-if="showCheckAllSync"
        :indeterminate="isIndeterminate"
        v-model="checkAll"
        @change="_handleCheckAllChange"
        >全选</el-checkbox
    >
    <el-checkbox-group :model-value="valueSync" @change="_onChange">
        <el-checkbox v-for="item in list" :label="item[valueKey]" :key="item[valueKey]" :disabled="disabled">{{item[labelKey]}}</el-checkbox>
    </el-checkbox-group>
</template>

<script>
export default {
    name: "st-checkbox",
    emits:["update:modelValue","change"],
    props:{
        modelValue : Array ,
        list:{
            type : Array,
            default(){
                return []
            }
        },
        labelKey:{
            type : String ,
            default(){
                return "label" ;
            }
        },
        valueKey:{
            type : String ,
            default(){
                return "value" ;
            }
        },
        disabled: {
            type: Boolean,
            default: false
        },
        showCheckAll: {
            type: Boolean,
            default: false
        }
    },
    watch:{
        modelValue:{
            handler(){
                this.valueSync = this.modelValue ?? [] ;
            },
            immediate : true
        }
    },
    computed: {
        showCheckAllSync() {
            return this.showCheckAll && this.list.length>0;
        }
    },
    data(){
        return {
            valueSync : [],
            isIndeterminate: false,
            checkAll: false
        }
    },
    methods:{
        _onChange(value){
            this.valueSync = value;
            if(this.showCheckAll){
                const checkedCount = value.length;
                this.checkAll = checkedCount === this.list.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.list.length;
            }
            this._emits(value);
        },
        _handleCheckAllChange(value){
            this.valueSync = value ? this.list.map(v=>v[this.valueKey]) : [];
            this.isIndeterminate = false;
            this._emits(this.valueSync);
        },
        _emits(value){
            this.$emit("update:modelValue" , value);
            this.$emit("change" , value);
        }

    }
}
</script>