<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="120px" v-loading="loading">
      <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="year">
        <el-select 
          v-model="form.year" 
          placeholder="请选择学年" 
          clearable
          filterable
          style="width: 100%">
          <el-option
            v-for="item in schoolYearList"
            :key="item.year"
            :label="item.year"
            :value="item.year">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学期" prop="period">
        <el-select 
          v-model="form.period" 
          placeholder="请选择学期" 
          clearable
          style="width: 100%">
          <el-option
            v-for="item in schoolTermList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <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-form-item label="金额" prop="money">
        <el-input-number 
          v-model="form.money" 
          :precision="2"
          :min="0"
          placeholder="请输入金额"
          style="width: 100%" />
      </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="WaterOrderFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, putObj, getObj, getRoomList } from '/@/api/stuwork/waterorder'
import { queryAllSchoolYear } from '/@/api/basic/basicyear'
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 schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])
const typeList = ref<any[]>([])
const roomList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  id: '',
  roomNo: '',
  year: '',
  period: '',
  type: '',
  money: 0
})

// 定义校验规则
const dataRules = {
  roomNo: [
    { required: true, message: '请选择宿舍号', trigger: 'change' }
  ],
  year: [
    { required: true, message: '请选择学年', trigger: 'change' }
  ],
  period: [
    { required: true, message: '请选择学期', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  money: [
    { 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.roomNo = ''
      form.year = ''
      form.period = ''
      form.type = ''
      form.money = 0
      
      // 编辑时填充数据
      if (type === 'edit' && row) {
        form.id = row.id
        form.roomNo = row.roomNo || ''
        form.year = row.year || ''
        form.period = row.period || ''
        form.type = row.type || ''
        form.money = row.money || 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 = {
        roomNo: form.roomNo,
        year: form.year,
        period: form.period,
        type: form.type,
        money: form.money
      }
      
      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 getSchoolYearList = async () => {
  try {
    const res = await queryAllSchoolYear()
    if (res.data) {
      schoolYearList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    schoolYearList.value = []
  }
}

// 获取学期字典
const getSchoolTermDict = async () => {
  try {
    const res = await getDicts('school_term')
    if (res.data) {
      schoolTermList.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) {
    schoolTermList.value = []
  }
}

// 获取类型字典
const getTypeDict = async () => {
  try {
    const res = await getDicts('dorm_water_source_type')
    if (res.data) {
      typeList.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) {
    typeList.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(() => {
  getSchoolYearList()
  getSchoolTermDict()
  getTypeDict()
  getRoomListData()
})

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

