<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="userName">
        <el-select
          v-model="form.userName"
          placeholder="请选择教师"
          filterable
          clearable
          style="width: 100%"
          :disabled="!!form.id"
          @change="handleTeacherChange">
          <el-option
            v-for="item in teacherList"
            :key="item.teacherNo || item.userName"
            :label="(item.realName || item.name) + (item.teacherNo ? ` (${item.teacherNo})` : '')"
            :value="item.teacherNo || item.userName">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input
          v-model="form.realName"
          placeholder="选教师后自动带出，可修改"
          clearable />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input
          v-model="form.phone"
          placeholder="请输入联系方式"
          clearable />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input
          v-model="form.remarks"
          type="textarea"
          :rows="4"
          placeholder="请输入备注"
          maxlength="250"
          show-word-limit />
      </el-form-item>
    </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="PsychologicalCounselingTeacherFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/psychologicalcounselingteacher'
import { getTeacherBaseList } from '/@/api/professional/professionaluser/teacherbase'

const emit = defineEmits(['refresh'])

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

const form = reactive({
  id: '',
  userName: '',
  realName: '',
  phone: '',
  remarks: ''
})

const dataRules = {
  userName: [
    { required: true, message: '请选择教师', trigger: 'change' }
  ]
}

const handleTeacherChange = (val: string) => {
  const item = teacherList.value.find(
    (t: any) => (t.teacherNo || t.userName) === val
  )
  if (item) {
    form.realName = item.realName || item.name || ''
    form.phone = item.phone || item.tel || ''
  } else {
    form.realName = ''
    form.phone = ''
  }
}

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

  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.userName = ''
    form.realName = ''
    form.phone = ''
    form.remarks = ''

    if (type === 'edit' && row) {
      form.id = row.id
      form.userName = row.userName || ''
      form.realName = row.realName || ''
      form.phone = row.phone || ''
      form.remarks = row.remarks || ''
    }
  })
}

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

    loading.value = true
    try {
      if (operType.value === 'add') {
        await addObj({
          userName: form.userName,
          realName: form.realName,
          phone: form.phone,
          remarks: form.remarks
        })
        useMessage().success('新增成功')
      } else {
        await editObj({
          id: form.id,
          userName: form.userName,
          realName: form.realName,
          phone: form.phone,
          remarks: form.remarks
        })
        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 getTeacherBaseList()
    if (res.data && Array.isArray(res.data)) {
      teacherList.value = res.data
    } else {
      teacherList.value = []
    }
  } catch (err) {
    teacherList.value = []
  }
}

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

defineExpose({
  openDialog
})
</script>

<style scoped lang="scss">
.mb20 {
  margin-bottom: 0;
}
</style>
