<template>
  <vxe-modal
    resize
    v-model="showModal"
    @hide="onHide"
    title="菜单权限分配"
    width="800px"
    show-maximize
    show-footer
    esc-closable
  >
    <el-tree
      ref="treeRef"
      :data="menuData"
      show-checkbox
      node-key="id"
      default-expand-all
      :default-checked-keys="defaultCheckedKeys"
      :props="defaultProps"
    />
    <template #footer>
      <el-button type="default" @click="showModal = false">取消</el-button>
      <el-button :loading="loading" type="primary" @click="submitForm">提交</el-button>
    </template>
  </vxe-modal>
</template>

<script setup name="AllocationUserModal">
  import { ref, onMounted, reactive, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import { getMenuTree } from '@/api/menu';
  import { saveRole } from '@/api/role';

  const defaultProps = {
    children: 'children',
    label: 'title',
  };
  const emits = defineEmits(['success']);
  const currentRole = ref(null);
  const showModal = ref(false);
  const treeRef = ref(null);
  const menuData = ref([]);
  const defaultCheckedKeys = computed(() => currentRole.value?.menus.map((v) => v.id) || []);

  const loading = ref(false);
  const submitForm = async () => {
    try {
      // 获取全选中节点
      const checkedNodes = treeRef.value.getCheckedNodes();
      // 获取半选中节点
      const halfCheckedNodes = treeRef.value.getHalfCheckedNodes();
      if (!checkedNodes.length) {
        return ElMessage.info('请选择要设置的权限！');
      }
      loading.value = true;
      const params = {
        ...currentRole.value,
        menus: checkedNodes.map((v) => ({ id: v.id })),
        // menus: [...checkedNodes, ...halfCheckedNodes].map((v) => ({ id: v.id })),
      };

      await saveRole(params);
      emits('success');
      ElMessage({
        type: 'success',
        message: '设置成功!',
        plain: true,
      });
      showModal.value = false;
    } catch {}
    loading.value = false;
  };
  const onHide = () => {
    currentRole.value = null;
    treeRef.value.setCheckedNodes([]);
  };
  const openModal = (role) => {
    currentRole.value = role;
    showModal.value = true;
  };

  const initTreeData = async () => {
    const { result } = await getMenuTree();
    menuData.value = result;
  };

  onMounted(() => {
    initTreeData();
  });

  defineExpose({
    openModal,
  });
</script>
