<template>
  <div class="all_checkbox_container">
    <p>{{ title }}</p>
    <el-checkbox
    v-model="checkoutAll"
    :indeterminate="indeterminate"
    @change="handleCheckAll"
    >
    全选
    </el-checkbox>
    <el-checkbox-group
    v-model="value"
    @change="handleCheck"
    >
        <el-checkbox v-for="item in options" :key="item" :label="item">{{ item }}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<script lang="ts">
interface IData {
    checkoutAll: boolean;
    indeterminate: boolean;
    value: any[];
}

import { defineComponent, reactive, toRefs, onMounted } from "vue";

export default defineComponent({
    name: "AllCheckBox",
    props: {
        title: {
            type: String,
            default: "页面显示字段"
        },
        options: {
            type: Array,
            default: () => [],
        },
        checkValue: {
            type: Array,
            default: () => [],
        }
    },
    setup(props) {
        const data = reactive<IData>({
            checkoutAll: false,
            indeterminate: false,
            value: []
        });


        // 全选
        const handleCheckAll = (val: boolean) => {
            data.value = val ? props.options : [];
            data.indeterminate = false;
        };

        // 单选
        const handleCheck = (value: string) => {
            const checkedCount = value.length;
            data.checkoutAll = checkedCount === props.options.length;
            data.indeterminate = checkedCount > 0 && checkedCount < props.options.length;
        };

        onMounted(() => {
            data.value = props.checkValue;
            // 设置初始化状态
            const checkedCount = props.checkValue.length;
            data.checkoutAll = checkedCount === props.options.length;
            data.indeterminate = checkedCount > 0 && checkedCount < props.options.length;
        });

        return {
            ...toRefs(data),
            handleCheckAll,
            handleCheck
        }
    }
})
</script>

<style lang="scss" scoped>
.all_checkbox_container {
    height: 100%;
}
</style>