<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="schoolYear">
            <el-select 
              v-model="form.schoolYear" 
              placeholder="请选择学年"  
              clearable
              filterable
              style="width: 100%"
              :disabled="!!form.id">
              <el-option
                v-for="item in schoolYearList"
                :key="item.year"
                :label="item.year"
                :value="item.year">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="学期" prop="schoolTerm">
            <el-select 
              v-model="form.schoolTerm" 
              placeholder="请选择学期" 
              clearable
              style="width: 100%"
              :disabled="!!form.id">
              <el-option
                v-for="item in schoolTermList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <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 ? '请选择学生' : '请先选择班级'" 
              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="score">
            <el-input-number
              v-model="form.score"
              :min="0"
              :max="100"
              placeholder="请输入分数"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="类型" prop="conductType">
            <el-select 
              v-model="form.conductType" 
              placeholder="请选择类型" 
              clearable
              style="width: 100%">
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </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="24" class="mb20">
          <el-form-item label="情况记录" prop="description">
            <el-input 
              v-model="form.description" 
              type="textarea" 
              :rows="4" 
              placeholder="请输入情况记录"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="附件" prop="attachment">
            <upload-file
              v-model="form.attachment"
              :limit="5"
              :fileSize="10"
              type="simple" />
          </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="StuConductFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/stuconduct'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { queryAllSchoolYear } from '/@/api/basic/basicyear'
import { queryAllStudentByClassCode } from '/@/api/basic/basicstudent'
import { getDicts } from '/@/api/admin/dict'
import UploadFile from '/@/components/Upload/index.vue'

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 schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])
const typeList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  id: '',
  schoolYear: '',
  schoolTerm: '',
  classCode: '',
  stuNo: '',
  score: 0,
  conductType: '',
  recordDate: '',
  description: '',
  attachment: ''
})

// 定义校验规则
const dataRules = {
  schoolYear: [
    { required: true, message: '请选择学年', trigger: 'change' }
  ],
  schoolTerm: [
    { required: true, message: '请选择学期', trigger: 'change' }
  ],
  classCode: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  stuNo: [
    { required: true, message: '请选择学生', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入分数', trigger: 'blur' }
  ],
  conductType: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  recordDate: [
    { required: true, message: '请选择考核时间', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入情况记录', trigger: 'blur' }
  ]
  // attachment 非必填，不需要验证规则
}

// 班级变化
const handleClassChange = async () => {
  form.stuNo = ''
  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 openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.schoolYear = ''
    form.schoolTerm = ''
    form.classCode = ''
    form.stuNo = ''
    form.score = 0
    form.conductType = ''
    form.recordDate = ''
    form.description = ''
    form.attachment = ''
    studentList.value = []
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.schoolYear = row.schoolYear || ''
      form.schoolTerm = row.schoolTerm || ''
      form.classCode = row.classCode || ''
      form.stuNo = row.stuNo || ''
      form.score = row.score || 0
      form.conductType = row.conductType || ''
      form.recordDate = row.recordDate || ''
      form.description = row.description || ''
      form.attachment = row.attachment || ''
      
      // 加载学生列表
      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 = {
        schoolYear: form.schoolYear,
        schoolTerm: form.schoolTerm,
        classCode: form.classCode,
        stuNo: form.stuNo,
        score: form.score,
        conductType: form.conductType,
        recordDate: form.recordDate,
        description: form.description,
        attachment: form.attachment || ''
      }
      
      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 getSchoolYearList = async () => {
  try {
    const res = await queryAllSchoolYear()
    if (res.data && Array.isArray(res.data)) {
      schoolYearList.value = res.data
    }
  } catch (err) {
  }
}

// 获取学期字典
const getSchoolTermDict = async () => {
  try {
    const res = await getDicts('school_term')
    if (res.data && Array.isArray(res.data)) {
      schoolTermList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      }))
    }
  } catch (err) {
  }
}

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

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

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

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

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

