<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.name }}
        </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>
export default {
  name: "BgPermissionOption",
  props: {
    option: {
      type: Object,
      require: true,
    }, // 数据项
    depth: {
      type: Number,
      default: 0,
    },
    deep: {
      type: Number,
      default: 1,
    },
  },
  methods: {
    changeSelf() {
      let isSelected = this.option.isSelected;
      let children = this.option.children || [];

      // 将自己的选中状态赋值给子级
      if (children.length > 0) {
        children.forEach((v, i) => {
          v.isSelected = isSelected;

          this.$nextTick(() => {
            this.$refs[`child${i}`][0].changeSelf();
          });
        });
      }

      // 关于自己选中都是全选和不选，所以不存在半选状态
      this.option.isIndeterminate = false;

      // 修改完自己和自己子级，告诉父级更新
      this.$emit("change");
    }, // 本级选中状态发生变化
    changeChild() {
      let isSelected = true;
      let isIndeterminate = false;
      let children = this.option.children;

      children.forEach((v, i) => {
        isSelected = isSelected && v.isSelected; // 所有子级都为选中时，自己才为选中状态
        isIndeterminate = isIndeterminate || v.isIndeterminate || v.isSelected; // 只要有下级为半选状态或选中状态，自己就为半选状态
      });

      // 自己为全选状态时，半选不生效
      isIndeterminate = isSelected ? false : isIndeterminate;

      // 赋值
      this.option.isSelected = isSelected;
      this.option.isIndeterminate = isIndeterminate;

      // 修改完自己和自己子级，告诉父级更新
      this.$emit("change");
    }, // 下级选中状态发生变化
  },
};
</script>
