<template>
  <div>
    <el-dialog
      title="分配权限"
      width="500px"
      :model-value="modelValue"
      :destroy-on-close="true"
      @close="closed"
    >
      <div class="treeCnt">
        <el-tree
          ref="treeRef"
          :data="allPermission"
          :props="defaultProps"
          node-key="id"
          show-checkbox
          default-expand-all
          :check-strictly="true"
          @check="checkeTree"
        >
        </el-tree>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closed">取消</el-button>
          <el-button type="primary" @click="onComfirm">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { defineProps, watch, ref, onMounted, nextTick } from "vue";
import {
  saveRoleMenuInfo,
  getRoleMenuIds,
  getMenuTree
} from "@/api/user-manage";
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  roleId: {
    type: String,
    required: true
  }
});
const form = ref({});

const emits = defineEmits(["update:modelValue", "updateRole"]);
const closed = () => {
  emits("update:modelValue", false);
};

const onComfirm = () => {
  let params = {
    roleId: Number(props.roleId),
    menuIds: treeRef.value.getCheckedKeys().map((item) => Number(item))
  };
  saveRoleMenuInfo(params).then((res) => {
    ElMessage.success("操作成功");
  });
  closed();
};

//所有权限
const allPermission = ref([]);
const getPermissionList = async () => {
  const res = await getMenuTree();
  allPermission.value = res;
};
getPermissionList();

const treeRef = ref(null);
//属性结构配置
const defaultProps = {
  children: "sysMenuList",
  label: "menuName"
};
//当前角色权限
const getRolePermission = async () => {
  const checkedKeys = await getRoleMenuIds(props.roleId);
  treeRef.value.setCheckedKeys(checkedKeys);
};

// 选中子节点，默认选中父节点
const checkeTree = (data) => {
  let thisNode = treeRef.value.getNode(data.id); // 获取当前节点
  const keys = treeRef.value.getCheckedKeys(); // 获取已勾选节点的key值
  if (thisNode.checked) {
    // 当前节点若被选中
    for (let i = thisNode.level; i > 1; i--) {
      // 判断是否有父级节点
      if (!thisNode.parent.checked) {
        // 父级节点未被选中，则将父节点替换成当前节点，往上继续查询，并将此节点key存入keys数组
        thisNode = thisNode.parent;
        // keys.push(thisNode.data.id);
      }
    }
  }
  treeRef.value.setCheckedKeys(keys); // 将所有keys数组的节点全选中
};

watch(
  () => props.roleId,
  (val) => {
    if (val) {
      getRolePermission();
    }
  },
  {
    immediate: true,
    deep: true
  }
);
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  max-height: 80vh;
  .treeCnt {
    height: 65vh;
    overflow: hidden;
    overflow-y: auto;
  }
}
</style>
