<!-- eslint-disable vue/no-mutating-props -->
<template>
  <el-checkbox
    v-if="isCheckAll"
    v-model="checkAll"
    :indeterminate="isIndeterminate"
    @change="handleCheckAllChange"
  >
    {{ checkAllLabel }}
  </el-checkbox>
  <el-checkbox-group v-model="checkeds">
    <el-checkbox
      v-for="(option, index) in options"
      :key="index"
      :label="option?.['value']"
    >
      {{ option?.['label'] }}
    </el-checkbox>
  </el-checkbox-group>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';

const emits = defineEmits(['changeValues']);

// const checked = ref<any>([]);
const props = defineProps({
  options: {
    type: Array<any>,
    default: () => []
  },
  checkAllLabel: {
    type: String,
    default: () => '全选'
  },
  // 是否有全选反选选项
  isCheckAll: {
    type: Boolean,
    default: () => false
  },
  checked: {
    type: Array<any>,
    default: () => []
  }
});

const checkeds = ref<any>(props.checked);
const isIndeterminate = ref(false);
const checkAll = ref<any>(false);

function getAllValue() {
  const all = <any>[];
  props.options.forEach((item: any) => all.push(item.value));
  return all;
}

// 全选/全不选
function handleCheckAllChange(bol: any): void {
  checkeds.value = bol ? getAllValue() : [];
  isIndeterminate.value = false;
}

watch(
  checkeds.value,
  () => {
    emits('changeValues', checkeds.value);
  },
  { deep: true }
);
</script>

<script lang="ts">
export default {
  name: 'CommonCheckGroup'
};
</script>

<style scoped lang="scss"></style>
