<script setup lang="ts">
import { Upload } from '@element-plus/icons-vue'
import { useFileDialog } from '@vueuse/core'
import { ElMessage } from 'element-plus'
import { useFilterList } from '../composables/useFilterList'
import { importScore } from '../api'

const emit = defineEmits<{
  (e: 'update'): void
}>()

const { competitions } = useFilterList(1)
const form = reactive<any>({
  competition_id: ''
})

const templateUrl = $computed(() => {
  return form.competition_id ? `/api/lab//v1/expert/check/import-score?competition_id=${form.competition_id}` : ''
})
// 批量导入完整评分
const { files, open, reset } = useFileDialog()
function handleImport() {
  if (!form.competition_id) return
  open({
    accept: '.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
    multiple: false
  })
}
watchEffect(() => {
  if (!files.value?.length) return
  const [file] = files.value
  importScore({ competition_id: form.competition_id, file }).then(() => {
    ElMessage({ message: '导入成功', type: 'success' })
    emit('update')
  })
  reset()
})
</script>

<template>
  <el-dialog title="批量导入完整评分" :close-on-click-modal="false" width="400px">
    <el-form label-width="70px">
      <el-form-item label="赛项名称">
        <el-select v-model="form.competition_id">
          <el-option v-for="item in competitions" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <a :href="templateUrl" download style="margin-left: 10px" v-if="templateUrl">下载模板</a>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          round
          :icon="Upload"
          @click="handleImport"
          :disabled="!form.competition_id"
          style="width: 195px"
          >本地上传</el-button
        >
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
