<template>
  <div class="checkBox">
    <el-checkbox class="checkall" :class="customClass" v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAll">全部</el-checkbox>
    <el-checkbox-group v-model="hasChecked" @change="handleCheckedChange">
      <span class="zwModel" :class="customClass"></span>
      <el-checkbox :class="customClass" v-for="item in checkedList" :key="item" :label="item" :style="{width:props.width || 'auto'}">{{item}}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<script setup>
import { ref, defineProps, watch, defineEmits } from "vue";
const emits = defineEmits(["changeData"]);
const props = defineProps({
  data: {
    type: Object,
    default: {
      list: [],
      hasChoose: []
    }
  },
  width:String,
  customClass:String //自定义样式
});
const checkAll = ref(false);
const isIndeterminate = ref(true);
const hasChecked = ref([]); //已经全选的数据
const checkedList = ref([]);
watch(
  () => props.data,
  (val) => {
    hasChecked.value = val.hasChoose;
    checkedList.value = val.list;
    handleChange(val.hasChoose); //判断是否全选
  },
  {
    deep: true,
    immediate: true
  }
);
// 全选
function handleCheckAll(val) {
  hasChecked.value = val ? checkedList.value : [];
  isIndeterminate.value = false;
  emits("changeData", hasChecked.value);
}
// 处理多选框改变
function handleCheckedChange(val) {
  handleChange(val);////判断是否全选
  emits("changeData", hasChecked.value);
}
//判断是否全选
function handleChange(val) {
  let checkCount = val.length;
  let len = checkedList.value.length;
  checkAll.value = checkCount == len ? true : false;
  isIndeterminate.value = checkCount > 0 && checkCount < len ? true : false;
}
</script>

<style lang="scss" scoped>
.checkBox {
  display: flex;
  flex-wrap:nowrap;
  width:100%;
  height:100%;
  .checkall {
    margin: 0 20px 0 4px;
  }
}
</style>