<script setup lang="ts">
import type { UploadFile } from 'element-plus';
import { Upload } from '@element-plus/icons-vue';

import { ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { Inbox } from '@element-plus/icons-vue';

import { ElUpload } from 'element-plus';

import { workflowDefinitionImport } from '#/api/workflow/definition';

const emit = defineEmits<{ reload: [] }>();



const [BasicDrawer, drawerApi] = useVbenDrawer({
  onCancel: handleCancel,
  onConfirm: handleSubmit,
  fullscreenButton: false,
  title: '流程部署'
});

const fileList = ref<UploadFile[]>([]);

async function handleSubmit() {
  try {
    drawerApi.drawerLoading(true);
    if (fileList.value.length !== 1) {
      handleCancel();
      return;
    }
    const data = {
      file: fileList.value[0]!.raw as Blob,
      category: drawerApi.getData().category,
    };
    await workflowDefinitionImport(data);
    emit('reload');
    handleCancel();
  } catch (error) {
    console.warn(error);
    drawerApi.close();
  } finally {
    drawerApi.drawerLoading(false);
  }
}

function handleCancel() {
  drawerApi.close();
  fileList.value = [];
}
</script>

<template>
  <BasicDrawer :close-on-click-modal="false">
    <!-- z-index不设置会遮挡模板下载loading -->
    <!-- 手动处理 而不是放入文件就上传 -->
    <ElUpload
      v-model:file-list="fileList"
      :auto-upload="false"
      :limit="1"
      accept="application/json"
      drag
    >
      <template #default>
        <div class="flex items-center justify-center">
          <Inbox class="text-primary size-[48px]" />
        </div>
        <p>点击或者拖拽到此处上传[json]文件</p>
      </template>
    </ElUpload>
  </BasicDrawer>
</template>
