<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import type { ExperimentItem } from '../types'
import { ElMessage } from 'element-plus'
import { copyExperiment } from '../api'
import { useGetProjectList } from '@/composables/useGetProjectList'
import { useGetTeacherList } from '../composables/useGetTeacherList'
import { pickBy } from 'lodash-es'
const props = defineProps<{
  data: ExperimentItem
}>()
const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const formRef = ref<FormInstance>()

const form = reactive({
  experiment_name: '',
  organ_id: '',
  sso_id: '',
  is_copy_class: 0
})

onMounted(() => {
  form.organ_id = props.data.organ_id
  form.experiment_name = props.data.name + '(copy)'
  // const [teacher] = props.data.teacher
  // form.sso_id = teacher.sso_id
})

// 机构列表
const { organizations } = useGetProjectList()

// 指导教师列表
const { teachers, updateTeachers } = useGetTeacherList()
watch(
  () => form.organ_id,
  () => {
    updateTeachers(form.organ_id)
  }
)

function handleOrgChange() {
  form.sso_id = ''
}

async function handleSubmit() {
  formRef.value?.validate().then(async () => {
    const params = { ...pickBy(form, item => item !== ''), experiment_id: props.data.id }
    await copyExperiment(params)
    ElMessage.success('复制成功')
    emit('update')
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog title="复制实验" width="600px" @update:modelValue="value => $emit('update:modelValue', value)">
    <el-form ref="formRef" :model="form" label-width="130px">
      <el-form-item label="实验名称" prop="experiment_name">
        <el-input v-model="form.experiment_name" />
      </el-form-item>
      <el-form-item label="实验所属部门/学校" prop="organ_id">
        <el-select v-model="form.organ_id" style="width: 100%" @change="handleOrgChange" clearable>
          <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="sso_id">
        <el-select v-model="form.sso_id" style="width: 100%" clearable>
          <el-option v-for="item in teachers" :key="item.id" :label="item.name" :value="item.sso_id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否复制班级" prop="experiment_name">
        <el-switch
          v-model="form.is_copy_class"
          active-text="是"
          inactive-text="否"
          :active-value="1"
          :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row justify="center">
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)">关闭</el-button>
        <el-button type="primary" round auto-insert-space @click="handleSubmit">复制</el-button>
      </el-row>
    </template></el-dialog
  >
</template>
