<template>
  <el-dialog 
    title="编辑学生会" 
    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="unionName">
            <el-input 
              v-model="form.unionName" 
              placeholder="学生会名称" 
              disabled
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="类型" prop="unionType">
            <el-select 
              v-model="form.unionType" 
              placeholder="类型" 
              disabled
              style="width: 100%">
              <el-option
                v-for="item in unionTypeList"
                :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="address">
            <el-input 
              v-model="form.address" 
              placeholder="请输入联系地址" 
              clearable
              style="width: 100%" />
          </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="sort">
            <el-input-number
              v-model="form.sort"
              :min="0"
              placeholder="请输入排序"
              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="StuUnionFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { editObj, getDetail } from '/@/api/stuwork/stuunion'
import { getDicts } from '/@/api/admin/dict'

const emit = defineEmits(['refresh'])

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

// 提交表单数据
const form = reactive({
  id: '',
  unionName: '',
  unionType: '',
  address: '',
  maintainer: '',
  sort: undefined as number | undefined
})

// 定义校验规则
const dataRules = {
  address: [
    { required: true, message: '请输入联系地址', trigger: 'blur' }
  ],
  maintainer: [
    { required: true, message: '请输入负责人', trigger: 'blur' }
  ]
}

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

// 打开弹窗
const openDialog = async (type: string = 'edit', row?: any) => {
  visible.value = true
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.unionName = ''
    form.unionType = ''
    form.address = ''
    form.maintainer = ''
    form.sort = undefined
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.unionName = row.unionName || ''
      form.unionType = row.unionType || ''
      form.address = row.address || ''
      form.maintainer = row.maintainer || ''
      form.sort = row.sort !== undefined && row.sort !== null ? row.sort : undefined
      
      // 如果需要获取详情
      if (row.id && (!row.address || !row.maintainer)) {
        loading.value = true
        getDetail(row.id).then((res: any) => {
          if (res.data) {
            form.unionName = res.data.unionName || ''
            form.unionType = res.data.unionType || ''
            form.address = res.data.address || ''
            form.maintainer = res.data.maintainer || ''
            form.sort = res.data.sort !== undefined && res.data.sort !== null ? res.data.sort : undefined
          }
        }).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 = {
          id: form.id,
          address: form.address,
          maintainer: form.maintainer,
          sort: form.sort !== undefined && form.sort !== null ? form.sort : undefined
        }
        
        await editObj(submitData)
        useMessage().success('编辑成功')
        
        visible.value = false
        emit('refresh')
      } catch (err: any) {
        useMessage().error(err.msg || '编辑失败')
      } finally {
        loading.value = false
      }
    }
  })
}

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

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

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

