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

interface Props {
  data: Contest
}

const props = defineProps<Props>()

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

const route = useRoute()

const formRef = $ref<FormInstance>()
const form = reactive<any>({ files: [] })

async function fetchInfo() {
  const res = await getExperimentReport({
    competition_id: props.data.id,
    platform_key: route.query.type as string
  })
  const detail = res.data.detail
  form.files = detail.id ? [detail] : []
}
onMounted(fetchInfo)

const rules = ref<FormRules>({
  files: [{ required: true, message: '请上传实验报告文件', trigger: 'blur' }]
})
// 提交
function handleSubmit() {
  formRef?.validate().then(update)
}
// 修改
const update = () => {
  const [file] = form.files
  uploadExperimentReport({
    competition_id: props.data.id,
    platform_key: route.query.type as string,
    name: file.name,
    url: file.url,
    size: file.size,
    desc: file.name
  }).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>
