import React, { useState } from 'react' import { View, Text } from '@tarojs/components' import { Card, Button, Tag } from '@nutui/nutui-react-taro' import { Scan, Success, Failure, ArrowLeft } from '@nutui/icons-react-taro' import Taro from '@tarojs/taro' import { confirmWechatQRLogin, parseQRContent } from '@/api/passport/qr-login' enum ScanType { LOGIN = 'login', UNKNOWN = 'unknown', } interface ScanRecord { id: number time: string success: boolean type: ScanType message: string raw?: string } const UnifiedQRPage: React.FC = () => { const [loading, setLoading] = useState(false) const [lastRecord, setLastRecord] = useState(null) const [scanHistory, setScanHistory] = useState([]) const pushHistory = (record: ScanRecord) => { setLastRecord(record) setScanHistory((prev) => [record, ...prev.slice(0, 4)]) } const handleGoBack = () => { Taro.navigateBack() } const buildRecord = (success: boolean, type: ScanType, message: string, raw?: string): ScanRecord => ({ id: Date.now(), time: new Date().toLocaleString(), success, type, message, raw, }) const handleLoginScan = async (raw: string) => { const token = parseQRContent(raw) const userId = Number(Taro.getStorageSync('UserId') || 0) if (!token) { throw new Error('未识别到可登录的二维码内容') } if (!userId) { throw new Error('请先登录小程序账号后再扫码') } const result = await confirmWechatQRLogin(token, userId) if (result?.status !== 'confirmed') { throw new Error(result?.message || '二维码登录确认失败') } return '登录确认成功' } const handleStartScan = async () => { if (loading) return try { setLoading(true) const res = await Taro.scanCode({ scanType: ['qrCode'] }) const raw = (res.result || '').trim() if (!raw) { throw new Error('扫码结果为空') } const token = parseQRContent(raw) if (token) { const message = await handleLoginScan(raw) pushHistory(buildRecord(true, ScanType.LOGIN, message, raw)) Taro.showToast({ title: message, icon: 'success' }) return } const unsupportedMessage = '当前版本仅支持登录二维码,核销能力待补充' pushHistory(buildRecord(false, ScanType.UNKNOWN, unsupportedMessage, raw)) Taro.showToast({ title: unsupportedMessage, icon: 'none' }) } catch (error: any) { const message = error?.errMsg?.includes('cancel') ? '已取消扫码' : error?.message || '扫码失败' pushHistory(buildRecord(false, ScanType.UNKNOWN, message)) if (message !== '已取消扫码') { Taro.showToast({ title: message, icon: 'none' }) } } finally { setLoading(false) } } const getTypeTag = (type: ScanType) => { if (type === ScanType.LOGIN) { return 登录 } return 其他 } return ( 统一扫码 先恢复登录扫码,后续再补齐核销流程 扫码入口 当前可识别网页登录二维码,其他码先给出明确提示 {lastRecord && ( {lastRecord.success ? ( ) : ( )} 最近一次结果 {getTypeTag(lastRecord.type)} {lastRecord.message} {lastRecord.time} )} {scanHistory.length > 0 && ( 扫码记录 {scanHistory.map((item) => ( {item.message} {getTypeTag(item.type)} {item.time} ))} )} ) } export default UnifiedQRPage