<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal basicFormModal"
    @on-ok="handleSubmit"
    @on-close="handleClose"
  >
    <template #default>
      <div>
        <n-checkbox v-model:checked="expandFlag" @update:checked="handleExpand"
          >展开/折叠</n-checkbox
        >
        <n-checkbox v-model:checked="checkedFlag" @update:checked="handleSelectAll"
          >全选/不全选</n-checkbox
        >
        <div>
          <n-tree
            :data="menuTree"
            key-field="id"
            label-field="name"
            children-field="children"
            cascade
            :height="600"
            :checked-keys="checkedKeys"
            :expanded-keys="expandedKeys"
            @update:checked-keys="onChangePermissionsTree"
            ref="treeRef"
            @update:expanded-keys="handleExpands"
            checkable
          />
        </div>
      </div>
    </template>
  </basicModal>
</template>
<script lang="ts" setup>
  import { getRoleMenuList, roleMenuSave } from '@/api/system/role';
  import { buildTree } from '@/utils/auth';
  import { useMessage } from 'naive-ui';
  import { onMounted, ref } from 'vue';
  import { useModal } from '@/components/Modal';
  import { isArray } from '@/utils/is';

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    roleId: {
      type: Number,
      required: true,
      default: 0,
    },
  });

  /**
   * 定义参数变量
   */
  const message = useMessage();
  const emit = defineEmits(['success', 'update:visible']);
  const treeRef = ref();
  const checkedFlag = ref(false);
  const expandFlag = ref(false);
  const allMenuIds = ref([]);
  const checkedKeys = ref([]);
  const expandedKeys = ref([]);
  const menuArray = ref<any[]>([]);
  const menuTree = ref<any[]>([]);

  const [modalRegister, { openModal, setSubLoading }] = useModal({
    title: '分配权限',
    subBtuText: '确定',
    width: 600,
  });
  /**
   * 执行扩展、收缩
   */
  const handleExpand = () => {
    if (expandFlag.value) {
      expandedKeys.value = allMenuIds.value;
    } else {
      expandedKeys.value = [];
    }
  };

  /**
   * 执行选中全部
   */
  const handleSelectAll = () => {
    if (checkedFlag.value) {
      checkedKeys.value = allMenuIds.value;
    } else {
      checkedKeys.value = [];
    }
  };

  // 获取所有选择的节点
  const getDeptAllCheckedKeys = () => {
    const checkedKeys = treeRef.value?.getCheckedData();
    const halfCheckedKeys = treeRef.value?.getIndeterminateData()!;
    checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
    return checkedKeys;
  };

  /**
   * 执行提交表单
   */
  const handleSubmit = async () => {
    const keys = getDeptAllCheckedKeys()!;
    await roleMenuSave({ menuIds: keys, roleId: props.roleId });
    message.success('操作成功');
    emit('update:visible', false);
    emit('success');
  };

  /**
   * 关闭窗体
   */
  const dialogClose = () => {
    emit('update:visible', false);
  };

  /**
   * 树结构选中发生变化
   * @param node 节点
   * @param event 事件
   */
  const onChangePermissionsTree = (node, event) => {
    checkedKeys.value = node;
  };

  const handleExpands = (node) => {
    expandedKeys.value = node;
  };

  /**
   * 设置表单数据
   */
  const setFormData = async () => {
    const data = await getRoleMenuList(props.roleId);
    menuTree.value = buildTree(data);
    menuArray.value = data;
    checkedKeys.value = [];
    menuArray.value.map((item) => {
      if (item.checked) {
        checkedKeys.value.push(item.id);
      }
    });
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    setFormData();
  });
  defineExpose({
    openModal,
  });
</script>
<style lang="less"></style>
