<template>
  <el-dialog 
    :title="form.id ? '编辑' : '新增'" 
    v-model="visible" 
    :width="800" 
    :close-on-click-modal="false" 
    draggable>
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="120px" 
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="班级" prop="classCode">
            <el-select 
              v-model="form.classCode" 
              placeholder="请选择班级" 
              clearable
              filterable
              style="width: 100%"
              @change="handleClassChange">
              <el-option
                v-for="item in classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="学号" prop="stuNo">
            <el-select 
              v-model="form.stuNo" 
              :placeholder="form.classCode ? (studentLoading ? '加载中...' : '请选择学号') : '请先选择班级'" 
              clearable
              filterable
              style="width: 100%"
              :disabled="!form.classCode || studentLoading"
              :loading="studentLoading"
              @change="handleStudentChange">
              <el-option
                v-for="item in studentList"
                :key="item.stuNo"
                :label="`${item.realName} (${item.stuNo})`"
                :value="item.stuNo">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="需关爱类型" prop="careType">
            <el-select 
              v-model="form.careType" 
              placeholder="请选择需关爱类型" 
              clearable
              style="width: 100%">
              <el-option
                v-for="item in careTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="危机表现" prop="present">
            <el-input 
              v-model="form.present" 
              type="textarea" 
              :rows="4" 
              placeholder="请输入危机表现"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="记录时间" prop="recordDate">
            <el-date-picker
              v-model="form.recordDate"
              type="date"
              placeholder="选择记录时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
    </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="StuCareFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/stucare'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { queryAllStudentByClassCode } from '/@/api/basic/basicstudent'
import { getDicts } from '/@/api/admin/dict'

const emit = defineEmits(['refresh'])

// 定义变量内容
const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const studentLoading = ref(false)
const operType = ref('add')
const classList = ref<any[]>([])
const studentList = ref<any[]>([])
const careTypeList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  id: '',
  classCode: '',
  stuNo: '',
  realName: '',
  careType: '',
  present: '',
  recordDate: ''
})

// 定义校验规则
const dataRules = {
  classCode: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  stuNo: [
    { required: true, message: '请选择学号', trigger: 'change' }
  ],
  careType: [
    { required: true, message: '请选择需关爱类型', trigger: 'change' }
  ],
  present: [
    { required: true, message: '请输入危机表现', trigger: 'blur' }
  ],
  recordDate: [
    { required: true, message: '请选择记录时间', trigger: 'change' }
  ]
}

// 班级变化
const handleClassChange = async () => {
  form.stuNo = ''
  form.realName = ''
  studentList.value = []
  
  if (form.classCode) {
    studentLoading.value = true
    try {
      const res = await queryAllStudentByClassCode(form.classCode)
      if (res.data && Array.isArray(res.data)) {
        studentList.value = res.data
      } else {
        studentList.value = []
      }
    } catch (err) {
      useMessage().error('获取学生列表失败')
      studentList.value = []
    } finally {
      studentLoading.value = false
    }
  }
}

// 学生变化
const handleStudentChange = () => {
  const student = studentList.value.find(item => item.stuNo === form.stuNo)
  if (student) {
    form.realName = student.realName || ''
  } else {
    form.realName = ''
  }
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.classCode = ''
    form.stuNo = ''
    form.realName = ''
    form.careType = ''
    form.present = ''
    form.recordDate = ''
    studentList.value = []
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.classCode = row.classCode || ''
      form.stuNo = row.stuNo || ''
      form.realName = row.realName || ''
      form.careType = row.careType || ''
      form.present = row.present || ''
      form.recordDate = row.recordDate || ''
      
      // 加载学生列表
      if (form.classCode) {
        handleClassChange()
      }
    }
  })
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    try {
      const submitData = {
        classCode: form.classCode,
        stuNo: form.stuNo,
        careType: form.careType,
        present: form.present,
        recordDate: form.recordDate
      }
      
      if (operType.value === 'add') {
        await addObj(submitData)
        useMessage().success('新增成功')
      } else {
        await editObj({
          id: form.id,
          ...submitData
        })
        useMessage().success('编辑成功')
      }
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      useMessage().error(err.msg || (operType.value === 'add' ? '新增失败' : '编辑失败'))
    } finally {
      loading.value = false
    }
  })
}

// 获取班级列表
const getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data && Array.isArray(res.data)) {
      classList.value = res.data
    }
  } catch (err) {
  }
}

// 获取需关爱类型字典
const getCareTypeDict = async () => {
  try {
    const res = await getDicts('stu_care_type')
    if (res.data && Array.isArray(res.data)) {
      careTypeList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    }
  } catch (err) {
  }
}

// 初始化
onMounted(() => {
  getClassListData()
  getCareTypeDict()
})

// 暴露方法
defineExpose({
  openDialog
})
</script>

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

