<template>
  <div class="appointment-layout">
    <!-- 顶部状态栏 -->
    <StatusBar :title="robotName" />

    <!-- 主内容区 -->
    <div class="layout-main">
      <div class="appointment-page">
        <!-- 动态背景层 -->
        <div class="bg-layer">
          <div class="bg-orb orb-1"></div>
          <div class="bg-orb orb-2"></div>
          <div class="bg-orb orb-3"></div>
          <div class="bg-grid-overlay"></div>
        </div>

        <!-- 内容区 -->
        <div class="appointment-content">
          <!-- 标题区 -->
          <div class="appointment-hero">
            <h1 class="page-title">预约核验</h1>
            <p class="page-subtitle">请选择预约信息核验方式</p>
          </div>

          <!-- 核验入口卡片 -->
          <div class="verify-options">
            <!-- 身份证读取 -->
            <div
              class="verify-card"
              role="button"
              tabindex="0"
              aria-label="身份证读取"
              @click="handleIdCard"
              @keydown.enter="handleIdCard"
            >
              <div class="card-body">
                <div class="verify-icon idcard-icon">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
                    <rect x="2" y="4" width="20" height="16" rx="2" />
                    <circle cx="8.5" cy="10" r="2.5" />
                    <path d="M2 16h5" />
                    <path d="M2 19h3" />
                    <line x1="13" y1="9" x2="20" y2="9" />
                    <line x1="13" y1="13" x2="20" y2="13" />
                    <line x1="13" y1="17" x2="17" y2="17" />
                  </svg>
                </div>
                <div class="verify-text">
                  <h3>身份证读取</h3>
                  <p>请将身份证放置在读卡区，系统将自动核验</p>
                </div>
              </div>
            </div>

            <!-- 手机号查询 -->
            <div
              class="verify-card"
              role="button"
              tabindex="0"
              aria-label="手机号查询"
              @click="showPhoneInputModal"
              @keydown.enter="showPhoneInputModal"
            >
              <div class="card-body">
                <div class="verify-icon phone-icon">
                  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
                    <rect x="5" y="2" width="14" height="20" rx="3" />
                    <line x1="12" y1="17" x2="12.01" y2="17" stroke-width="2.5" />
                    <line x1="9" y1="8" x2="15" y2="8" />
                    <line x1="9" y1="12" x2="15" y2="12" />
                  </svg>
                </div>
                <div class="verify-text">
                  <h3>手机号查询</h3>
                  <p>输入预约手机号，快速查询您的到访预约</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 悬浮返回按钮 -->
        <button class="btn-back" @click="goToVisitor">
          <svg class="back-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
            <path d="M15 18l-6-6 6-6" />
          </svg>
          <span>返回登记</span>
        </button>
      </div>
    </div>

    <!-- 手机号输入弹窗 -->
    <Teleport to="body">
      <div v-if="showPhoneInput" class="phone-modal" @click.self="closePhoneModal">
        <div class="modal-card">
          <!-- 弹窗标题 -->
          <div class="modal-header">
            <h2>手机号查询</h2>
            <p>请输入预约时预留的手机号</p>
          </div>

          <!-- 数字键盘 -->
          <NumericKeyboard
            v-model="phoneNumber"
            :max-length="11"
            type="phone"
            :class="{ 'keyboard-error': phoneError }"
            @confirm="handlePhoneConfirm"
          />

          <!-- 操作按钮 -->
          <div class="modal-actions">
            <button class="btn-cancel" @click="closePhoneModal">取消</button>
            <button
              class="btn-confirm"
              :disabled="loading"
              @click="handlePhoneConfirm"
            >
              {{ loading ? '查询中...' : '查询' }}
            </button>
          </div>

          <!-- 转现场登记 -->
          <button class="btn-switch" @click="goToWalkIn">
            未查询到？转现场登记
          </button>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import StatusBar from '@/components/StatusBar.vue'
import NumericKeyboard from '@/components/NumericKeyboard.vue'
import { useScreenStore } from '@/stores/screen'
import { useVisitorStore } from '@/stores/visitor'

const router = useRouter()
const screenStore = useScreenStore()
const visitorStore = useVisitorStore()

const robotName = computed(() => screenStore.screenTheme?.robotName || '迎宾巡逻机器人')

const showPhoneInput = ref(false)
const phoneNumber = ref('')
const phoneError = ref(false)
const loading = ref(false)

const showPhoneInputModal = () => {
  phoneNumber.value = ''
  phoneError.value = false
  showPhoneInput.value = true
}

const closePhoneModal = () => {
  showPhoneInput.value = false
  phoneNumber.value = ''
  phoneError.value = false
}

const goToVisitor = () => {
  router.push('/visitor')
}

const goToWalkIn = () => {
  closePhoneModal()
  router.push('/visitor/walk-in')
}

const handleIdCard = async () => {
  if (loading.value) return
  loading.value = true
  try {
    const result = await visitorStore.readIdCard()
    screenStore.showAlert({
      type: 'success',
      message: '身份证读取成功，正在核验...'
    })
    if (result.idCardNo) {
      try {
        await visitorStore.queryAppointment({ idCardNo: result.idCardNo })
        router.push('/visitor/appointment-confirm')
      } catch {
        screenStore.showAlert({
          type: 'info',
          message: '未查询到预约信息，您可以转现场登记',
          duration: 4000
        })
      }
    }
  } catch {
    screenStore.showAlert({
      type: 'error',
      message: '身份证读取失败，请重新放置证件，或使用手机号查询',
      duration: 4000
    })
  } finally {
    loading.value = false
  }
}

const handlePhoneConfirm = async () => {
  if (loading.value) return

  // #region debug log
  fetch('http://127.0.0.1:7870/ingest/a84a825e-d3f2-4bc0-99e9-e2345f77eced',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'ce506e'},body:JSON.stringify({sessionId:'ce506e',location:'Appointment.vue:handlePhoneConfirm',message:'手机号查询开始',data:{phoneNumber:phoneNumber.value},timestamp:Date.now()})}).catch(()=>{});
  // #endregion

  if (!phoneNumber.value || phoneNumber.value.length !== 11) {
    phoneError.value = true
    screenStore.showAlert({
      type: 'warning',
      message: '请输入正确的11位手机号',
      duration: 3000
    })
    return
  }

  phoneError.value = false
  loading.value = true
  try {
    // #region debug log
    fetch('http://127.0.0.1:7870/ingest/a84a825e-d3f2-4bc0-99e9-e2345f77eced',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'ce506e'},body:JSON.stringify({sessionId:'ce506e',location:'Appointment.vue:handlePhoneConfirm',message:'调用 visitorStore.queryAppointment',data:{params:{mobile:phoneNumber.value}},timestamp:Date.now()})}).catch(()=>{});
    // #endregion
    const result = await visitorStore.queryAppointment({ mobile: phoneNumber.value })
    // #region debug log
    fetch('http://127.0.0.1:7870/ingest/a84a825e-d3f2-4bc0-99e9-e2345f77eced',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'ce506e'},body:JSON.stringify({sessionId:'ce506e',location:'Appointment.vue:handlePhoneConfirm',message:'queryAppointment 成功',data:{result},timestamp:Date.now()})}).catch(()=>{});
    // #endregion
    closePhoneModal()
    router.push('/visitor/appointment-confirm')
  } catch (err) {
    // #region debug log
    fetch('http://127.0.0.1:7870/ingest/a84a825e-d3f2-4bc0-99e9-e2345f77eced',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'ce506e'},body:JSON.stringify({sessionId:'ce506e',location:'Appointment.vue:handlePhoneConfirm',message:'queryAppointment 失败',data:{error:err?.message||err},timestamp:Date.now()})}).catch(()=>{});
    // #endregion
    screenStore.showAlert({
      type: 'info',
      message: '未查询到预约信息，您可以转现场登记',
      duration: 4000
    })
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
/* 页面布局 */
.appointment-layout {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 主内容 */
.layout-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

/* 预约页面容器 */
.appointment-page {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  overflow: hidden;
}

/* 动态背景 */
.bg-layer {
  position: absolute;
  inset: 0;
  background: linear-gradient(160deg, #e8f1fd 0%, #dbeeff 30%, #eef5ff 60%, #e5f0f8 100%);
  overflow: hidden;
}

.bg-orb {
  position: absolute;
  border-radius: 50%;
  filter: blur(80px);
  pointer-events: none;
}

.orb-1 {
  top: -180px;
  right: -120px;
  width: 560px;
  height: 560px;
  background: radial-gradient(ellipse, rgba(59, 130, 246, 0.14) 0%, transparent 65%);
  animation: orbFloat 18s ease-in-out infinite;
}

.orb-2 {
  bottom: -140px;
  left: -100px;
  width: 480px;
  height: 480px;
  background: radial-gradient(ellipse, rgba(6, 182, 212, 0.11) 0%, transparent 65%);
  animation: orbFloat 22s ease-in-out infinite reverse;
}

.orb-3 {
  top: 40%;
  left: 45%;
  transform: translate(-50%, -50%);
  width: 320px;
  height: 320px;
  background: radial-gradient(ellipse, rgba(47, 142, 229, 0.06) 0%, transparent 65%);
  animation: orbFloat 15s ease-in-out infinite;
  animation-delay: -5s;
}

.bg-grid-overlay {
  position: absolute;
  inset: 0;
  background-image:
    linear-gradient(rgba(47, 142, 229, 0.025) 1px, transparent 1px),
    linear-gradient(90deg, rgba(47, 142, 229, 0.025) 1px, transparent 1px);
  background-size: 48px 48px;
  pointer-events: none;
}

@keyframes orbFloat {
  0%, 100% { transform: translate(0, 0) scale(1); }
  33% { transform: translate(20px, -15px) scale(1.05); }
  66% { transform: translate(-15px, 20px) scale(0.97); }
}

/* 内容区 */
.appointment-content {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 1200px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 标题区 */
.appointment-hero {
  text-align: center;
  flex-shrink: 0;
  padding-top: 64px;
  margin-bottom: 40px;
}

.page-title {
  font-size: 54px;
  font-weight: 900;
  color: var(--text-primary);
  letter-spacing: 3px;
  margin: 0 0 6px;
  line-height: 1.05;
}

.page-subtitle {
  font-size: 22px;
  color: var(--text-secondary);
  margin: 0;
  font-weight: 500;
  line-height: 1.25;
}

/* 核验卡片 */
.verify-options {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 36px;
  width: 100%;
}

.verify-card {
  height: 420px;
  padding: 48px 52px 44px;
  border-radius: 44px;
  background: rgba(255, 255, 255, 0.92);
  border: 1px solid rgba(255, 255, 255, 0.80);
  box-shadow:
    0 28px 80px rgba(30, 64, 175, 0.14),
    0 2px 10px rgba(255, 255, 255, 0.72) inset;
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
  cursor: pointer;
  transition: all 0.22s ease;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-sizing: border-box;
  -webkit-tap-highlight-color: transparent;
  user-select: none;
}

.verify-card:hover {
  transform: translateY(-6px);
  box-shadow:
    0 34px 88px rgba(30, 64, 175, 0.18),
    0 2px 10px rgba(255, 255, 255, 0.78) inset;
}

.verify-card:active {
  transform: scale(0.984);
}

.card-body {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding-top: 4px;
}

/* 卡片图标 */
.verify-icon {
  width: 116px;
  height: 116px;
  border-radius: 32px;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  flex-shrink: 0;
}

.verify-icon svg {
  width: 58px;
  height: 58px;
}

.idcard-icon {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  box-shadow: 0 18px 36px rgba(37, 99, 235, 0.24);
}

.phone-icon {
  background: linear-gradient(135deg, #20b7c7 0%, #0ea5e9 100%);
  box-shadow: 0 18px 36px rgba(32, 183, 199, 0.28);
}

/* 卡片文字 */
.verify-text {
  display: flex;
  flex-direction: column;
}

.verify-text h3 {
  font-size: 44px;
  font-weight: 900;
  color: var(--text-primary);
  margin: 0 0 14px;
  letter-spacing: 1.5px;
  line-height: 1.15;
}

.verify-text p {
  font-size: 22px;
  color: var(--text-secondary);
  line-height: 1.50;
  margin: 0;
  font-weight: 500;
}

/* 悬浮返回按钮 */
.btn-back {
  position: absolute;
  left: 42px;
  bottom: 30px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  height: 66px;
  padding: 0 30px;
  background: rgba(255, 255, 255, 0.88);
  border: 1px solid rgba(47, 142, 229, 0.20);
  border-radius: 999px;
  box-shadow:
    0 12px 36px rgba(47, 142, 229, 0.14),
    0 2px 8px rgba(0, 0, 0, 0.06);
  color: var(--text-secondary);
  font-size: 23px;
  font-weight: 800;
  cursor: pointer;
  transition: all 0.22s ease;
  letter-spacing: 1.5px;
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  z-index: 10;
}

.btn-back:hover {
  background: rgba(255, 255, 255, 0.97);
  color: var(--primary);
  box-shadow:
    0 18px 48px rgba(47, 142, 229, 0.22),
    0 4px 12px rgba(0, 0, 0, 0.08);
  transform: translateY(-3px);
}

.btn-back:active {
  transform: scale(0.97);
  box-shadow: 0 8px 24px rgba(47, 142, 229, 0.12);
}

.back-icon {
  width: 22px;
  height: 22px;
  flex-shrink: 0;
}

/* 手机号输入弹窗 */
.phone-modal {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.48);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 200;
  animation: fadeIn 0.2s ease-out;
  backdrop-filter: blur(6px);
  -webkit-backdrop-filter: blur(6px);
}

.modal-card {
  width: 800px;
  max-width: calc(100vw - 48px);
  max-height: calc(100vh - 48px);
  overflow-y: auto;
  padding: 44px 56px 40px;
  background: rgba(255, 255, 255, 0.97);
  border-radius: 40px;
  box-shadow:
    0 40px 100px rgba(30, 64, 175, 0.22),
    0 4px 16px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  display: flex;
  flex-direction: column;
  align-items: center;
  scrollbar-width: thin;
}

.modal-header {
  text-align: center;
  margin-bottom: 28px;
  flex-shrink: 0;
}

.modal-header h2 {
  font-size: 36px;
  font-weight: 900;
  color: var(--text-primary);
  margin: 0 0 8px;
  letter-spacing: 2px;
}

.modal-header p {
  font-size: 20px;
  color: var(--text-secondary);
  margin: 0;
  font-weight: 500;
}

/* 操作按钮 */
.modal-actions {
  display: grid;
  grid-template-columns: 1fr 1.5fr;
  gap: 16px;
  width: 100%;
  margin-top: 24px;
  flex-shrink: 0;
}

.btn-cancel,
.btn-confirm {
  height: 74px;
  font-size: 26px;
  font-weight: 800;
  border-radius: 999px;
  cursor: pointer;
  transition: all 0.22s ease;
  letter-spacing: 1.5px;
}

.btn-cancel {
  background: rgba(107, 114, 128, 0.10);
  color: #4b5563;
  border: 1px solid rgba(107, 114, 128, 0.15);
}

.btn-cancel:hover {
  background: rgba(107, 114, 128, 0.16);
}

.btn-cancel:active {
  transform: scale(0.97);
}

.btn-confirm {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  border: none;
  box-shadow: 0 12px 28px rgba(37, 99, 235, 0.28);
}

.btn-confirm:hover {
  box-shadow: 0 16px 36px rgba(37, 99, 235, 0.36);
  transform: translateY(-2px);
}

.btn-confirm:active {
  transform: scale(0.97);
}

.btn-confirm:disabled {
  background: linear-gradient(135deg, #93c5fd 0%, #60a5fa 100%);
  cursor: not-allowed;
  box-shadow: none;
  transform: none;
}

/* 转现场登记 */
.btn-switch {
  margin-top: 20px;
  padding: 0;
  background: none;
  border: none;
  color: var(--primary);
  font-size: 17px;
  font-weight: 600;
  cursor: pointer;
  text-decoration: underline;
  text-underline-offset: 3px;
  transition: color 0.2s;
  flex-shrink: 0;
}

.btn-switch:hover {
  color: var(--primary-dark);
}

/* 开发调试入口按钮 */
.btn-debug-entry {
  position: fixed;
  right: 16px;
  bottom: 16px;
  padding: 8px 16px;
  background: rgba(245, 158, 11, 0.15);
  border: 1px solid rgba(245, 158, 11, 0.40);
  border-radius: 999px;
  color: #d97706;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  z-index: 999;
  transition: all 0.2s ease;
  letter-spacing: 0.5px;
}

.btn-debug-entry:hover {
  background: rgba(245, 158, 11, 0.25);
  border-color: rgba(245, 158, 11, 0.60);
  transform: translateY(-1px);
}

.btn-debug-entry:active {
  transform: scale(0.97);
}

/* 键盘内部输入框错误态 */
:deep(.keyboard-error .keyboard-input) {
  border-color: #ef4444 !important;
  background: linear-gradient(160deg, #fef2f2 0%, #fee2e2 100%) !important;
}

:deep(.keyboard-error .input-label) {
  color: #dc2626 !important;
}

:deep(.keyboard-error .placeholder) {
  color: #fca5a5 !important;
}

/* 键盘宽屏大按钮覆盖 */
:deep(.numeric-keyboard) {
  width: 100%;
  max-width: 100%;
}

:deep(.numeric-keyboard .keyboard-input) {
  height: 108px;
  min-height: 108px;
  max-height: 108px;
  padding: 0 24px;
  margin-bottom: 16px;
}

:deep(.numeric-keyboard .input-value) {
  height: 100%;
  min-height: 0;
}

:deep(.numeric-keyboard .keyboard-keys) {
  gap: 14px;
}

:deep(.numeric-keyboard .key-btn) {
  height: 82px;
  font-size: 32px;
  font-weight: 700;
  border-radius: 20px;
}

:deep(.numeric-keyboard .key-btn svg) {
  width: 34px;
  height: 34px;
}

:deep(.numeric-keyboard .key-action) {
  background: rgba(107, 114, 128, 0.08);
}

:deep(.numeric-keyboard .key-delete) {
  color: var(--text-secondary);
}

:deep(.numeric-keyboard .key-delete:hover) {
  background: rgba(239, 68, 68, 0.06);
  border-color: rgba(239, 68, 68, 0.20);
  color: #dc2626;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

/* 响应式 */
@media (max-width: 900px), (max-height: 660px) {
  .appointment-hero {
    padding-top: 50px;
    margin-bottom: 32px;
  }

  .page-title {
    font-size: 46px;
    letter-spacing: 2px;
    margin-bottom: 5px;
  }

  .page-subtitle {
    font-size: 20px;
  }

  .verify-options {
    gap: 36px;
  }

  .verify-card {
    height: 360px;
    padding: 38px 42px 34px;
    border-radius: 38px;
  }

  .verify-icon {
    width: 94px;
    height: 94px;
    border-radius: 28px;
    margin-bottom: 24px;
  }

  .verify-icon svg {
    width: 48px;
    height: 48px;
  }

  .verify-text h3 {
    font-size: 36px;
    margin-bottom: 12px;
  }

  .verify-text p {
    font-size: 18px;
    line-height: 1.42;
  }

  .btn-back {
    left: 30px;
    bottom: 24px;
    height: 62px;
    padding: 0 28px;
    font-size: 21px;
  }

  .modal-card {
    width: 560px;
    padding: 36px 40px 30px;
  }

  .modal-header h2 {
    font-size: 30px;
  }

  .modal-header p {
    font-size: 18px;
  }

  .phone-value {
    font-size: 28px;
  }

  .btn-cancel,
  .btn-confirm {
    height: 60px;
    font-size: 22px;
  }
}
</style>
