<template>
  <Modal
    centered
    title="选择文件目录"
    :width="500"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
  >
    <DirectoryTree :loadData="onLoadData" :treeData="treeData" @select="onSelect" />
  </Modal>
</template>

<script lang="ts" name="FileSelectModal" setup>
  import { ref } from 'vue';
  import { getAction } from '../../../../../api/manage';
  import { onMounted } from 'vue';
  import { DirectoryTree, Modal } from 'ant-design-vue'

  const emit = defineEmits(['callback']);
  const visible = ref(false);
  const confirmLoading = ref(false);
  const treeData = ref([]);
  const fileTreeUrl = '/online/cgform/head/fileTree';
  const rootFileUrl = '/online/cgform/head/rootFile';
  const selectedKey = ref<any>('');

  onMounted(() => {
    loadRoot();
  });

  const handleSubmit = () => {
    emit('callback', selectedKey.value);
    visible.value = false;
  };
  const handleCancel = () => {
    visible.value = false;
  };
  const show = () => {
    visible.value = true;
    selectedKey.value = '';
  };
  const loadRoot = () => {
    getAction(rootFileUrl, {}).then((res) => {
      if (res.success) {
        treeData.value = res.result;
      }
    });
  };
  const onLoadData = (treeNode) => {
    return new Promise((resolve) => {
      if (treeNode.dataRef.children) {
        resolve();
        return;
      }
      let params = {
        parentPath: treeNode.dataRef.key
      };
      getAction(fileTreeUrl, params).then((res) => {
        if (res.success) {
          treeNode.dataRef.children = res.result;
          treeData.value = [...treeData.value];
        }
        resolve();
      });
    });
  };
  const onSelect = (selectedKeys) => {
    selectedKey.value = selectedKeys[0];
  };
  defineExpose({ show });
</script>

<style scoped></style>
