<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { ExperimentItem, ExperimentCreateItem } from '../types'

import { ElMessage } from 'element-plus'
import { createExperiment, updateExperiment } from '../api'
import { useGetProjectList } from '@/composables/useGetProjectList'
import { useGetCourseList } from '../composables/useGetCourseList'
import { useGetTeacherList } from '../composables/useGetTeacherList'
import { useMapStore } from '@/stores/map'

interface Props {
  data?: ExperimentItem | null
}

const props = defineProps<Props>()

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

// 机构列表
const { organizations } = useGetProjectList()
// 实验类型
const types = useMapStore().getMapValuesByKey('experiment_type')
// 数据状态
const status = useMapStore().getMapValuesByKey('system_status')

const formRef = $ref<FormInstance>()
const form = reactive<ExperimentCreateItem>({
  organ_id: '',
  status: '1',
  course_id: '',
  name: '',
  length: 10,
  type: '',
  score: 100,
  teachers_id: '',
  teachers_ids: []
})
watchEffect(() => {
  if (!props.data) return
  const score = parseFloat(props.data.score)
  const length = parseFloat(props.data.length)
  const teachers_ids = props.data.teacher.map(item => item.id)
  Object.assign(form, props.data, { score, length, teachers_ids })
})

// 课程列表
const { courses, updateCourses } = useGetCourseList()
watchEffect(() => {
  updateCourses(form.organ_id)
})
// 指导教师列表
const { teachers, updateTeachers } = useGetTeacherList()
watchEffect(() => {
  updateTeachers(form.organ_id)
})

const rules = ref<FormRules>({
  organ_id: [{ required: true, message: '请选择实验所属部门/学校' }],
  course_id: [{ required: true, message: '请选择实验课程' }],
  name: [{ required: true, message: '请输入实验名称' }],
  length: [{ required: true, message: '请输入实验学时' }],
  type: [{ required: true, message: '请选择实验类型' }],
  teachers_ids: [{ type: 'array', required: true, message: '请选择指导教师', trigger: 'change' }],
  score: [{ required: true, message: '请输入实验总成绩' }]
})
const isUpdate = $computed(() => {
  return !!form.id
})
const title = $computed(() => {
  return isUpdate ? '编辑实验' : '新增实验'
})
function handleOrgChange() {
  form.course_id = ''
  form.teachers_ids = []
}

// 提交
function handleSubmit() {
  formRef?.validate().then(() => {
    const params = {
      ...form,
      teachers_id: form.teachers_ids?.join(',') || ''
    }
    isUpdate ? handleUpdate(params) : handleCreate(params)
  })
}
// 新增
function handleCreate(params: ExperimentCreateItem) {
  createExperiment(params).then(() => {
    ElMessage({ message: '创建成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
// 修改
function handleUpdate(params: ExperimentCreateItem) {
  updateExperiment(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="$emit('update:modelValue')">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="实验所属部门/学校" prop="organ_id">
        <el-select v-model="form.organ_id" style="width: 100%" :disabled="isUpdate" @change="handleOrgChange">
          <el-option v-for="item in organizations" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="实验课程" prop="course_id">
        <el-select v-model="form.course_id" style="width: 100%" :disabled="isUpdate">
          <el-option v-for="item in courses" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="实验名称" prop="name">
        <el-input v-model="form.name" :disabled="isUpdate" />
      </el-form-item>
      <el-form-item label="实验学时" prop="length">
        <el-input-number v-model="form.length" :min="1" :max="20" step-strictly style="width: 100%" />
      </el-form-item>
      <el-form-item label="指导教师" prop="teachers_ids">
        <el-select v-model="form.teachers_ids" multiple style="width: 100%">
          <el-option v-for="item in teachers" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="实验类型" prop="type">
        <el-select v-model="form.type" style="width: 100%">
          <el-option v-for="item in types" :key="item.id" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="实验总成绩" prop="score">
        <el-input-number v-model="form.score" :min="1" :max="150" step-strictly style="width: 100%" />
      </el-form-item>
      <el-form-item label="有效状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio v-for="item in status" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </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>
