<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="压缩" @ok="handleSubmit">
    <div class="ziplist">
      待压缩文件：
      <div class="zip" v-for="(zip, index) in zipS" :key="zip.id">
        <span>{{ zip.name }}</span>
        <CloseOutlined @click="deleteZip(index)" />
      </div>
    </div>
    <div style="height: 200px; border: 1px solid black; padding-top: 10px">
      压缩文件存放目录：
      <a-tree
        :tree-data="treeData"
        :field-names="{
          key: 'id',
          title: 'name',
        }"
        v-model:selectedKeys="selectedKeys"
        default-expand-all
        :height="200"
        :showIcon="true"
        :autoExpandParent="true"
        :defaultExpandAll="true"
      >
        <template #icon="{ children }">
          <template v-if="children">
            <FolderOutlined />
          </template>
        </template>
      </a-tree>
    </div>
    <div style="height: 80px; padding: 10px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { CloseOutlined, FolderOutlined } from '@ant-design/icons-vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { compressFileSchema } from '../modal.data';
  import { orgPosGroup } from '@/api/demo/system';
  import { useMessage } from '@/hooks/web/useMessage';
  const { createMessage } = useMessage();

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

  // 压缩文件名称
  const compressName = ref('');
  // 目标文件
  const zipS: any = ref([]);
  // 减少
  function deleteZip(index: number) {
    if (zipS.value.length !== 1) {
      zipS.value.splice(index, 1);
    } else {
      createMessage.info('至少要保留一个文件');
    }
  }

  // form
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: compressFileSchema,
    showActionButtonGroup: false,
  });

  // 压缩文件存放目录
  const selectedKeys: any = ref<string[]>();
  // 树目录
  const treeData = ref([]);
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    // 过滤掉非文件夹
    treeData.value = filterTreeByType(data.tableData);
    zipS.value = data.record.map((item) => item);
  });

  // 提交
  async function handleSubmit() {
    try {
      const values = await validate();
      let query = {
        zipS: zipS.value.map((item) => item.id),
        key: selectedKeys.value[0],
        compressName: values.compressName,
      };
      // 调用接口
      const data = await orgPosGroup(query);
      if (data) {
        setModalProps({ confirmLoading: true });
        closeModal();
        emit('success');
        return createMessage.success('成功');
      } else {
        return createMessage.error('失败');
      }
    } 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>
<style lang="scss" scoped>
  .ziplist {
    height: 200px;
    border: 1px solid black;
  }
  .zip {
    padding-left: 10px;
    padding-right: 10px;
    display: flex;
    justify-content: space-between; /* 让子元素分布在两侧 */
    align-items: center; /* 垂直居中对齐 */
    width: 100%;
  }
</style>
