<template>
  <BasicModal v-bind="$attrs" @register="registerTreeModal" destroyOnClose title="选择文件夹" @ok="handleSubmit">
    <a-tree v-model:selectedKeys="selectedKeys" v-model:expandedKeys="expandedKeys" :tree-data="treeData" :disabled="isDisabled" @select="onSelect">
      <template #title="{ key: treeKey, title, otherData }">
        <span>{{ title }}</span>
      </template>
    </a-tree>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { loadTreeData } from '../DocFilesDir.api';
  import { saveOrUpdate } from '../DocFiles.api';

  // Emits声明
  const emit = defineEmits(['register', 'success', 'edit-success']);
  defineProps({
    rootTreeData: { type: Array, default: () => [] },
  });
  const isDisabled = ref<boolean>(false);
  // 当前是否是更新模式
  const isUpdate = ref<boolean>(false);

  const record = ref<object>({});
  let treeData = ref([]);
  const expandedKeys = ref<string[]>([]);
  const selectedKeys = ref<string[]>([]);
  //表单赋值
  const [registerTreeModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    record.value = unref(data?.record);
    //重置表单
    iniTreeData();
    setModalProps({ confirmLoading: false, showCancelBtn: true, showOkBtn: true });
    isUpdate.value = !!data?.isUpdate;
  });

  async function iniTreeData() {
    treeData.value = await loadTreeData({});
  }

  const newFileId = ref();
  function onSelect(selectedKeys, e) {
    newFileId.value = selectedKeys[0];
  }
  //表单提交事件
  async function handleSubmit() {
    try {
      setModalProps({ confirmLoading: true });
      record.value.ctp = newFileId.value;
      let values = record.value;
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      await nextTick();
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success', values);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
