<template>
  <el-dialog 
    :title="form.id ? '编辑' : '新增'" 
    v-model="visible" 
    :width="900" 
    :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="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="themeName">
            <el-input 
              v-model="form.themeName" 
              placeholder="请输入活动主题" 
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="主持人" prop="author">
            <el-input 
              v-model="form.author" 
              placeholder="请输入主持人" 
              clearable
              style="width: 100%" />
          </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="address">
            <el-input 
              v-model="form.address" 
              placeholder="请输入活动地点" 
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="参加人数" prop="attendNum">
            <el-input-number
              v-model="form.attendNum"
              :min="0"
              placeholder="请输入参加人数"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="活动内容" prop="content">
            <Editor
              v-model:getHtml="form.content"
              :height="300"
              placeholder="请输入活动内容" />
          </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-col :span="24" class="mb20">
          <el-form-item label="活动图片2" prop="attachment2">
            <upload-file
              v-model="form.attachment2"
              :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="ClassActivityFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/classactivity'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { queryAllSchoolYear } from '/@/api/basic/basicyear'
import { getDicts } from '/@/api/admin/dict'
import { CURRENT_SCHOOL_YEAR, CURRENT_SCHOOL_TERM } from '/@/config/global'
import Editor from '/@/components/Editor/index.vue'
import UploadFile from '/@/components/Upload/index.vue'

const emit = defineEmits(['refresh'])

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

// 提交表单数据
const form = reactive({
  id: '',
  classCode: '',
  themeName: '',
  author: '',
  recordDate: '',
  address: '',
  attendNum: 0,
  content: '',
  attachment: '',
  attachment2: ''
})

// 定义校验规则
const dataRules = {
  classCode: [
    { required: true, message: '请选择班号', trigger: 'change' }
  ],
  themeName: [
    { required: true, message: '请输入活动主题', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入主持人', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  attendNum: [
    { required: true, message: '请输入参加人数', trigger: 'blur' }
  ]
  // activityTime 和 content 非必填，不需要验证规则
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
      form.classCode = ''
      form.themeName = ''
      form.author = ''
      form.recordDate = ''
      form.address = ''
      form.attendNum = 0
      form.content = ''
      form.attachment = ''
      form.attachment2 = ''
      
      // 编辑时填充数据
      if (type === 'edit' && row) {
        form.id = row.id
        form.classCode = row.classCode || ''
        form.themeName = row.themeName || ''
        form.author = row.author || ''
        form.recordDate = row.activityTime || row.recordDate || ''
        form.address = row.address || ''
        form.attendNum = row.attendNum || 0
        form.content = row.content || ''
        form.attachment = row.attachment || ''
        form.attachment2 = row.attachment2 || ''
      
      // 如果需要获取详情
      if (row.id && !row.content) {
        loading.value = true
        getDetail(row.id).then((res: any) => {
          if (res.data) {
            form.content = res.data.content || ''
            form.attachment = res.data.attachment || ''
            form.attachment2 = res.data.attachment2 || ''
          }
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    try {
      const submitData = {
        classCode: form.classCode,
        schoolYear: currentSchoolYear.value || CURRENT_SCHOOL_YEAR, // 使用当前学年
        schoolTerm: currentSchoolTerm.value || CURRENT_SCHOOL_TERM, // 使用当前学期
        themeName: form.themeName,
        author: form.author,
        recordDate: form.recordDate || '',
        address: form.address,
        attendNum: String(form.attendNum || 0), // API文档示例中是字符串类型
        content: form.content || '',
        attachment: form.attachment || '',
        attachment2: form.attachment2 || ''
      }
      
      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 getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data && Array.isArray(res.data)) {
      classList.value = res.data
    }
  } catch (err) {
  }
}

// 获取学年列表并设置当前学年
const getSchoolYearList = async () => {
  try {
    const res = await queryAllSchoolYear()
    if (res.data && Array.isArray(res.data)) {
      schoolYearList.value = res.data
      // 设置当前学年（如果列表中有的话）
      const currentYear = schoolYearList.value.find((item: any) => item.year === CURRENT_SCHOOL_YEAR)
      currentSchoolYear.value = currentYear ? currentYear.year : (schoolYearList.value.length > 0 ? schoolYearList.value[0].year : CURRENT_SCHOOL_YEAR)
    } else {
      currentSchoolYear.value = CURRENT_SCHOOL_YEAR
    }
  } catch (err) {
    currentSchoolYear.value = CURRENT_SCHOOL_YEAR
  }
}

// 获取学期字典并设置当前学期
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
      }))
      // 设置当前学期
      const currentTerm = schoolTermList.value.find((item: any) => item.value === CURRENT_SCHOOL_TERM)
      currentSchoolTerm.value = currentTerm ? currentTerm.value : (schoolTermList.value.length > 0 ? schoolTermList.value[0].value : CURRENT_SCHOOL_TERM)
    } else {
      currentSchoolTerm.value = CURRENT_SCHOOL_TERM
    }
  } catch (err) {
    currentSchoolTerm.value = CURRENT_SCHOOL_TERM
  }
}

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

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

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

