<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :width="600" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="100px" v-loading="loading">
      <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-form-item label="楼号" prop="buildingNo">
        <el-select 
          v-model="form.buildingNo" 
          placeholder="请选择楼号" 
          clearable
          filterable
          style="width: 100%">
          <el-option
            v-for="item in buildingList"
            :key="item.buildingNo"
            :label="item.buildingNo"
            :value="item.buildingNo">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="房间号" prop="roomNo">
        <el-input v-model="form.roomNo" placeholder="请输入房间号" />
      </el-form-item>
      <el-form-item label="几人间" prop="bedNum">
        <el-select 
          v-model="form.bedNum" 
          placeholder="请选择几人间" 
          clearable
          style="width: 100%">
          <el-option
            v-for="item in bedNumList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="已住人数" prop="livedNum">
        <el-input-number 
          v-model="form.livedNum" 
          :min="0" 
          placeholder="请输入已住人数"
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input 
          v-model="form.remarks" 
          type="textarea" 
          :rows="3"
          placeholder="请输入备注" />
      </el-form-item>
    </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="DormRoomFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, putObj, getObj } from '/@/api/stuwork/dormroom'
import { getDeptList } from '/@/api/basic/basicclass'
import { getBuildingList } from '/@/api/stuwork/dormbuilding'
import { getDicts } from '/@/api/admin/dict'

const emit = defineEmits(['refresh'])

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

// 提交表单数据
const form = reactive({
  id: '',
  deptCode: '',
  buildingNo: '',
  roomNo: '',
  bedNum: '',
  livedNum: 0,
  remarks: ''
})

// 定义校验规则
const dataRules = {
  buildingNo: [
    { required: true, message: '请选择楼号', trigger: 'change' }
  ],
  roomNo: [
    { required: true, message: '请输入房间号', trigger: 'blur' }
  ],
  bedNum: [
    { required: true, message: '请选择几人间', trigger: 'change' }
  ]
}

// 打开弹窗
const openDialog = (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.deptCode = ''
    form.buildingNo = ''
    form.roomNo = ''
    form.bedNum = ''
    form.livedNum = 0
    form.remarks = ''
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.deptCode = row.deptCode || ''
      form.buildingNo = row.buildingNo || ''
      form.roomNo = row.roomNo || ''
      form.bedNum = row.bedNum || ''
      form.livedNum = row.livedNum || 0
      form.remarks = row.remarks || ''
    }
  })
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    try {
      const submitData: any = {
        deptCode: form.deptCode || '',
        buildingNo: form.buildingNo,
        roomNo: form.roomNo,
        bedNum: form.bedNum,
        livedNum: form.livedNum || '',
        remarks: form.remarks || ''
      }
      
      if (operType.value === 'add') {
        await addObj(submitData)
        useMessage().success('新增成功')
      } else {
        submitData.id = form.id
        await putObj(submitData)
        useMessage().success('编辑成功')
      }
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      useMessage().error(err.msg || (operType.value === 'add' ? '新增失败' : '编辑失败'))
    } finally {
      loading.value = false
    }
  })
}

// 获取学院列表
const getDeptListData = async () => {
  try {
    const res = await getDeptList()
    if (res.data) {
      deptList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取学院列表失败', err)
    deptList.value = []
  }
}

// 获取楼号列表
const getBuildingListData = async () => {
  try {
    const res = await getBuildingList()
    if (res.data) {
      buildingList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取楼号列表失败', err)
    buildingList.value = []
  }
}

// 获取几人间字典
const getBedNumDict = async () => {
  try {
    const res = await getDicts('room_stu_num')
    if (res.data) {
      bedNumList.value = Array.isArray(res.data) ? res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value || item.dictValue || item.code
      })) : []
    }
  } catch (err) {
    console.error('获取几人间字典失败', err)
    bedNumList.value = []
  }
}

// 初始化
onMounted(() => {
  getDeptListData()
  getBuildingListData()
  getBedNumDict()
})

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>

