<template>
  <el-dialog 
    title="新增宿舍点名" 
    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="type">
            <el-select
              v-model="form.type"
              placeholder="请选择点名类型"
              clearable
              style="width: 100%">
              <el-option label="普通住宿点名" value="1" />
              <el-option label="留宿点名" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="楼号" prop="buildId">
            <el-select
              v-model="form.buildId"
              placeholder="请选择楼号"
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in buildingList"
                :key="item.buildingNo"
                :label="item.buildingNo"
                :value="item.buildingNo" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="房间号" prop="roomNo">
            <el-input
              v-model="form.roomNo"
              placeholder="请输入房间号"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-form-item label="学生列表" prop="list">
            <el-input
              v-model="studentNosInput"
              type="textarea"
              :rows="5"
              placeholder="请输入学号，多个学号用逗号或换行分隔"
              style="width: 100%" />
            <div class="form-tip">提示：多个学号可用逗号或换行分隔</div>
          </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="DormSignRecordFormDialog">
import { ref, reactive, nextTick, computed, onMounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { addObj } from '/@/api/stuwork/dormsignrecord'
import { getBuildingList } from '/@/api/stuwork/dormbuilding'

const emit = defineEmits(['refresh'])

// 定义变量内容
const dataFormRef = ref()
const visible = ref(false)
const loading = ref(false)
const buildingList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  type: '',
  buildId: '',
  roomNo: '',
  list: [] as Array<{ stuNo: string }>
})

// 学生学号输入（用于显示和编辑）
const studentNosInput = ref('')

// 定义校验规则
const dataRules = {
  type: [
    { required: true, message: '请选择点名类型', trigger: 'change' }
  ],
  buildId: [
    { required: true, message: '请选择楼号', trigger: 'change' }
  ],
  roomNo: [
    { required: true, message: '请输入房间号', trigger: 'blur' }
  ],
  list: [
    { required: true, message: '请输入至少一个学号', trigger: 'change' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value || value.length === 0) {
          callback(new Error('请输入至少一个学号'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 打开弹窗
const openDialog = async () => {
  visible.value = true
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
    form.type = ''
    form.buildId = ''
    form.roomNo = ''
    form.list = []
    studentNosInput.value = ''
  })
}

// 解析学号输入（支持逗号和换行分隔）
const parseStudentNos = (input: string): string[] => {
  if (!input || !input.trim()) return []
  return input
    .split(/[,\n]/)
    .map(s => s.trim())
    .filter(s => s.length > 0)
}

// 提交表单
const onSubmit = async () => {
  if (!dataFormRef.value) return
  
  // 解析学号列表
  const stuNos = parseStudentNos(studentNosInput.value)
  if (stuNos.length === 0) {
    useMessage().warning('请输入至少一个学号')
    return
  }
  
  form.list = stuNos.map(stuNo => ({ stuNo }))
  
  await dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    loading.value = true
    try {
      await addObj({
        type: form.type,
        buildId: form.buildId,
        roomNo: form.roomNo,
        list: form.list
      })
      useMessage().success('新增成功')
      visible.value = false
      emit('refresh')
    } catch (err: any) {
      if (!err?._messageShown) {
        useMessage().error(err?.msg || '新增失败')
      }
    } finally {
      loading.value = false
    }
  })
}

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

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

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

<style scoped lang="scss">
.mb20 {
  margin-bottom: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
