<!-- PermissionTree.vue -->
<template>
  <div class="hander" v-loading="loading">
    <div v-for="(item, index) in newPermissionTree" :key="index" class="permission-item">
      <div class="list">
        <div class="t1_line">{{ item.title }}</div>
      </div>
      <el-checkbox-group :value="newSelectedPermissions">
          <template v-for="(group, groupIndex) in item.children">
                <el-row :key="group.id">
                  <el-col :span="23" class="level-two-title">
                    <div>
                      <el-checkbox
                        :label="group.id"
                        :indeterminate="group.indeterminate"
                        :checked="group.check"
                        class="level-two-label"
                        @change="handleLevelChange(group.level,$event, { index, groupIndex })"
                      >
                        <span>{{ group.title }}：</span>
                      </el-checkbox>
                    </div>
                  </el-col>
                </el-row>

                <template v-for="(subGroup, subGroupIndex) in group.children">
                  <div :key="subGroup.id" class="threetitle-container">
                    <el-row>
                      <el-col :span="22" :offset="1">
                        <div class="level-three-title">
                          <el-checkbox
                            :label="subGroup.id"
                            :checked="subGroup.check"
                            :indeterminate="subGroup.indeterminate"
                            class="level-three-item"
                            @change="handleLevelChange(subGroup.level,$event, { index, groupIndex, subGroupIndex})"
                          >
                            <span>{{ subGroup.title }}：</span>
                          </el-checkbox>

                          <el-checkbox
                            v-for="(leaf, leafIndex) in subGroup.children"
                            :key="leaf.id"
                            :label="leaf.id"
                            :checked="leaf.check"
                            class="level-four-item"
                            @change="handleLevelChange(leaf.level,$event, { index, groupIndex, subGroupIndex, leafIndex })"
                          >
                            {{ leaf.title }}
                          </el-checkbox>
                        </div>
                      </el-col>
                    </el-row>
                  </div>
                </template>
              </template>
      </el-checkbox-group>
    </div>
    <el-button size="small" type="primary" @click="save">保 存</el-button>
  </div>
</template>

<script>
export default {
  name: 'ZrPermissionTree',
  data() {
			return {
        newPermissionTree:[],
        newSelectedPermissions:[]
      }
  },
  props: {
    permissionTree: {//树型结构
      type: Array,
      required: true,
      default: () => []
    },
    selectedPermissions: {//选中的权限
      type: Array,
      required: true,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    permissionTree: {
      handler(val) {
        this.newPermissionTree = val
      },
      deep: true,
      immediate: true
    },
    selectedPermissions: {
      handler(newVal) {
        this.newSelectedPermissions = newVal
        this.get_config(this.newSelectedPermissions)
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
      save(){
        this.$emit('save',this.newSelectedPermissions)
      },
      get_config(newSelectedPermissions){//初次进来数据渲染处理
      let myset = new Set(newSelectedPermissions);
      function mapList(list) {
        return list.map(item => {
          if (item.children && item.children.length)
            item.children = mapList(item.children);
          /**
           * 判断当前id是否在 已选权限列表中  如果在  设置check 为true 并将将父级id增加进去
           * 再判断 当前 子选项中  check是否全为true
           */
          if (myset.has(item.id)) {
              item.check = true;
              if (item.children && item.children.length)
                item.indeterminate = item.level === 2 ?
                  item.children.findIndex(item => !item.check) !==
                  -1 : item.children.filter(item => item.indeterminate).length !== 0

              if (item.pid) myset.add(item.pid);
            } else {
              item.check = false
              item.indeterminate = false
            }
            return item;
        });
      }
      this.newPermissionTree = mapList(this.newPermissionTree);
      this.newSelectedPermissions = Array.from(myset)
    },
   handleLevelChange(level, e, data) {
      let list = [...this.newPermissionTree];
      let node = list;
      if (level === 1) {
        const { index, groupIndex } = data;
        node = list[index].children[groupIndex];
      } else if (level === 2) {
        const { index, groupIndex, subGroupIndex } = data;
        node = list[index].children[groupIndex].children[subGroupIndex];
      } else if (level === 3) {
        const { index, groupIndex, subGroupIndex, leafIndex } = data;
        node = list[index].children[groupIndex].children[subGroupIndex].children[leafIndex];
      }
      // 设置当前节点的 check 状态
      node.check = e;
      // 如果有子节点，递归设置所有子节点的 check 状态
      if (node.children && node.children.length) {
        this.setChildrenCheckStatus(node.children, e);
      }
      // 更新整棵树状态
      this.update(list);
    },
    setChildrenCheckStatus(children, status) {
      children.forEach(child => {
        child.check = status;
        if (child.children && child.children.length) {
          this.setChildrenCheckStatus(child.children, status);
        }
      });
    },
    update(list) {
    // 同原逻辑，但更集中管理
        let checkbox = new Set();
        function mapList(items) {
          return items.map(item => {
            if (item.children?.length) {
              item.children = mapList(item.children);
              item.check = item.children.some(v => v.check);
              item.indeterminate =
                item.level === 2
                  ? item.check && !item.children.every(v => v.check)
                  : item.check &&
                    item.children.some(v => v.check && v.indeterminate);
            }
            if (item.check) checkbox.add(item.id);
            return item;
          });
        }
        list = mapList(list);
        this.newSelectedPermissions = Array.from(checkbox);
        this.newPermissionTree = list;
      },  
  }
};
</script>

<style lang="less">
.hander {
  .list {
    .t1_line {
      font-size: 16px;
      font-weight: 600;
      color: #333333;
      margin-left: 10px;
      position: relative;
      padding-left: 10px;

      &::after {
        content: '';
        width: 3px;
        height: 16px;
        background-color: #2b54e4;
        position: absolute;
        top: 0;
        left: 0;
      }
    }
  }
  .threetitle-container{
    // margin-bottom: 10px;
  }
  .level-two-title {
      margin: 20px 0;
      margin-left: 22px;
      font-size: 16px;
      margin-bottom: 6px;
    .as {
      display: flex;
    }
  }

  .level-three-title {
     margin-left: 8px;
     font-size: 14px;
     display: flex;
     flex-wrap: wrap;
  }
  .level-two-label{
    .el-checkbox__label{
      font-size: 16px !important;
    }
  }
   .level-three-item {
    margin-right: 10px;
    }
  .level-four-item {
    margin-right: 10px;
  }
}
</style>