<template>
    <div>
        <el-checkbox v-if="all" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"
                     :style="style">全选
        </el-checkbox>
        <div style="width: 20px; display: inline-block;" v-if="inline&&all"></div>
        <div style="margin: 15px 0;" v-if="!inline&&all"></div>
        <el-checkbox-group v-model="checkList" @change="handleCheckedCitiesChange" :style="style">
            <el-checkbox :label="item.value" v-for="item in options" :key="item.value" :disabled="item.disabled">
                {{ item.label }}
            </el-checkbox>
        </el-checkbox-group>
    </div>
</template>

<script>
import ListUtil from "../../../util/pattern/list"

export default {
    name: "veCheckGroup",
    data() {
        return {
            checkAll: false,
            style: {},
            checkList: [],
            isIndeterminate: true
        }
    },
    props: {
        all: {
            type: Boolean,
            default: true,
        },
        inline: {
            type: Boolean,
            default: false,
        },
        value: {
            type: Array,
            default: () => []
        },
        options: {
            type: Array,
            default: () => []
        },
    },
    model: {
        prop: 'value',
        event: 'change'
    },
    created() {
        this.style = this.inline ? {
            display: "inline-block"
        } : "";
        this.checkList = this.value;
        this.handleCheckedCitiesChange(this.value);
    },
    watch: {
        checkList: {
            immediate: true, // 很重要！！！
            handler(newV, oldV) {
                this.onChange();
            }
        }
    },
    methods: {
        handleCheckAllChange(val) {
            this.checkList = val ? ListUtil.toArray(this.options, "value") : [];
            this.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.options.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.options.length;
        },
        onChange() {
            this.$emit('change', this.checkList);
        },
    }
}
</script>

<style scoped>

</style>
