<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 (form.id && form.id !== '' && form.deptCode) ? filteredClassList : 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="ClassRoomHygieneDailyDialog">
import { ref, reactive, nextTick, computed, onMounted } from 'vue'
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/stuwork/classroomhygienedaily'
import { getDeptList } from '/@/api/basic/basicclass'
import { getClassListByRole, queryClassByDeptCode } from '/@/api/basic/basicclass'

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

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

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

// 根据学院筛选班级列表
const filteredClassList = computed(() => {
  if (!form.deptCode) {
    return []
  }
  return classList.value.filter((item: any) => item.deptCode === form.deptCode)
})

// 定义校验规则
const dataRules = computed(() => ({
  deptCode: form.id ? [
    { required: true, message: '学院不能为空', trigger: 'change' }
  ] : [],
  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 handleDeptChange = () => {
  // 清空班号选择
  form.classCode = ''
}

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

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

  // 获取详情
  if (id) {
    form.id = id
    getClassRoomHygieneDailyData(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 getClassRoomHygieneDailyData = (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 || '',
          deptCode: data.deptCode || '',
          classCode: data.classCode || '',
          recordDate: data.recordDate || '',
          score: data.score || 0,
          note: data.note || ''
        })
        
        // 如果编辑时 deptCode 为空，但 classCode 有值，尝试从 classList 中找到对应的 deptCode
        if (!form.deptCode && form.classCode && classList.value.length > 0) {
          const classItem = classList.value.find((item: any) => item.classCode === form.classCode)
          if (classItem && classItem.deptCode) {
            form.deptCode = classItem.deptCode
          }
        }
        
        // 数据加载完成后，清除验证状态，避免触发验证
        nextTick(() => {
          dataFormRef.value?.clearValidate();
        });
      }
    }
  }).catch((err: any) => {
    console.error('获取详情失败', err)
    useMessage().error('获取详情失败')
  }).finally(() => {
    loading.value = false
  })
}

// 获取学院列表
const getDeptListData = async () => {
  try {
    const res = await getDeptList()
    if (res.data) {
      deptList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取学院列表失败', err)
    deptList.value = []
  }
}

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

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

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