<script setup lang="ts">
import type { UploadFile } from 'element-plus';
import { ref } from 'vue';
import { $t } from '@vben/locales';
import { ElIcon, ElUpload } from 'element-plus';
import { useVbenDrawer } from '@vben/common-ui';
import { workflowDefinitionImport } from '#/api/workflow/definition';
import { Box } from '@element-plus/icons-vue';

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

// 侧拉内置容器
const [Drawer, DrawerApi] = useVbenDrawer({
  // 点击侧拉的确定按钮执行逻辑
  async onConfirm() {
    try {
      DrawerApi.drawerLoading(true);
      if (fileList.value.length !== 1) {
        return;
      }
      const data = {
        file: fileList.value[0]!.raw as Blob,
        category: DrawerApi.getData().category,
      };
      await workflowDefinitionImport(data);
      emit('reload');
      DrawerApi.close();
      fileList.value = [];
    } catch (error) {
      console.warn(error);
    } finally {
      DrawerApi.drawerLoading(false);
    }
  },
  async onOpenChange(isOpen) {
    if (!isOpen) {
      fileList.value = [];
      return;
    }
  },
});
</script>

<template>
  <Drawer
    :close-on-click-modal="false"
    :fullscreen-button="false"
    title="流程部署"
    class="w-[500px]"
  >
    <!-- 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">
          <ElIcon class="text-primary size-[48px]">
            <Box />
          </ElIcon>
        </div>
        <p>点击或者拖拽到此处上传[json]文件</p>
      </template>
    </ElUpload>
  </Drawer>
</template>
