<template>
  <el-dialog 
    title="新增" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="800px">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="100px" 
      :validate-on-rule-change="false"
      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%">
              <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="请选择学生" 
              clearable
              filterable
              style="width: 100%"
              :disabled="!form.classCode"
              @change="handleStudentChange">
              <el-option
                v-for="item in studentList"
                :key="item.stuNo"
                :label="item.realName"
                :value="item.stuNo">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="记录时间" prop="recordTime">
            <el-date-picker
              v-model="form.recordTime"
              type="date"
              placeholder="选择记录时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="分数" prop="score">
            <el-input-number
              v-model="form.score"
              :precision="0"
              :step="1"
              placeholder="请输入分数（可为负数）"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="24" class="mb20">
          <el-form-item label="检查记录" prop="note">
            <el-input
              v-model="form.note"
              type="textarea"
              :rows="4"
              placeholder="请输入检查记录"
              maxlength="500"
              show-word-limit />
          </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="ClassCheckDailyDialog">
import { ref, reactive, nextTick, onMounted, watch } from 'vue'
import { useMessage } from "/@/hooks/message";
import { getObj, addObj } from '/@/api/stuwork/classcheckdaily'
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 classList = ref<any[]>([])
const studentList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  id: '',
  classCode: '',
  stuNo: '',
  realName: '',
  recordTime: '',
  score: 0,
  note: ''
});

// 定义校验规则
const dataRules = ref({
  classCode: [
    { required: true, message: '班号不能为空', trigger: 'change' }
  ],
  stuNo: [
    { required: true, message: '学生不能为空', trigger: 'change' }
  ],
  recordTime: [
    { required: true, message: '记录时间不能为空', trigger: 'blur' }
  ],
  score: [
    { required: true, message: '分数不能为空', trigger: 'blur' }
  ],
  note: [
    { required: true, message: '检查记录不能为空', trigger: 'blur' }
  ]
})

// 监听班级变化，加载学生列表
watch(() => form.classCode, (newVal) => {
  if (newVal) {
    getStudentList(newVal)
  } else {
    studentList.value = []
    form.stuNo = ''
    form.realName = ''
  }
})

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

// 打开弹窗
const openDialog = (id?: string) => {
  visible.value = true
  
  // 重置表单数据
  Object.assign(form, {
    id: '',
    classCode: '',
    stuNo: '',
    realName: '',
    recordTime: '',
    score: 0,
    note: ''
  })
  
  // 清空学生列表
  studentList.value = []

  // 清除表单验证状态，不触发验证
  nextTick(() => {
    dataFormRef.value?.clearValidate();
    dataFormRef.value?.resetFields();
  });

  // 获取详情
  if (id) {
    form.id = id
    getClassCheckDailyData(id)
  }  
  // 新增时，确保验证状态已清除
  nextTick(() => {
    dataFormRef.value?.clearValidate();
  });
   
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;

  try {
    loading.value = true;
    // 日常巡检只有新增，没有编辑功能
    await addObj(form);
    useMessage().success('添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg || '操作失败');
  } finally {
    loading.value = false;
  }
};

// 初始化表单数据（如果需要查看详情）
const getClassCheckDailyData = (id: string) => {
  loading.value = true
  getObj({ id: id }).then((res: any) => {
    if (res.data) {
      // 处理返回数据，可能是对象或数组
      const data = Array.isArray(res.data) ? res.data[0] : res.data
      if (data) {
        Object.assign(form, {
          id: data.id || '',
          classCode: data.classCode || '',
          stuNo: data.stuNo || '',
          realName: data.realName || '',
          recordTime: data.recordTime || '',
          score: data.score || 0,
          note: data.note || ''
        })
        
        // 如果有班级代码，加载学生列表
        if (data.classCode) {
          getStudentList(data.classCode)
        }
      }
    }
  }).catch((err: any) => {
    useMessage().error('获取详情失败')
  }).finally(() => {
    loading.value = false
    // 数据加载完成后，清除验证状态，避免触发验证
    nextTick(() => {
      dataFormRef.value?.clearValidate();
    });
  })
}

// 获取学生列表
const getStudentList = async (classCode: string) => {
  try {
    const res = await queryAllStudentByClassCode(classCode)
    if (res.data) {
      studentList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    studentList.value = []
  }
}

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

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

// 暴露变量
defineExpose({
  openDialog
});
</script>
