<template>
  <el-dialog
    :title="form.id ? '编辑' : '新增'"
    v-model="visible"
    :width="600"
    :close-on-click-modal="false"
    draggable>
    <el-form
      ref="dataFormRef"
      :model="form"
      :rules="dataRules"
      label-width="100px"
      v-loading="loading">
      <el-form-item label="值班教师" prop="teacherNo">
        <el-select
          v-model="form.teacherNo"
          placeholder="请选择值班教师"
          filterable
          clearable
          style="width: 100%"
          :disabled="!!form.id"
          @change="handleTeacherChange">
          <el-option
            v-for="item in teacherList"
            :key="item.userName"
            :label="(item.realName || '') + (item.userName ? ` (${item.userName})` : '')"
            :value="item.userName" />
        </el-select>
      </el-form-item>
      <el-form-item label="预约时间" prop="reservationTime">
        <el-date-picker
          v-model="form.reservationTime"
          type="datetime"
          placeholder="选择预约时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
          :disabled="!!form.id" />
      </el-form-item>
      <el-form-item label="班号" prop="classCode">
        <el-select
          v-model="form.classCode"
          placeholder="请选择班号"
          clearable
          filterable
          style="width: 100%"
          :disabled="!!form.id"
          @change="handleClassChange">
          <el-option
            v-for="item in classList"
            :key="item.classCode"
            :label="item.classNo"
            :value="item.classCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="学号" prop="stuNo">
        <el-select
          v-model="form.stuNo"
          :placeholder="form.classCode ? (studentLoading ? '加载中...' : '请选择学生') : '请先选择班号'"
          clearable
          filterable
          style="width: 100%"
          :disabled="!form.classCode || !!form.id || studentLoading"
          :loading="studentLoading"
          @change="handleStudentChange">
          <el-option
            v-for="item in studentList"
            :key="item.stuNo"
            :label="`${item.realName || item.stuName || ''} (${item.stuNo})`"
            :value="item.stuNo" />
        </el-select>
      </el-form-item>
      <el-form-item label="学生姓名" prop="stuName">
        <el-input v-model="form.stuName" placeholder="选学生后自动带出" disabled />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="form.phone" placeholder="选学生后自动带出" disabled />
      </el-form-item>
      <el-form-item label="学生留言" prop="remarks">
        <el-input
          v-model="form.remarks"
          type="textarea"
          :rows="3"
          placeholder="请输入学生留言"
          maxlength="250"
          show-word-limit
          :disabled="!!form.id" />
      </el-form-item>
      <template v-if="form.id">
        <el-form-item label="是否处理" prop="isHandle">
          <el-select
            v-model="form.isHandle"
            placeholder="请选择"
            clearable
            style="width: 100%">
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="老师备注" prop="teaRemark">
          <el-input
            v-model="form.teaRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入老师备注"
            maxlength="250"
            show-word-limit />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="PsychologicalCounselingReservationFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/psychologicalcounselingreservation'
import { getList } from '/@/api/stuwork/psychologicalcounselingteacher'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { queryAllStudentByClassCode } from '/@/api/basic/basicstudent'

const emit = defineEmits(['refresh'])

const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const studentLoading = ref(false)
const operType = ref('add')
const teacherList = ref<any[]>([])
const classList = ref<any[]>([])
const studentList = ref<any[]>([])

const form = reactive({
  id: '',
  teacherNo: '',
  realName: '',
  reservationTime: '',
  classCode: '',
  classNo: '',
  stuNo: '',
  stuName: '',
  phone: '',
  remarks: '',
  isHandle: '0',
  teaRemark: ''
})

const dataRules = {
  teacherNo: [{ required: true, message: '请选择值班教师', trigger: 'change' }],
  reservationTime: [{ required: true, message: '请选择预约时间', trigger: 'change' }],
  classCode: [{ required: true, message: '请选择班号', trigger: 'change' }],
  stuNo: [{ required: true, message: '请选择学生', trigger: 'change' }]
}

const handleTeacherChange = (val: string) => {
  const item = teacherList.value.find((t: any) => t.userName === val)
  form.realName = item ? (item.realName || '') : ''
}

const handleClassChange = async () => {
  form.stuNo = ''
  form.stuName = ''
  form.phone = ''
  studentList.value = []
  if (!form.classCode) return
  studentLoading.value = true
  try {
    const res = await queryAllStudentByClassCode(form.classCode)
    studentList.value = Array.isArray(res.data) ? res.data : []
  } catch (err) {
    studentList.value = []
  } finally {
    studentLoading.value = false
  }
}

const handleStudentChange = (val: string) => {
  const item = studentList.value.find((s: any) => s.stuNo === val)
  if (item) {
    form.stuName = item.realName || item.stuName || ''
    form.phone = item.phone || item.mobile || ''
  } else {
    form.stuName = ''
    form.phone = ''
  }
}

const openDialog = (type: string = 'add', row?: any) => {
  operType.value = type
  visible.value = true

  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.teacherNo = ''
    form.realName = ''
    form.reservationTime = ''
    form.classCode = ''
    form.classNo = ''
    form.stuNo = ''
    form.stuName = ''
    form.phone = ''
    form.remarks = ''
    form.isHandle = '0'
    form.teaRemark = ''
    studentList.value = []

    if (type === 'edit' && row) {
      form.id = row.id
      form.teacherNo = row.teacherNo || ''
      form.realName = row.realName || ''
      form.reservationTime = row.reservationTime || ''
      form.classNo = row.classNo || ''
      const cls = classList.value.find((c: any) => c.classNo === row.classNo)
      form.classCode = cls ? cls.classCode : (row.classCode || '')
      form.stuNo = row.stuNo || ''
      form.stuName = row.stuName || ''
      form.phone = row.phone || ''
      form.remarks = row.remarks || ''
      form.isHandle = row.isHandle !== undefined && row.isHandle !== null ? String(row.isHandle) : '0'
      form.teaRemark = row.teaRemark || ''
    }
  })
}

const onSubmit = async () => {
  if (!dataFormRef.value) return
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    const selectedClass = classList.value.find((c: any) => c.classCode === form.classCode)
    const classNo = selectedClass ? selectedClass.classNo : form.classNo || form.classCode

    loading.value = true
    try {
      if (operType.value === 'add') {
        await addObj({
          teacherNo: form.teacherNo,
          realName: form.realName,
          reservationTime: form.reservationTime ? (form.reservationTime.length === 10 ? form.reservationTime + ' 00:00:00' : form.reservationTime) : '',
          classNo,
          stuNo: form.stuNo,
          stuName: form.stuName,
          phone: form.phone,
          remarks: form.remarks
        })
        useMessage().success('新增成功')
      } else {
        await editObj({
          id: form.id,
          teacherNo: form.teacherNo,
          realName: form.realName,
          reservationTime: form.reservationTime,
          classNo: form.classNo || classNo,
          stuNo: form.stuNo,
          stuName: form.stuName,
          phone: form.phone,
          remarks: form.remarks,
          isHandle: form.isHandle,
          teaRemark: form.teaRemark || ''
        })
        useMessage().success('编辑成功')
      }
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      useMessage().error(err.msg || (operType.value === 'add' ? '新增失败' : '编辑失败'))
    } finally {
      loading.value = false
    }
  })
}

const loadTeacherList = async () => {
  try {
    const res = await getList()
    teacherList.value = Array.isArray(res.data) ? res.data : []
  } catch (err) {
    teacherList.value = []
  }
}

const loadClassList = async () => {
  try {
    const res = await getClassListByRole()
    classList.value = Array.isArray(res.data) ? res.data : []
  } catch (err) {
    classList.value = []
  }
}

onMounted(() => {
  loadTeacherList()
  loadClassList()
})

defineExpose({
  openDialog
})
</script>

<style scoped lang="scss">
</style>
