<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Form, Input, message } from 'ant-design-vue';

import { createVideoTask } from '#/api/cv/iva';

const projectName = ref('');
const year = ref<null | number>(null);
const month = ref<null | number>(null);
const day = ref<null | number>(null);
const hours = ref<null | number>(null);
const minutes = ref<null | number>(null);
const seconds = ref<null | number>(null);
const fileName = ref('');
const selectedFile = ref<File | null>(null);
const fileInputRef = ref<HTMLInputElement | null>(null);

const [Modal, modalApi] = useVbenModal({
  title: '新建蚕茧分析任务',
  class: 'w-[600px]',
  onCancel() {
    modalApi.close();
  },
  onConfirm() {
    if (!projectName.value || !selectedFile.value) {
      message.warning('请填写项目名并选择蚕茧图片');
    }
    uploadFile();
  },
});

async function uploadFile() {
  const formData = new FormData();
  formData.append('file', selectedFile.value!);
  formData.append('projectName', projectName.value);
  await createVideoTask(formData).then(() => {
    message.success('任务创建成功，正在处理图像，请稍后刷新列表查看');
    modalApi.close();
    // 清空表单
    projectName.value = '';
    year.value = null;
    month.value = null;
    day.value = null;
    hours.value = null;
    minutes.value = null;
    seconds.value = null;
    fileName.value = '';
    selectedFile.value = null;
  });
}

function selectFile() {
  fileInputRef.value?.click();
}

function handleFileChange(event: Event) {
  const files = (event.target as HTMLInputElement).files;
  if (files && files.length > 0) {
    selectedFile.value = files[0];
    fileName.value = files[0]!.name;
  }
}
</script>

<template>
  <Modal>
    <Form layout="vertical">
      <Form.Item label="项目名*" required>
        <Input v-model:value="projectName" />
      </Form.Item>

      <Form.Item label="上传图片*" required>
        <div
          @click="selectFile"
          style="
            padding: 16px;
            text-align: center;
            cursor: pointer;
            border: 1px dashed #d9d9d9;
          "
        >
          {{ fileName || '点击选择文件' }}
          <input
            type="file"
            accept="image/*"
            ref="fileInputRef"
            @change="handleFileChange"
            style="display: none"
          />
        </div>
      </Form.Item>
    </Form>
  </Modal>
</template>
