<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { pick } from 'lodash-es'
import { updateExam, getAllExamList } from '../api'

interface Props {
  id: string
  data?: any
  type: string
}
const props = defineProps<Props>()

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

const formRef = ref<FormInstance>()
const form = reactive<any>({
  experiment_id: props.id,
  exam_id: ''
})
watchEffect(() => {
  if (!props.data) return
  Object.assign(form, props.data)
})

const rules = ref<FormRules>({
  exam_id: [{ required: true, message: '请选择考试', trigger: 'change' }]
})
const isUpdate = $computed(() => {
  return !!props.data?.id
})
const title = computed(() => {
  return isUpdate ? '编辑理论考试' : '新增理论考试'
})

const examList = ref<Record<string, any>[]>([])
// 获取关联考试列表
function fetchExamList() {
  getAllExamList({ project: 'x1', 'per-page': 1000 }).then(res => {
    examList.value = res.data.list || []
  })
}
onMounted(() => {
  fetchExamList()
})
// 提交
function handleSubmit() {
  formRef.value?.validate().then(() => {
    const params = Object.assign({ type: props.type }, pick(form, ['experiment_id', 'exam_id']))
    isUpdate ? handleUpdate(params) : handleUpdate(params)
  })
}

// 修改
function handleUpdate(params: any) {
  params.id = props.data?.id
  updateExam(params).then(() => {
    ElMessage({ message: '修改成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog :title="title" :close-on-click-modal="false" width="600px" @update:modelValue="value => $emit('update:modelValue', value)">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
      <el-form-item label="考试名称" prop="exam_id">
        <el-select v-model="form.exam_id" filterable style="width: 100%">
          <el-option v-for="item in examList" :key="item.exam_id" :label="item.name" :value="item.exam_id"></el-option>
        </el-select>
      </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>
