<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { ExperimentInfo, ExperimentRecord } from '../types'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { uploadExperimentReport } from '../api'

interface Props {
  data: ExperimentInfo
}

const props = defineProps<Props>()

const detail = $ref(inject<ExperimentRecord>('detail'))

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const formRef = $ref<FormInstance>()
const form = reactive<any>({ files: [] })
watchEffect(() => {
  form.files = detail?.file ? [detail.file] : []
})
const rules = ref<FormRules>({
  files: [{ required: true, message: '请上传实验报告文件', trigger: 'blur' }]
})
// 提交
function handleSubmit() {
  formRef?.validate().then(update)
}
// 修改
const update = () => {
  const [file] = form.files
  uploadExperimentReport({
    experiment_id: props.data.id,
    file: JSON.stringify({ name: file.name, url: file.url, upload_time: dayjs().format('YYYY-MM-DD HH:mm:ss') })
  }).then(() => {
    ElMessage({ message: '上传成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog title="上传实验报告" :close-on-click-modal="false" width="600px" @update:modelValue="value => $emit('update:modelValue', value)">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item label="实验报告文件" prop="files">
        <AppUpload
          v-model="form.files"
          :limit="1"
          accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.pdf,application/pdf,.ppt,.pptx,application/vnd.ms-powerpoint">
          <template #tip>实验报告文件只能上传一个，支持格式包含：doc docx pdf ppt pptx，大小不超过50M</template>
        </AppUpload>
      </el-form-item>
      <el-row justify="center">
        <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>
