<template>
  <div class="bg-permission-option">
    <div
      class="bg-permission-option--self"
      :class="{
        'full-option': !(option.children && option.children.length > 0),
      }">
      <el-checkbox v-model="option.isSelected" :indeterminate="option.isIndeterminate" @change="changeSelf">
        <span :title="option.name + (option.remark ? `(${option.remark})` : '')">
          {{ option.name }}
          {{ option.remark ? `(${option.remark})` : "" }}
        </span>
      </el-checkbox>
    </div>
    <div
      class="bg-permission-option--list"
      :class="{ 'flex-wrap': deep === depth - 1 }"
      v-if="option.children && option.children.length > 0">
      <BgPermissionOption
        v-for="(item, index) in option.children"
        :ref="`child${index}`"
        :option="item"
        :key="`opt_${index}`"
        :deep="deep + 1"
        :depth="depth"
        @change="changeChild" />
    </div>
  </div>
</template>

<script setup>
import { nextTick } from "vue";
const props = defineProps({
  option: {
    type: Object,
    require: true,
  }, // 数据项
  depth: {
    type: Number,
    default: 0,
  },
  deep: {
    type: Number,
    default: 1,
  },
});

const dealData = (arr, flag) => {
  arr.forEach((e) => {
    e.isSelected = flag;
    if (e.children && e.children.length) {
      dealData(e.children, flag);
    }
  });
};
const emit = defineEmits(["change"]);

const changeSelf = () => {
  let isSelected = props.option.isSelected;
  let children = props.option.children || [];

  // 将自己的选中状态赋值给子级
  if (children.length > 0) {
    dealData(children, isSelected);
  }
  // 关于自己选中都是全选和不选，所以不存在半选状态
  props.option.isIndeterminate = false;
  // 修改完自己和自己子级，告诉父级更新
  emit("change");
};

const changeChild = () => {
  let isSelected = true;
  let isIndeterminate = false;
  let children = props.option.children;
  children.forEach((v, i) => {
    isSelected = isSelected && v.isSelected; // 所有子级都为选中时，自己才为选中状态
    isIndeterminate = isIndeterminate || v.isIndeterminate || v.isSelected; // 只要有下级为半选状态或选中状态，自己就为半选状态
  });
  // 自己为全选状态时，半选不生效
  isIndeterminate = isSelected ? false : isIndeterminate;
  // 赋值
  props.option.isSelected = isSelected;
  props.option.isIndeterminate = isIndeterminate;
  // 修改完自己和自己子级，告诉父级更新
  emit("change");
};
</script>
