<template>
  <el-form
    ref="form"
    :model="caseFile"
    label-width="90px"
    class="camera-from dispatch-file-from"
  >
    <el-form-item label="附件标题：" class="mandatory">
      <el-input
        v-model="caseFile.filesTitle"
        placeholder="请输入最多不能超过50字"
        maxlength="50"
        show-word-limit
      ></el-input>
    </el-form-item>
    <el-form-item label="附件：" class="mandatory">
      <el-upload
        class="upload-demo"
        :multiple="false"
        :limit="1"
        :before-upload="upload"
        :on-preview="previewFile"
        :accept="accept"
        :before-remove="removeFile"
      >
        <el-button type="primary" :disabled="!!file">
          <el-icon><Upload /></el-icon>上传
        </el-button>
        <template v-slot:tip>
          <div class="el-upload__tip">注：可上传{{ size }}以内的{{ format }}</div>
        </template>
      </el-upload>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { DrawFormats, FileDrawType, OtherFormats } from "@/constant/caseFile";
import { maxFileSize } from "@/constant/caseFile";
import { useUpload } from "@/hook/upload";
import { CaseFile, addCaseFile } from "@/store/caseFile";
import { ElMessage } from "element-plus";
import { ref, watchEffect } from "vue";
import { QuiskExpose } from "@/helper/mount";

const props = defineProps<{
  caseId: number;
  fileType: number;
}>();

const caseFile = ref<CaseFile>({
  caseId: props.caseId,
  filesTypeId: props.fileType,
  filesTitle: "",
} as any);

const { size, format, upload, removeFile, previewFile, file, accept } = useUpload({
  maxSize: maxFileSize,
  formats: props.fileType === FileDrawType ? DrawFormats : OtherFormats,
});

watchEffect(() => {
  if (file.value?.name) {
    caseFile.value.filesTitle = file.value?.name;
  }
});

defineExpose<QuiskExpose>({
  async submit() {
    if (!file.value) {
      ElMessage.error("请上传附件");
      throw "请上传附件";
    } else if (!caseFile.value.filesTitle.trim()) {
      ElMessage.error("附件标题不能为空！");
      throw "附件标题不能为空！";
    }

    await addCaseFile({ ...caseFile.value, file: file.value });
    return caseFile.value;
  },
});
</script>
