<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    title="分配菜单"
    @ok="handleSubmit"
  >
    <BasicTree
      :checkedKeys="checkedKeys"
      :treeData="treeData"
      checkable
      @check="handleCheck"
      :defaultExpandAll="true"
      :multiple="true"
      :fieldNames="{ key: 'id', title: 'name' }"
    />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicTree } from '/@/components/Tree';
  import { sysPortalAssign, sysPortalQueryMenuTree } from '/@/api/sys/sysPortalApi';

  import { sysMenuQueryTree } from '/@/api/sys/sysMenuApi';

  const emit = defineEmits(['success', 'register']);

  const treeData = ref([]) as any;
  const portalId = ref();
  const checkedKeys = ref([]);
  const halfCheckedKeys = ref([]);
  const parentIds = ref([]) as any;
  onMounted(() => {
    getTreeData();
  });

  const { createMessage, createConfirm } = useMessage();
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    setModalProps({ confirmLoading: false });
    portalId.value = data.record.id;
    // 获取已选中列表
    const roleMenuList = (await sysPortalQueryMenuTree(portalId.value)) || [];
    // 找出菜单的所有父节点ID
    treeData.value.map(item => {
      if (item.children.length) {
        item.children.map(ele => {
          if (ele.children.length) {
            ele.children.map(eles => {
              if (eles.children.length) {
                parentIds.value.push(eles.id);
              }
            });
            parentIds.value.push(ele.id);
          }
        });
        parentIds.value.push(item.id);
      }
    });
    // 因为antd树插件勾选父节点会导致所有子节点选中,所以过滤所有父节点
    halfCheckedKeys.value = Array.from(parentIds.value);
    checkedKeys.value = roleMenuList
      .filter(item => !parentIds.value.includes(item.id))
      .map(item => item.id);
  });

  // 树节点选中事件
  function handleCheck(keys, e) {
    halfCheckedKeys.value = e.halfCheckedKeys;
    checkedKeys.value = keys;
  }

  // 提交按钮事件
  async function handleSubmit() {
    setModalProps({ confirmLoading: true });
    try {
      createConfirm({
        iconType: 'warning',
        title: '提示',
        content: '确认分配权限?',
        onOk: async () => {
          await sysPortalAssign({
            menuIds: checkedKeys.value.concat(halfCheckedKeys.value),
            portalId: portalId.value,
          });
          createMessage.success('分配成功！');
          emit('success', portalId.value);
          closeModal();
        },
      });
    } catch (error) {
      // console.log('error', error);
      createMessage.error((error as unknown as Error).message);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  // 查询树数据
  async function getTreeData() {
    treeData.value = await sysMenuQueryTree({ menuType: ['menu', 'dir'] });
  }
</script>
