<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="移动文件" @ok="handleSubmit">
    <a-tree
      :tree-data="treeData"
      :field-names="{
        key: 'id',
        title: 'name',
      }"
      v-model:selectedKeys="selectedKeys"
      default-expand-all
      :height="300"
      :showIcon="true"
      :autoExpandParent="true"
      :defaultExpandAll="true"
    >
      <template #icon="{ children }">
        <template v-if="children">
          <FolderOutlined />
        </template>
      </template>
    </a-tree>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { FolderOutlined } from '@ant-design/icons-vue';
  import { orgPosGroup } from '@/api/demo/system';
  import { useMessage } from '@/hooks/web/useMessage';
  const { createMessage } = useMessage();

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

  // 上级文件夹的id
  const moveIds: any = ref([]);
  const selectedKeys: any = ref<string[]>();
  const treeData = ref([]);

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    // 过滤掉非文件夹
    treeData.value = filterTreeByType(data.tableData);
    moveIds.value = data.record.map((item) => item);
  });

  // 提交
  async function handleSubmit() {
    try {
      let ids = moveIds.value.map((item) => item.id);
      let key = selectedKeys.value[0];
      if (!ids.includes(key)) {
        let query = {
          moveIds: ids,
          key: key,
        };
        // 调用接口
        const data = await orgPosGroup(query);
        if (data) {
          setModalProps({ confirmLoading: true });
          closeModal();
          emit('success');
          return createMessage.success('成功');
        } else {
          return createMessage.error('失败');
        }
      } else {
        return createMessage.warn('目标目录不能包含选择目录');
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  // 过滤掉非文件夹
  function filterTreeByType(tree) {
    function recurse(nodes) {
      const filteredNodes: any = [];
      for (let node of nodes) {
        // 如果当前节点是 folder 类型
        if (node.type === 'folder') {
          // 深拷贝原对象，避免修改原始数据
          const newNode = { ...node };
          // 如果有 children，则递归处理
          if (node.children && node.children.length > 0) {
            const children = recurse(node.children);
            newNode.children = children;
          } else {
            newNode.children = []; // 没有 children 也保留为空数组
          }
          // 无论如何，只要是 folder 类型就 push 到结果里
          filteredNodes.push(newNode);
        }
      }
      return filteredNodes;
    }
    return recurse(tree);
  }
</script>
