<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 { sysPackageAssign, sysPackageQueryMenuTree } from '/@/api/sys/sysTenantPackageApi';

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

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

  const treeData = ref([]) as any;
  const packageId = 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 });
    packageId.value = data.record.id;
    // 获取已选中列表
    const roleMenuList = (await sysPackageQueryMenuTree(packageId.value)) || [];
    debugger;
    // 找出菜单的所有父节点ID
    treeData.value.map(item => {
      if (item.children.length) {
        item.children.map(ele => {
          if (ele.children.length) {
            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) && item.parentId != '0') || item.menuType == 'menu',
      )
      .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 sysPackageAssign({
            menuIds: checkedKeys.value.concat(halfCheckedKeys.value),
            packageId: packageId.value,
          });
          createMessage.success('分配成功！');
          emit('success', packageId.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({});
  }
</script>
