<template>
  <div class="qx-dialog">
    <el-dialog title="分配权限" width="800px" :model-value="modelValue" :before-close="closed">
      <el-tree ref="treeRef" :data="allPermission" :props="defaultProps" node-key="id" show-checkbox v-loading="loading"
        :check-strictly="false">
      </el-tree>
      <template #footer>
        <div>
          <el-button type="primary" @click="onComfirm"><el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span> </el-button>
          <el-button @click="closed"> <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span></el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { defineProps, watch, ref, getCurrentInstance } from "vue";
import { saveRoleMenuInfo, getRoleMenuIds, getMenuTree } from "@/api/user-manage";
const loading = ref(false)
const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  roleId: {
    type: String,
    required: true
  }
});
const allPermission = ref([]);
const treeRef = ref(null);
//属性结构配置
const defaultProps = {
  children: "sysMenuList",
  label: "menuName"
};
const emits = defineEmits(["update:modelValue", "updateRole"]);
const closed = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      emits("update:modelValue", false);
    })
    .catch(() => {
      // catch error
    })

};
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      getPermissionList();
    }
  },
  { immediate: true, deep: true }
);
const onComfirm = () => {
  let params = {
    roleId: props.roleId,
    menuIds: treeRef.value.getCheckedKeys(),
    otherMenuIds: treeRef.value.getHalfCheckedKeys()
  };
  saveRoleMenuInfo(params).then(() => {
    ElMessage.success("操作成功");
  });
  emits("update:modelValue", false);
};
//所有权限
const getPermissionList = async () => {
  loading.value = true
  const res = await getMenuTree();
  allPermission.value = res;
  getRolePermission();
  loading.value = false
};
//当前角色权限
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();
  if (thisNode.checked) {
    for (let i = thisNode.level; i > 1; i--) {
      if (!thisNode.parent.checked) {
        thisNode = thisNode.parent;
        keys.push(thisNode.data.id);
      }
    }
  }
  treeRef.value.setCheckedKeys(keys);
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  height: 41vh !important;
}
</style>
