<template>
  <ScreenLayout :show-back-btn="true" back-text="返回登记" back-target="/visitor">
    <div class="page-walk-in">
      <h1 class="page-title">现场登记</h1>

      <div class="form-container">
        <!-- 身份证读取 -->
        <div class="idcard-section">
          <button class="btn-idcard" @click="handleReadIdCard" :disabled="reading">
            <div class="idcard-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="2" y="4" width="20" height="16" rx="2" />
                <line x1="6" y1="8" x2="10" y2="8" />
                <line x1="6" y1="12" x2="18" y2="12" />
                <line x1="6" y1="16" x2="14" y2="16" />
              </svg>
            </div>
            <span v-if="reading">读取中...</span>
            <span v-else>读取身份证</span>
          </button>
        </div>

        <div class="form-divider">
          <span>或手动填写</span>
        </div>

        <!-- 表单 -->
        <div class="form-fields">
          <!-- 姓名 -->
          <div class="form-field">
            <label>访客姓名</label>
            <input
              type="text"
              v-model="formData.visitorName"
              placeholder="请输入姓名"
              class="input"
            />
          </div>

          <!-- 手机号 -->
          <div class="form-field">
            <label>手机号码</label>
            <div class="input-with-keyboard" @click="showKeyboard('mobile')">
              <span class="input-value">{{ formData.mobile || '请输入手机号' }}</span>
            </div>
          </div>

          <!-- 身份证号 -->
          <div class="form-field">
            <label>身份证号</label>
            <div class="input-with-keyboard" @click="showKeyboard('idCardNo')">
              <span class="input-value">{{ formData.idCardNo || '请输入身份证号' }}</span>
            </div>
          </div>

          <!-- 被访人 -->
          <div class="form-field">
            <label>被访人</label>
            <input
              type="text"
              v-model="formData.visitedPerson"
              placeholder="请输入被访人姓名"
              class="input"
            />
          </div>

          <!-- 来访事由 -->
          <div class="form-field">
            <label>来访事由</label>
            <div class="reason-options">
              <button
                v-for="option in visitReasons"
                :key="option.value"
                class="reason-btn"
                :class="{ active: formData.visitReason === option.value }"
                @click="formData.visitReason = option.value"
              >
                {{ option.label }}
              </button>
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <button class="btn-submit" @click="handleSubmit" :disabled="submitting">
          <span v-if="submitting" class="loading-spinner"></span>
          <span v-else>提交登记</span>
        </button>
      </div>

      <!-- 数字键盘弹窗 -->
      <div v-if="showKeyboardFlag" class="keyboard-modal" @click.self="hideKeyboard">
        <div class="keyboard-content">
          <div class="keyboard-header">
            <span>{{ keyboardLabel }}</span>
            <button class="keyboard-close" @click="hideKeyboard">完成</button>
          </div>
          <NumericKeyboard
            v-model="currentInput"
            :label="keyboardLabel"
            :max-length="keyboardMaxLength"
            :type="keyboardType"
            @confirm="handleKeyboardConfirm"
          />
        </div>
      </div>
    </div>
  </ScreenLayout>
</template>

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

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

const reading = ref(false)
const submitting = ref(false)

// 键盘相关
const showKeyboardFlag = ref(false)
const currentInput = ref('')
const currentField = ref('')
const keyboardLabel = ref('')
const keyboardMaxLength = ref(11)
const keyboardType = ref('phone')

const visitReasons = visitorStore.visitReasonOptions

const formData = reactive({
  visitorName: '',
  mobile: '',
  idCardNo: '',
  visitedPerson: '',
  visitReason: ''
})

const showKeyboard = (field) => {
  currentField.value = field
  currentInput.value = formData[field] || ''

  if (field === 'mobile') {
    keyboardLabel.value = '手机号'
    keyboardMaxLength.value = 11
    keyboardType.value = 'phone'
  } else if (field === 'idCardNo') {
    keyboardLabel.value = '身份证号'
    keyboardMaxLength.value = 18
    keyboardType.value = 'idcard'
  }

  showKeyboardFlag.value = true
}

const hideKeyboard = () => {
  showKeyboardFlag.value = false
}

const handleKeyboardConfirm = (value) => {
  formData[currentField.value] = value
  hideKeyboard()
}

const handleReadIdCard = async () => {
  reading.value = true
  try {
    const result = await visitorStore.readIdCard()
    formData.visitorName = result.name || ''
    formData.idCardNo = result.idCardNo || ''
    screenStore.showAlert({
      type: 'success',
      message: '身份证读取成功'
    })
  } catch {
    screenStore.showAlert({
      type: 'error',
      message: '身份证读取失败，请手动输入'
    })
  } finally {
    reading.value = false
  }
}

const handleSubmit = async () => {
  // 验证
  if (!formData.visitorName?.trim()) {
    screenStore.showAlert({ type: 'warning', message: '请输入访客姓名' })
    return
  }
  if (!formData.mobile?.trim()) {
    screenStore.showAlert({ type: 'warning', message: '请输入手机号' })
    return
  }
  if (!/^1[3-9]\d{9}$/.test(formData.mobile)) {
    screenStore.showAlert({ type: 'warning', message: '手机号格式不正确' })
    return
  }

  submitting.value = true
  try {
    // 更新 store
    visitorStore.setFormField('visitorName', formData.visitorName)
    visitorStore.setFormField('mobile', formData.mobile)
    visitorStore.setFormField('idCardNo', formData.idCardNo)
    visitorStore.setFormField('visitedPerson', formData.visitedPerson)
    visitorStore.setFormField('visitReason', formData.visitReason)

    await visitorStore.submitRegistration()
    router.push('/visitor/success')
  } catch {
    screenStore.showAlert({
      type: 'error',
      message: '登记失败，请重试'
    })
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.page-walk-in {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
  overflow-y: auto;
}

.page-title {
  font-size: 32px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 24px;
}

.form-container {
  width: 100%;
  max-width: 500px;
  padding: 0 16px;
}

.idcard-section {
  margin-bottom: 24px;
}

.btn-idcard {
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  background: var(--primary-soft);
  color: var(--primary);
  border: 2px dashed var(--primary);
  border-radius: var(--radius-lg);
  font-size: 20px;
  font-weight: 500;
  cursor: pointer;
  transition: all var(--transition-fast);
}

.btn-idcard:hover:not(:disabled) {
  background: var(--primary);
  color: white;
  border-style: solid;
}

.btn-idcard:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.idcard-icon {
  width: 32px;
  height: 32px;
}

.idcard-icon svg {
  width: 100%;
  height: 100%;
}

.form-divider {
  display: flex;
  align-items: center;
  gap: 16px;
  margin: 24px 0;
}

.form-divider::before,
.form-divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background: var(--border-light);
}

.form-divider span {
  font-size: 14px;
  color: var(--text-muted);
}

.form-fields {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 32px;
}

.form-field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-field label {
  font-size: 16px;
  color: var(--text-secondary);
}

.input {
  width: 100%;
  height: 56px;
  padding: 0 16px;
  font-size: 18px;
  background: var(--bg-card);
  border: 2px solid var(--border-light);
  border-radius: var(--radius-lg);
  transition: border-color var(--transition-fast);
}

.input:focus {
  border-color: var(--primary);
}

.input::placeholder {
  color: var(--text-light);
}

.input-with-keyboard {
  height: 56px;
  padding: 0 16px;
  display: flex;
  align-items: center;
  background: var(--bg-card);
  border: 2px solid var(--border-light);
  border-radius: var(--radius-lg);
  cursor: pointer;
  transition: border-color var(--transition-fast);
}

.input-with-keyboard:hover {
  border-color: var(--primary);
}

.input-value {
  font-size: 18px;
  color: var(--text-light);
}

.input-with-keyboard:has(.input-value:not(:empty)) .input-value {
  color: var(--text-primary);
}

.reason-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.reason-btn {
  padding: 10px 18px;
  font-size: 15px;
  background: var(--bg-card);
  border: 2px solid var(--border-light);
  border-radius: var(--radius-full);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.reason-btn:hover {
  border-color: var(--primary);
  color: var(--primary);
}

.reason-btn.active {
  background: var(--primary);
  border-color: var(--primary);
  color: white;
}

.btn-submit {
  width: 100%;
  height: 64px;
  font-size: 22px;
  font-weight: 600;
  background: var(--primary);
  color: white;
  border: none;
  border-radius: var(--radius-lg);
  cursor: pointer;
  box-shadow: var(--shadow-md);
  transition: all var(--transition-fast);
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-submit:hover:not(:disabled) {
  background: var(--primary-dark);
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

.btn-submit:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top-color: white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 键盘弹窗 */
.keyboard-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 100;
  animation: fadeIn 0.2s ease-out;
}

.keyboard-content {
  width: 100%;
  background: var(--bg-card);
  border-radius: var(--radius-xl) var(--radius-xl) 0 0;
  padding: 20px;
  padding-bottom: 40px;
}

.keyboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.keyboard-header span {
  font-size: 18px;
  font-weight: 500;
  color: var(--text-primary);
}

.keyboard-close {
  padding: 8px 20px;
  font-size: 16px;
  color: var(--primary);
  background: none;
  border: none;
  cursor: pointer;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>
