<template>
  <el-dialog 
    :title="form.id ? '编辑获奖活动信息' : '新增获奖活动信息'" 
    v-model="visible" 
    :width="700" 
    :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="24" class="mb20">
          <el-form-item label="活动主题" prop="activityInfoId">
            <el-select 
              v-model="form.activityInfoId" 
              placeholder="请选择活动主题" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in activityInfoList"
                :key="item.id"
                :label="item.activityTheme"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="学号" prop="userName">
            <el-input 
              v-model="form.userName" 
              placeholder="请输入学号" 
              clearable
              @blur="handleStuNoBlur"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="姓名" prop="realName">
            <el-input 
              v-model="form.realName" 
              placeholder="请输入姓名" 
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="获奖信息" prop="awards">
            <el-input 
              v-model="form.awards" 
              type="textarea"
              :rows="4"
              placeholder="请输入获奖信息" 
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="获奖时间" prop="awardTime">
            <el-date-picker
              v-model="form.awardTime"
              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="remarks">
            <el-input 
              v-model="form.remarks" 
              type="textarea"
              :rows="4"
              placeholder="请输入备注" 
              clearable
              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="ActivityAwardsFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail, getActivityInfoList } from '/@/api/stuwork/activityawards'
import { queryAllStudentByStuNo } from '/@/api/basic/basicstudent'

const emit = defineEmits(['refresh'])

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

// 提交表单数据
const form = reactive({
  id: '',
  activityInfoId: '',
  userName: '',
  realName: '',
  awards: '',
  awardTime: '',
  remarks: ''
})

// 定义校验规则
const dataRules = {
  activityInfoId: [
    { required: true, message: '请选择活动主题', trigger: 'change' }
  ],
  userName: [
    { required: true, message: '请输入学号', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  awards: [
    { required: true, message: '请输入获奖信息', trigger: 'blur' }
  ],
  awardTime: [
    { required: true, message: '请选择获奖时间', trigger: 'change' }
  ]
}

// 学号失焦时自动填充姓名
const handleStuNoBlur = async () => {
  if (!form.userName) return
  
  try {
    const res = await queryAllStudentByStuNo({ stuNo: form.userName })
    if (res.data && res.data.length > 0) {
      const student = res.data[0]
      form.realName = student.realName || ''
    }
  } catch (err) {
    // 不显示错误，允许手动输入姓名
  }
}

// 获取活动主题列表
const getActivityInfoListData = async () => {
  try {
    const res = await getActivityInfoList()
    if (res.data && Array.isArray(res.data)) {
      activityInfoList.value = res.data
    } else {
      activityInfoList.value = []
    }
  } catch (err) {
    activityInfoList.value = []
  }
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  operType.value = type
  visible.value = true
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.activityInfoId = ''
    form.userName = ''
    form.realName = ''
    form.awards = ''
    form.awardTime = ''
    form.remarks = ''
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.activityInfoId = row.activityInfoId || ''
      form.userName = row.userName || ''
      form.realName = row.realName || ''
      form.awards = row.awards || ''
      form.awardTime = row.awardTime || row.month || ''
      form.remarks = row.remarks || ''
      
      // 如果需要获取详情
      if (row.id && (!row.userName || !row.awards)) {
        loading.value = true
        getDetail(row.id).then((res: any) => {
          if (res.data) {
            form.activityInfoId = res.data.activityInfoId || ''
            form.userName = res.data.userName || ''
            form.realName = res.data.realName || ''
            form.awards = res.data.awards || ''
            form.awardTime = res.data.awardTime || res.data.month || ''
            form.remarks = res.data.remarks || ''
          }
        }).catch((err) => {
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

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

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

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

<style scoped lang="scss">
</style>

