<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="移动文件" @ok="handleSubmit">
    <div style="height: 50vh; overflow-y: auto">
      <a-tree
        class="draggable-tree"
        show-icon
        draggable
        block-node
        default-expand-all
        :tree-data="treeData"
        v-model:selectedKeys="selectedKeys"
        :fieldNames="{ children: 'children', title: 'name', key: 'id' }"
      >
        <template #icon="{}">
          <FolderOpenOutlined />
        </template>
      </a-tree>
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { ListMediaFolder, UpdatePicParentKey } from '@/api/demo/mediaLibrary';
  import { FolderOpenOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '@/hooks/web/useMessage';
  const { createMessage } = useMessage();

  const emits = defineEmits(['handleSuccess']);

  // // 上级文件夹的id
  const moveDataList: any = ref([]);
  const selectedKeys: any = ref<string[]>();
  const treeData: any = ref([]);
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    moveDataList.value = data.records;
    ListMediaFolder({}).then((res) => {
      treeData.value = res;
    });
  });

  // 提交
  async function handleSubmit() {
    try {
      if (moveDataList.value.some((item) => item.id == selectedKeys.value)) {
        return createMessage.warn('文件不能移动到自己文件夹内');
      }
      let flag = true;
      moveDataList.value.forEach((movedata) => {
        if (!movedata.objectKey) {
          // 文件夹
          // 查找要移动的文件夹下的文件树
          let tempTreeData = findNodeById(treeData.value, movedata.id);
          let list: any = [];
          list.push(tempTreeData);
          // 要移动到位置是否是自身文件夹下的文件夹
          let tempTreeData2 = findNodeById(list, selectedKeys.value[0], 'parentKey');
          if (tempTreeData2 && tempTreeData2.id != movedata.id) {
            flag = false;
          }
        }
      });
      if (flag) {
        moveDataList.value.forEach((movedata, index) => {
          UpdatePicParentKey({ id: movedata.id, ParentKey: selectedKeys.value[0] }).then((res) => {
            if (index == moveDataList.value.length - 1) {
              createMessage.success('移动成功！');
              emits('handleSuccess');
              closeModal();
            }
          });
        });
      } else {
        return createMessage.warn('文件夹不能移动到自己文件夹的子文件夹内');
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function findNodeById(tree, targetId, idKey = 'id') {
    // 遍历树的每一项
    for (const node of tree) {
      if (node[idKey] === targetId) {
        return node; // 找到了，返回整个节点（包含 children）
      }
      // 如果有 children，递归查找
      if (node.children && Array.isArray(node.children)) {
        const found = findNodeById(node.children, targetId, idKey);
        if (found) return found;
      }
    }
    return null;
  }
</script>

<style lang="less" scoped>
  .floderTitle {
    display: flex;
    align-items: center;
    justify-content: center;
    width: fit-content;
    cursor: pointer;
  }
  ::v-deep .vben-basic-table-header__toolbar {
    display: flex !important;
    justify-content: flex-start !important;
  }
  .floderOtherButton {
    position: absolute;
    right: 0px;
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
  }
  .flodersname {
    max-width: 120px;
    white-space: nowrap; /* 禁止换行 */
    overflow: hidden; /* 超出部分隐藏 */
    text-overflow: ellipsis; /* 超出显示省略号 */
  }
  ::v-deep .ant-table-row-expand-icon {
    display: none !important;
  }
  ::v-deep .ant-table-row-expand-icon-collapsed {
    display: none !important;
  }
</style>
