<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="24" class="mb20">
          <el-form-item label="社团名称" prop="associationName">
            <el-input 
              v-model="form.associationName" 
              placeholder="请输入社团名称" 
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="学院" prop="deptCode">
            <el-select 
              v-model="form.deptCode" 
              placeholder="请选择学院" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in deptList"
                :key="item.deptCode"
                :label="item.deptName"
                :value="item.deptCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="指导老师" prop="teacherNo">
            <el-select 
              v-model="form.teacherNo" 
              placeholder="请选择指导老师" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in teacherList"
                :key="item.teacherNo"
                :label="item.realName"
                :value="item.teacherNo">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="负责人" prop="maintainer">
            <el-input 
              v-model="form.maintainer" 
              placeholder="请输入负责人姓名" 
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="成立时间" prop="openTime">
            <el-date-picker
              v-model="form.openTime"
              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="tel">
            <el-input 
              v-model="form.tel" 
              placeholder="请输入联系电话" 
              clearable
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="所属类别" prop="type">
            <el-select 
              v-model="form.type" 
              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="24" class="mb20">
          <el-form-item label="成立申请" prop="applyNote">
            <el-input 
              v-model="form.applyNote" 
              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="ruleNote">
            <el-input 
              v-model="form.ruleNote" 
              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="StuAssociationFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/stuassociation'
import { getDeptList } from '/@/api/basic/basicclass'
import { getDicts } from '/@/api/admin/dict'
import request from '/@/utils/request'

const emit = defineEmits(['refresh'])

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

// 提交表单数据
const form = reactive({
  id: '',
  associationName: '',
  deptCode: '',
  teacherNo: '',
  maintainer: '',
  openTime: '',
  tel: '',
  type: '',
  applyNote: '',
  ruleNote: ''
})

// 定义校验规则
const dataRules = {
  associationName: [
    { required: true, message: '请输入社团名称', trigger: 'blur' }
  ],
  deptCode: [
    { required: true, message: '请选择学院', trigger: 'change' }
  ],
  teacherNo: [
    { required: true, message: '请选择指导老师', trigger: 'change' }
  ],
  maintainer: [
    { required: true, message: '请输入负责人姓名', trigger: 'blur' }
  ],
  openTime: [
    { required: true, message: '请选择成立时间', trigger: 'change' }
  ],
  tel: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择所属类别', trigger: 'change' }
  ],
  applyNote: [
    { required: true, message: '请输入成立申请', trigger: 'blur' }
  ],
  ruleNote: [
    { required: true, message: '请输入社团章程', trigger: 'blur' }
  ]
}

// 获取学院列表
const getDeptListData = async () => {
  try {
    const res = await getDeptList()
    if (res.data && Array.isArray(res.data)) {
      deptList.value = res.data
    } else {
      deptList.value = []
    }
  } catch (err) {
    deptList.value = []
  }
}

// 获取教师列表
const getTeacherList = async () => {
  try {
    const res = await request({
      url: '/professional/teacherbase/TeacherBaseList',
      method: 'get'
    })
    if (res.data && Array.isArray(res.data)) {
      teacherList.value = res.data
    } else {
      teacherList.value = []
    }
  } catch (err) {
    teacherList.value = []
  }
}

// 获取类别字典
const getTypeDict = async () => {
  try {
    const res = await getDicts('association_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
      }))
    } else {
      typeList.value = []
    }
  } catch (err) {
    typeList.value = []
  }
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  operType.value = type
  visible.value = true
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.associationName = ''
    form.deptCode = ''
    form.teacherNo = ''
    form.maintainer = ''
    form.openTime = ''
    form.tel = ''
    form.type = ''
    form.applyNote = ''
    form.ruleNote = ''
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.associationName = row.associationName || ''
      form.deptCode = row.deptCode || ''
      form.teacherNo = row.teacherNo || ''
      form.maintainer = row.maintainer || ''
      form.openTime = row.openTime || ''
      form.tel = row.tel || ''
      form.type = row.type || ''
      form.applyNote = row.applyNote || ''
      form.ruleNote = row.ruleNote || ''
      
      // 如果需要获取详情
      if (row.id && (!row.associationName || !row.deptCode)) {
        loading.value = true
        getDetail(row.id).then((res: any) => {
          if (res.data) {
            form.associationName = res.data.associationName || ''
            form.deptCode = res.data.deptCode || ''
            form.teacherNo = res.data.teacherNo || ''
            form.maintainer = res.data.maintainer || ''
            form.openTime = res.data.openTime || ''
            form.tel = res.data.tel || ''
            form.type = res.data.type || ''
            form.applyNote = res.data.applyNote || ''
            form.ruleNote = res.data.ruleNote || ''
          }
        }).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 {
        // 根据 deptCode 获取 deptName
        const selectedDept = deptList.value.find(item => item.deptCode === form.deptCode)
        const deptName = selectedDept ? selectedDept.deptName : ''
        
        // 根据 teacherNo 获取 teacherRealName
        const selectedTeacher = teacherList.value.find(item => item.teacherNo === form.teacherNo)
        const teacherRealName = selectedTeacher ? selectedTeacher.realName : ''
        
        // 格式化 openTime，确保格式为 YYYY-MM-DD HH:mm:ss
        let formattedOpenTime = form.openTime
        if (formattedOpenTime && !formattedOpenTime.includes(' ')) {
          formattedOpenTime = formattedOpenTime + ' 00:00:00'
        }
        
        const submitData = {
          associationName: form.associationName,
          deptCode: form.deptCode,
          deptName: deptName,
          teacherNo: form.teacherNo,
          teacherRealName: teacherRealName,
          maintainer: form.maintainer,
          openTime: formattedOpenTime,
          tel: form.tel,
          type: form.type,
          applyNote: form.applyNote,
          ruleNote: form.ruleNote,
          num: '' // 根据接口文档示例，num 字段为空字符串
        }
        
        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(() => {
  getDeptListData()
  getTeacherList()
  getTypeDict()
})

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

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

