<template>
  <el-dialog 
    :title="form.id ? '编辑' : '新增'" 
    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="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-col :span="12" class="mb20">
          <el-form-item label="分数" prop="score">
            <el-input-number
              v-model="form.score"
              :precision="0"
              :step="1"
              :min="0"
              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="ClassHygieneDailyDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/stuwork/classhygienedaily'
import { getClassListByRole } from '/@/api/basic/basicclass'

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
const classList = ref<any[]>([])

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

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

// 打开弹窗
const openDialog = (id?: string) => {
  visible.value = true
  
  // 重置表单数据
  Object.assign(form, {
    id: '',
    classCode: '',
    recordDate: '',
    score: 0,
    note: ''
  })

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

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

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

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg || '操作失败');
  } finally {
    loading.value = false;
  }
};

// 初始化表单数据
const getClassHygieneDailyData = (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 || '',
          recordDate: data.recordDate || '',
          score: data.score || 0,
          note: data.note || ''
        })
      }
    }
  }).catch((err: any) => {
    useMessage().error('获取详情失败')
  }).finally(() => {
    loading.value = false
    // 数据加载完成后，清除验证状态，避免触发验证
    nextTick(() => {
      dataFormRef.value?.clearValidate();
    });
  })
}

// 获取班号列表
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>
