<script lang="ts" setup>
import { ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import type { ITodayStats } from '@/api/types/appointment'
import { getTodayAppointments } from '@/api/appointment'
import QRCode from 'qrcode';
import { md5 } from 'js-md5';

definePage({
  style: {
    navigationBarTitleText: '保安工作台',
  },
})

const stats = ref<ITodayStats>({ total: 0, checked_in: 0, checked_out: 0 })
const loading = ref(false)

async function loadData() {
  loading.value = true
  try {
    const res = await getTodayAppointments()
    stats.value = res.stats
  } catch {
    // ignore
  } finally {
    loading.value = false
  }
}

const QR_SECRET_KEY = 'LKTX_QR_SECRET_2024'

/** 验证二维码数据：检查签名有效性和时效性 */
function verifyQRData(data: { id: number; timestamp: number; sign: string }): { valid: boolean; expired: boolean } {
  const expectedSign = md5(`${data.id}|${data.timestamp}|${QR_SECRET_KEY}`)
  if (data.sign !== expectedSign) {
    return { valid: false, expired: false }
  }
  const now = Math.floor(Date.now() / 1000)
  const expired = (now - data.timestamp) > 10
  return { valid: true, expired }
}

function formatQRTime(timestamp: number): string {
  const d = new Date(timestamp * 1000)
  const pad = (n: number) => String(n).padStart(2, '0')
  return `${d.getFullYear()}年${pad(d.getMonth() + 1)}月${pad(d.getDate())}日 ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

async function handleScan() {
  try {
    const res = await uni.scanCode({ onlyFromCamera: true })
    const qrContent = res.result
    let data: any
    try {
      data = JSON.parse(qrContent)
    } catch {
      uni.showModal({ title: '二维码无效', content: '无法识别的二维码', showCancel: false })
      return
    }
    if (!data || !data.id || !data.timestamp || !data.sign) {
      uni.showModal({ title: '二维码无效', content: '二维码数据不完整，请使用有效二维码', showCancel: false })
      return
    }
    const result = verifyQRData(data)
    if (!result.valid) {
      uni.showModal({ title: '二维码无效', content: '二维码签名无效，请使用有效二维码', showCancel: false })
      return
    }
    if (result.expired) {
      const elapsed = Math.floor(Date.now() / 1000) - data.timestamp
      uni.showModal({
        title: '二维码已过期',
        content: `此二维码生成于 ${formatQRTime(data.timestamp)}，已过期${elapsed}秒`,
        showCancel: false,
      })
      return
    }
    uni.navigateTo({ url: `/subpackages/appointment/appointment-detail?id=${data.id}` })
  } catch {
    // 用户取消扫码
  }
}

onShow(() => {
  loadData()
})
</script>

<template>
  <view class="workbench-page min-h-screen bg-[#f5f5f5]">
    <!-- 头部标题 -->
    <view class="px-4 pt-5 pb-3">
      <text class="text-xl font-bold text-[#1a1a1a]">保安工作台</text>
      <text class="mt-1 block text-sm text-[#999]">扫码核验、登记进出场</text>
    </view>

    <!-- 统计卡片 -->
    <view class="stats-row flex gap-3 px-3">
      <view class="stat-card flex flex-1 flex-col items-center rounded-xl bg-white py-5 shadow-sm">
        <text class="text-3xl font-bold text-[#2979ff]">{{ stats.total }}</text>
        <text class="mt-1.5 text-xs text-[#999]">今日预约</text>
      </view>
      <view class="stat-card flex flex-1 flex-col items-center rounded-xl bg-white py-5 shadow-sm">
        <text class="text-3xl font-bold text-[#18bc37]">{{ stats.checked_in }}</text>
        <text class="mt-1.5 text-xs text-[#999]">已进场</text>
      </view>
      <view class="stat-card flex flex-1 flex-col items-center rounded-xl bg-white py-5 shadow-sm">
        <text class="text-3xl font-bold text-[#ff9900]">{{ stats.checked_out }}</text>
        <text class="mt-1.5 text-xs text-[#999]">已出场</text>
      </view>
    </view>

    <!-- 扫码入口（大卡片） -->
    <view class="px-3 mt-4">
      <view class="scan-card flex flex-col items-center rounded-xl bg-gradient-to-r from-[#2979ff] to-[#0d47a1] py-8 shadow-md" @click="handleScan">
        <wd-icon name="scan" size="48px" color="#fff" />
        <text class="mt-3 text-lg font-bold text-white">扫码核验</text>
        <text class="mt-1 text-sm text-white/70">扫描访客二维码进行入场/出场登记</text>
      </view>
    </view>

    <!-- 底部说明 -->
    <view class="px-3 mt-4">
      <view class="rounded-xl bg-white px-4 py-3 shadow-sm">
        <text class="text-sm font-medium text-[#1a1a1a]">操作指引</text>
        <text class="mt-1 block text-xs text-[#999] leading-relaxed">
          1. 访客出示入场二维码\n2. 点击上方「扫码核验」扫描二维码\n3. 确认信息后完成入场/出场登记
        </text>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.workbench-page {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.scan-card {
  transition: transform 0.2s;
  &:active {
    transform: scale(0.97);
  }
}
</style>
