<template>
  <el-dialog 
    :title="form.id ? '编辑' : '新增'" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="800px">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="100px" 
      :validate-on-rule-change="false"
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="楼号" prop="buildNo">
            <el-select 
              v-model="form.buildNo" 
              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-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="宿舍号" prop="roomNo">
            <el-input v-model="form.roomNo" placeholder="请输入宿舍号" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <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-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="已住人数" prop="liveNum">
            <el-input-number 
              v-model="form.liveNum" 
              :min="0"
              placeholder="请输入已住人数"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="班号" prop="classNo">
            <el-input v-model="form.classNo" placeholder="请输入班号" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="班主任工号" prop="teacherNo">
            <el-input v-model="form.teacherNo" placeholder="请输入班主任工号" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="班主任姓名" prop="teacherRealName">
            <el-input v-model="form.teacherRealName" placeholder="请输入班主任姓名" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="校园补贴" prop="oddbMoney">
            <el-input-number 
              v-model="form.oddbMoney" 
              :precision="2"
              :min="0"
              placeholder="请输入校园补贴"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="消费金额" prop="costMoney">
            <el-input-number 
              v-model="form.costMoney" 
              :precision="2"
              :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="WaterDetailFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, putObj } from '/@/api/stuwork/waterdetail'
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 buildingList = ref<any[]>([])
const bedNumList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  id: '',
  buildNo: '',
  roomNo: '',
  bedNum: '',
  liveNum: 0,
  classNo: '',
  teacherNo: '',
  teacherRealName: '',
  oddbMoney: 0,
  costMoney: 0
})

// 定义校验规则
const dataRules = {
  buildNo: [
    { required: true, message: '请选择楼号', trigger: 'change' }
  ],
  roomNo: [
    { required: true, message: '请输入宿舍号', trigger: 'blur' }
  ],
  bedNum: [
    { required: true, message: '请选择床位数', trigger: 'change' }
  ],
  liveNum: [
    { required: true, message: '请输入已住人数', trigger: 'blur' },
    { type: 'number', min: 0, message: '已住人数必须大于等于0', trigger: 'blur' }
  ]
}

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

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    try {
      const submitData: any = {
        buildNo: form.buildNo,
        roomNo: form.roomNo,
        bedNum: form.bedNum,
        liveNum: form.liveNum,
        classNo: form.classNo,
        teacherNo: form.teacherNo,
        teacherRealName: form.teacherRealName,
        oddbMoney: form.oddbMoney,
        costMoney: form.costMoney
      }
      
      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 getBuildingListData = async () => {
  try {
    const res = await getBuildingList()
    if (res.data) {
      buildingList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (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) {
    bedNumList.value = []
  }
}

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

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

