<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="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-select 
          v-model="form.roomNo" 
          placeholder="请选择宿舍号" 
          clearable
          filterable
          style="width: 100%">
          <el-option
            v-for="item in roomList"
            :key="item.roomNo"
            :label="item.roomNo"
            :value="item.roomNo">
          </el-option>
        </el-select>
      </el-form-item>
      <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-form-item label="情况记录" prop="note">
        <el-input 
          v-model="form.note" 
          type="textarea" 
          :rows="4"
          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="DormHygieneDailyFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, putObj, getObj } from '/@/api/stuwork/dormhygienedaily'
import { getBuildingList } from '/@/api/stuwork/dormbuilding'
import { getRoomList } from '/@/api/stuwork/dormroom'

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 roomList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  id: '',
  buildingNo: '',
  roomNo: '',
  recordDate: '',
  note: ''
})

// 定义校验规则
const dataRules = {
  buildingNo: [
    { required: true, message: '请选择楼号', trigger: 'change' }
  ],
  roomNo: [
    { required: true, message: '请选择宿舍号', trigger: 'change' }
  ],
  recordDate: [
    { required: true, message: '请选择记录日期', trigger: 'change' }
  ],
  note: [
    { required: true, message: '请输入情况记录', trigger: 'blur' }
  ]
}

// 打开弹窗
const openDialog = (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.buildingNo = ''
    form.roomNo = ''
    form.recordDate = ''
    form.note = ''
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.buildingNo = row.buildingNo || ''
      form.roomNo = row.roomNo || ''
      // 处理日期格式
      if (row.recordDate) {
        form.recordDate = row.recordDate.split(' ')[0] || row.recordDate
      }
      form.note = row.note || ''
    }
  })
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    try {
      const submitData: any = {
        buildingNo: form.buildingNo,
        roomNo: form.roomNo,
        recordDate: form.recordDate + ' 00:00:00',
        note: form.note
      }
      
      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 getRoomListData = async () => {
  try {
    const res = await getRoomList()
    if (res.data) {
      roomList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    roomList.value = []
  }
}

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

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

