<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-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="学年" prop="schoolYear">
            <el-select
              v-model="form.schoolYear"
              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-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="学期" prop="schoolTerm">
            <el-select
              v-model="form.schoolTerm"
              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-col>
        <el-col :span="24" class="mb20">
          <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-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="奖项名称" prop="ruleId">
            <el-select
              v-model="form.ruleId"
              placeholder="请选择奖项名称"
              clearable
              filterable
              style="width: 100%"
              @change="handleRewardRuleChange">
              <el-option
                v-for="item in rewardRuleList"
                :key="item.id"
                :label="item.ruleName"
                :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="form.remarks"
              type="textarea"
              :rows="4"
              placeholder="请输入备注"
              :maxlength="250"
              show-word-limit
              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="RewardDormFormDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj, editObj, getDetail } from '/@/api/stuwork/rewarddorm'
import { dormRoomList } from '/@/api/stuwork/dormroom'
import { getList as getRewardRuleList } from '/@/api/stuwork/rewardrule'
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')
const roomList = ref<any[]>([])
const schoolYearList = ref<any[]>([])
const schoolTermList = ref<any[]>([])
/** 奖项列表（来自接口 /stuwork/rewardrule/list） */
const rewardRuleList = ref<any[]>([])

// 提交表单数据（与接口文档一致：roomNo, ruleId, ruleName, schoolYear, schoolTerm, remarks）
const form = reactive({
  id: '',
  schoolYear: '',
  schoolTerm: '',
  roomNo: '',
  ruleId: '',
  ruleName: '',
  remarks: ''
})

// 定义校验规则
const dataRules = {
  schoolYear: [
    { required: true, message: '请选择学年', trigger: 'change' }
  ],
  schoolTerm: [
    { required: true, message: '请选择学期', trigger: 'change' }
  ],
  roomNo: [
    { required: true, message: '请选择宿舍号', trigger: 'change' }
  ],
  ruleId: [
    { required: true, message: '请选择奖项名称', trigger: 'change' }
  ]
}

// 打开弹窗
const openDialog = async (type: string = 'add', row?: any) => {
  visible.value = true
  operType.value = type
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.id = ''
    form.schoolYear = ''
    form.schoolTerm = ''
    form.roomNo = ''
    form.ruleId = ''
    form.ruleName = ''
    form.remarks = ''
    
    // 编辑时填充数据
    if (type === 'edit' && row) {
      form.id = row.id
      form.schoolYear = row.schoolYear || ''
      form.schoolTerm = row.schoolTerm || ''
      form.roomNo = row.roomNo || ''
      form.ruleId = row.ruleId || ''
      form.ruleName = row.ruleName || ''
      form.remarks = row.remarks || ''
      handleRewardRuleChange(form.ruleId)
      
      // 如果需要获取详情
      if (row.id && (!row.ruleName || !row.schoolYear)) {
        loading.value = true
        getDetail(row.id).then((res: any) => {
          if (res.data) {
            form.schoolYear = res.data.schoolYear || ''
            form.schoolTerm = res.data.schoolTerm || ''
            form.roomNo = res.data.roomNo || ''
            form.ruleId = res.data.ruleId || ''
            form.ruleName = res.data.ruleName || ''
            form.remarks = res.data.remarks || ''
          }
        }).catch(() => {}).finally(() => {
          loading.value = false
        })
      }
    }
  })
}

// 选择奖项时同步 ruleName（提交时需要）
const handleRewardRuleChange = (id: string) => {
  const item = rewardRuleList.value.find((r) => r.id === id)
  form.ruleName = item ? item.ruleName : ''
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    try {
      // 与接口文档一致：roomNo, ruleId, ruleName, schoolYear, schoolTerm, remarks
      const submitData = {
        roomNo: form.roomNo,
        ruleId: form.ruleId != null && form.ruleId !== '' ? String(form.ruleId) : '',
        ruleName: form.ruleName,
        schoolYear: form.schoolYear,
        schoolTerm: form.schoolTerm,
        remarks: form.remarks || ''
      }
      
      if (operType.value === 'add') {
        await addObj(submitData)
        useMessage().success('新增成功')
      } else {
        await editObj({
          id: form.id,
          ...submitData
        })
        useMessage().success('编辑成功')
      }
      visible.value = false
      emit('refresh')
    } catch (_err) {
      // 不再在此处弹 error：request 拦截器已统一弹过，避免重复两个 error 弹窗
    } finally {
      loading.value = false
    }
  })
}

// 获取宿舍列表
const getRoomListData = async () => {
  try {
    const res = await dormRoomList()
    if (res.data && Array.isArray(res.data)) {
      roomList.value = res.data
    } else {
      roomList.value = []
    }
  } catch (err) {
    roomList.value = []
  }
}

// 获取奖项列表（接口：GET /stuwork/rewardrule/list）
const getRewardRuleData = async () => {
  try {
    const res = await getRewardRuleList()
    const list = res.data && Array.isArray(res.data) ? res.data : []
    rewardRuleList.value = list
  } catch (err) {
    rewardRuleList.value = []
  }
}

// 获取学年列表
const getSchoolYearData = async () => {
  try {
    const res = await queryAllSchoolYear()
    schoolYearList.value = res.data && Array.isArray(res.data) ? res.data : []
  } catch (err) {
    schoolYearList.value = []
  }
}

// 获取学期字典
const getSchoolTermData = async () => {
  try {
    const res = await getDicts('school_term')
    if (res.data && Array.isArray(res.data)) {
      schoolTermList.value = res.data.map((item: any) => ({
        label: item.label || item.dictLabel || item.name,
        value: item.value ?? item.dictValue ?? item.code
      }))
    } else {
      schoolTermList.value = []
    }
  } catch (err) {
    schoolTermList.value = []
  }
}

// 初始化
onMounted(() => {
  getRoomListData()
  getRewardRuleData()
  getSchoolYearData()
  getSchoolTermData()
})

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

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

