<template>
  <el-dialog
    title="打印宿舍卡"
    v-model="visible"
    :close-on-click-modal="false"
    width="640px"
    destroy-on-close
    @closed="onClosed">
    <div v-loading="loading">
      <el-form :inline="true" class="mb16">
        <el-form-item label="房间号">
          <el-input v-model="roomNo" placeholder="请输入房间号" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFetch">查询并预览</el-button>
        </el-form-item>
      </el-form>
      <div v-if="printData.length" ref="printAreaRef" class="print-area">
        <div v-for="(room, idx) in printData" :key="idx" class="room-card mb16">
          <div class="room-title">房间号：{{ room.roomNo }}</div>
          <table class="print-table">
            <thead>
              <tr>
                <th>姓名</th>
                <th>学号</th>
                <th>床位</th>
                <th>是否舍长</th>
                <th>班级</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(s, i) in (room.dormRoomStudentVOList || [])" :key="i">
                <td>{{ s.realName }}</td>
                <td>{{ s.stuNo }}</td>
                <td>{{ s.bedNo }}</td>
                <td>{{ s.isLeader === '1' ? '是' : '否' }}</td>
                <td>{{ s.className || s.classNo }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">关 闭</el-button>
        <el-button type="primary" @click="handlePrint" :disabled="!printData.length">打 印</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="DormRoomStudentPrintCard">
import { ref } from 'vue'
import { useMessage } from '/@/hooks/message'
import { printDormRoomData } from '/@/api/stuwork/dormroomstudent'

const visible = ref(false)
const loading = ref(false)
const roomNo = ref('')
const printData = ref<any[]>([])
const printAreaRef = ref<HTMLElement>()

const openDialog = (initialRoomNo?: string) => {
  visible.value = true
  roomNo.value = initialRoomNo || ''
  printData.value = []
}

const onClosed = () => {
  printData.value = []
}

const handleFetch = async () => {
  const no = (roomNo.value || '').trim()
  if (!no) {
    useMessage().warning('请输入房间号')
    return
  }
  loading.value = true
  try {
    const res = await printDormRoomData(no)
    const data = res?.data ?? res
    printData.value = Array.isArray(data) ? data : (data ? [data] : [])
    if (!printData.value.length) {
      useMessage().info('该房间暂无数据')
    }
  } catch (err: any) {
    useMessage().error(err?.msg || '查询失败')
    printData.value = []
  } finally {
    loading.value = false
  }
}

const handlePrint = () => {
  if (!printData.value.length) return
  const win = window.open('', '_blank')
  if (!win) {
    useMessage().error('无法打开打印窗口')
    return
  }
  const el = printAreaRef.value
  if (el) {
    win.document.write(`
      <!DOCTYPE html><html><head><meta charset="utf-8"><title>宿舍卡</title>
      <style>
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #333; padding: 6px 8px; text-align: center; }
        .room-title { font-weight: bold; margin-bottom: 8px; }
      </style>
      </head><body>${el.innerHTML}</body></html>
    `)
    win.document.close()
    win.focus()
    setTimeout(() => {
      win.print()
      win.close()
    }, 300)
  }
}

defineExpose({ openDialog })
</script>

<style scoped lang="scss">
.print-area {
  max-height: 60vh;
  overflow: auto;
}
.room-card {
  padding: 12px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
}
.room-title {
  margin-bottom: 8px;
}
.print-table {
  width: 100%;
  border-collapse: collapse;
  th,
  td {
    border: 1px solid var(--el-border-color);
    padding: 6px 8px;
    text-align: center;
  }
}
.mb16 {
  margin-bottom: 16px;
}
</style>
