<template>
  <div class="recognize-wrapper">
    <div class="recognize-container">
      <!-- 状态圆形区域 -->
      <div class="status-circle" :class="statusClass">
        <div class="circle-glow" />
        <div class="fingerprint-icon-wrapper">
          <svg class="fingerprint-svg" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
            <!-- 外侧指纹脊线 -->
            <ellipse
              cx="100" cy="100" rx="85" ry="90" fill="none" stroke="currentColor" stroke-width="2"
              opacity="0.3"
            />
            <ellipse
              cx="100" cy="100" rx="75" ry="80" fill="none" stroke="currentColor" stroke-width="2"
              opacity="0.4"
            />
            <ellipse
              cx="100" cy="100" rx="65" ry="70" fill="none" stroke="currentColor" stroke-width="2"
              opacity="0.5"
            />

            <!-- 内侧指纹脊线 -->
            <path
              d="M100 30 C130 30, 150 50, 150 80 C150 110, 130 130, 100 130 C70 130, 50 110, 50 80 C50 50, 70 30, 100 30"
              fill="none" stroke="currentColor" stroke-width="2.5" opacity="0.6"
            />
            <path
              d="M100 40 C120 40, 135 55, 135 75 C135 95, 120 110, 100 110 C80 110, 65 95, 65 75 C65 55, 80 40, 100 40"
              fill="none" stroke="currentColor" stroke-width="2.5" opacity="0.7"
            />
            <path
              d="M100 50 C110 50, 120 60, 120 70 C120 80, 110 90, 100 90 C90 90, 80 80, 80 70 C80 60, 90 50, 100 50"
              fill="none" stroke="currentColor" stroke-width="2.5" opacity="0.8"
            />

            <!-- 指纹脊线 -->
            <path
              d="M60 60 Q100 40, 140 60" fill="none" stroke="currentColor" stroke-width="1.5"
              opacity="0.6"
            />
            <path
              d="M65 70 Q100 50, 135 70" fill="none" stroke="currentColor" stroke-width="1.5"
              opacity="0.6"
            />
            <path
              d="M70 80 Q100 60, 130 80" fill="none" stroke="currentColor" stroke-width="1.5"
              opacity="0.6"
            />
            <path
              d="M75 90 Q100 70, 125 90" fill="none" stroke="currentColor" stroke-width="1.5"
              opacity="0.6"
            />
            <path
              d="M80 100 Q100 80, 120 100" fill="none" stroke="currentColor" stroke-width="1.5"
              opacity="0.6"
            />

            <!-- 中央螺旋纹 -->
            <circle
              cx="100" cy="75" r="8" fill="none" stroke="currentColor" stroke-width="2"
              opacity="0.8"
            />
            <circle cx="100" cy="75" r="4" fill="currentColor" opacity="0.6" />
          </svg>

          <!-- 扫描线动画 -->
          <div v-if="status === 'recognizing'" class="scan-line" />
        </div>

        <!-- 成功图标 -->
        <div v-if="status === 'success'" class="success-icon">
          <svg viewBox="0 0 52 52" xmlns="http://www.w3.org/2000/svg">
            <circle cx="26" cy="26" r="25" fill="none" />
            <path fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
          </svg>
        </div>

        <!-- 失败图标 -->
        <div v-if="status === 'failed'" class="failed-icon">
          <svg viewBox="0 0 52 52" xmlns="http://www.w3.org/2000/svg">
            <circle cx="26" cy="26" r="25" fill="none" />
            <path fill="none" d="M16 16 36 36 M36 16 16 36" />
          </svg>
        </div>
      </div>

      <!-- 状态文本 -->
      <div class="status-text">
        {{ isConnected ? statusText : '设备未连接' }}
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <van-button
          type="default" size="large" round block class="action-btn password-btn"
          @click="goToPasswordLogin"
        >
          <template #icon>
            <i class="fas fa-key" />
          </template>
          使用密码登录
        </van-button>
        <van-button
          type="default" size="large" round block class="action-btn restart-btn"
          @click="handleRestart"
        >
          <template #icon>
            <i class="fas fa-redo-alt" />
          </template>
          重启指纹识别
        </van-button>
      </div>

      <!-- 用户信息（识别成功后显示） -->
      <!-- <div v-if="status === 'success' && userInfo" class="user-info">
        <div class="user-avatar">
          <span class="avatar-text">{{ userInfo.name ? userInfo.name.charAt(0) : '?' }}</span>
        </div>
        <div class="user-details">
          <div class="user-name">{{ userInfo.name || '未知用户' }}</div>
          <div class="user-role">{{ userInfo.loginName || '' }}</div>
        </div>
      </div> -->
    </div>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from 'vue-router';
import { ref, onMounted, onUnmounted } from 'vue';
import { showSuccessToast, showFailToast, Button as VanButton } from 'vant';

const route = useRoute();
const router = useRouter();

// 状态：waiting(等待识别), recognizing(识别中), success(成功), failed(失败)
const userInfo = ref(null);
const status = ref('waiting');
const statusText = ref('');
const isConnected = ref(false);
// 计算状态类名
const statusClass = ref('status-waiting');

// 更新状态
const updateStatus = (newStatus, text) => {
    status.value = newStatus;
    statusText.value = text;

    switch (newStatus) {
    case 'waiting':
        statusClass.value = 'status-waiting';
        break;
    case 'recognizing':
        statusClass.value = 'status-recognizing';
        break;
    case 'success':
        statusClass.value = 'status-success';
        break;
    case 'failed':
        statusClass.value = 'status-failed';
        break;
    }
};

// 处理指纹响应
const handleFingerprintResponse = data => {
    console.log('接收到指纹设备的响应信息', data);

    if (!data) {
        updateStatus('failed', '识别失败，未接收到数据');
        showFailToast('识别失败');
        return;
    }

    const code = data.code;
    const msg = data.message || '';
    const responseData = data.loginInfo;

    if (code === 0) {
        // 有数据说明登录成功
        userInfo.value = responseData;
        if (msg === '连接成功' || msg === '请按下手指') {
            isConnected.value = true;
            updateStatus('recognizing', '请按下手指');
        }
        if (msg === '正在同步指纹，请稍后进行指纹登录') {
            updateStatus('waiting', '正在同步指纹，请稍后进行指纹登录');
        }
        if (responseData) {
            updateStatus('success', '识别成功，登录成功！');
            setTimeout(() => {
                localStorage.setItem('#token', responseData.token);
                localStorage.setItem('#accountId', responseData.accountId);
                localStorage.setItem('#LoginInfo', JSON.stringify(responseData));
                showSuccessToast('欢迎登录，' + responseData.userName);
                const redirectUrl = window.location.href.split('redirectUrl=')[1];

                if (redirectUrl) {
                    window.location = decodeURIComponent(redirectUrl);
                } else {
                    router.push('/home');
                }
            }, 1000);
        }
    } else {
        if (msg === '连接失败') {
            isConnected.value = false;
        } else {
            updateStatus('failed', msg || '识别失败，请重试');
        }
    }
};

// 开始识别
const startRecognize = () => {
    if (!plugin.fingerprintConfig) {
        updateStatus('failed', '指纹设备插件未就绪');
        showFailToast('设备不支持指纹识别功能');
        return;
    }

    try {
        plugin.fingerprintConfig.recognize();
    } catch (error) {
        console.error('启动指纹识别失败', error);
        updateStatus('failed', '启动识别失败');
        showFailToast('启动识别失败');
    }
};

// 重启指纹识别
const handleRestart = () => {
    userInfo.value = null;
    isConnected.value = true;
    updateStatus('waiting', '指纹重启中，请稍后...');

    setTimeout(() => {
        startRecognize();
        updateStatus('recognizing', '请按下手指');
    }, 1000);
};

// 跳转到密码登录页面
const goToPasswordLogin = () => {
    const isOut = localStorage.getItem('isOut') === 'true';
    if (isOut) {
        router.push({ path: '/login', query: { isOut: 'true' } });
    } else {
        router.push('/login');
    }
};

// 组件挂载
onMounted(() => {
    // 检查URL参数中是否包含isOut=true，如果有则存储到localStorage
    const isOutParam = route.query.isOut;
    if (isOutParam !== undefined) {
        const isOutValue = String(isOutParam) === 'true' ? 'true' : 'false';
        if (isOutValue == 'true') {
            localStorage.setItem('isOut', isOutValue);
        } else {
            localStorage.setItem('isOut', isOutValue);
        }
    } else {
        localStorage.setItem('isOut', 'false');
    }

    // 设置指纹设备的响应处理函数
    if (plugin.fingerprintConfig) {
        plugin.fingerprintConfig.connect();
        plugin.fingerprintConfig.receiveFingerprintResponse = handleFingerprintResponse;
    }

    // 延迟500ms后开始识别
    setTimeout(() => {
        startRecognize();
    }, 500);
});

// 组件卸载
onUnmounted(() => {
    // 清理响应处理函数
    if (plugin.fingerprintConfig) {
        plugin.fingerprintConfig.receiveFingerprintResponse = () => { };
        plugin.fingerprintConfig.disableConnect();
    }
});
</script>

<style scoped>
.recognize-wrapper {
    width: 100%;
    height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    position: relative;
}

/* 背景动画 */
.recognize-wrapper::before {
    content: '';
    position: absolute;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
    background-size: 50px 50px;
    animation: backgroundMove 20s linear infinite;
}

@keyframes backgroundMove {
    0% {
        transform: translate(0, 0);
    }

    100% {
        transform: translate(50px, 50px);
    }
}

.recognize-container {
    position: relative;
    z-index: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 2rem;
    padding: 2rem;
    max-width: 500px;
    width: 90%;
}

/* 状态圆形 */
.status-circle {
    position: relative;
    width: clamp(250px, 40vw, 350px);
    height: clamp(250px, 40vw, 350px);
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.95);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    transition: all 0.5s ease;
    overflow: hidden;
}

.circle-glow {
    position: absolute;
    inset: -20px;
    border-radius: 50%;
    opacity: 0;
    transition: opacity 0.5s ease;
}

/* 等待状态 */
.status-waiting {
    border: 4px solid rgba(102, 126, 234, 0.3);
}

.status-waiting .circle-glow {
    background: radial-gradient(circle, rgba(102, 126, 234, 0.2) 0%, transparent 70%);
    opacity: 0.5;
}

/* 识别中状态 */
.status-recognizing {
    border: 4px solid #667eea;
    animation: circlePulse 2s infinite;
}

.status-recognizing .circle-glow {
    background: radial-gradient(circle, rgba(102, 126, 234, 0.4) 0%, transparent 70%);
    opacity: 1;
    animation: glowPulse 2s infinite;
}

@keyframes circlePulse {

    0%,
    100% {
        transform: scale(1);
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    }

    50% {
        transform: scale(1.05);
        box-shadow: 0 25px 70px rgba(102, 126, 234, 0.5);
    }
}

@keyframes glowPulse {

    0%,
    100% {
        opacity: 0.8;
    }

    50% {
        opacity: 1;
    }
}

/* 成功状态 */
.status-success {
    border: 4px solid #10b981;
    background: rgba(16, 185, 129, 0.1);
    animation: successBounce 0.6s ease;
}

.status-success .circle-glow {
    background: radial-gradient(circle, rgba(16, 185, 129, 0.3) 0%, transparent 70%);
    opacity: 1;
}

@keyframes successBounce {
    0% {
        transform: scale(1);
    }

    50% {
        transform: scale(1.1);
    }

    100% {
        transform: scale(1);
    }
}

/* 失败状态 */
.status-failed {
    border: 4px solid #ef4444;
    animation: shake 0.5s ease;
}

.status-failed .circle-glow {
    background: radial-gradient(circle, rgba(239, 68, 68, 0.3) 0%, transparent 70%);
    opacity: 1;
}

@keyframes shake {

    0%,
    100% {
        transform: translateX(0);
    }

    25% {
        transform: translateX(-10px);
    }

    75% {
        transform: translateX(10px);
    }
}

/* 指纹图标 */
.fingerprint-icon-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.fingerprint-svg {
    width: 60%;
    height: 60%;
    color: #9ca3af;
    transition: color 0.5s ease;
}

.status-waiting .fingerprint-svg {
    color: #d1d5db;
}

.status-recognizing .fingerprint-svg {
    color: #667eea;
}

.status-success .fingerprint-svg {
    color: #10b981;
    opacity: 0.3;
}

.status-failed .fingerprint-svg {
    color: #ef4444;
    opacity: 0.3;
}

/* 扫描线动画 */
.scan-line {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, transparent, #667eea, transparent);
    animation: scanning 2s linear infinite;
}

@keyframes scanning {
    0% {
        transform: translateY(0);
    }

    100% {
        transform: translateY(clamp(250px, 40vw, 350px));
    }
}

/* 成功图标 */
.success-icon {
    position: absolute;
    width: 50%;
    height: 50%;
    animation: iconAppear 0.5s ease forwards;
}

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

.success-icon circle {
    stroke: #10b981;
    stroke-width: 3;
    stroke-dasharray: 166;
    stroke-dashoffset: 166;
    animation: checkmarkCircle 0.6s ease-in-out forwards;
}

.success-icon path {
    stroke: #10b981;
    stroke-width: 4;
    stroke-linecap: round;
    stroke-linejoin: round;
    stroke-dasharray: 48;
    stroke-dashoffset: 48;
    animation: checkmark 0.3s 0.3s ease-in-out forwards;
}

@keyframes iconAppear {
    from {
        opacity: 0;
        transform: scale(0.5);
    }

    to {
        opacity: 1;
        transform: scale(1);
    }
}

@keyframes checkmarkCircle {
    to {
        stroke-dashoffset: 0;
    }
}

@keyframes checkmark {
    to {
        stroke-dashoffset: 0;
    }
}

/* 失败图标 */
.failed-icon {
    position: absolute;
    width: 50%;
    height: 50%;
    animation: iconAppear 0.5s ease forwards;
}

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

.failed-icon circle {
    stroke: #ef4444;
    stroke-width: 3;
    stroke-dasharray: 166;
    stroke-dashoffset: 166;
    animation: checkmarkCircle 0.6s ease-in-out forwards;
}

.failed-icon path {
    stroke: #ef4444;
    stroke-width: 4;
    stroke-linecap: round;
    stroke-dasharray: 50;
    stroke-dashoffset: 50;
    animation: crossmark 0.3s 0.3s ease-in-out forwards;
}

@keyframes crossmark {
    to {
        stroke-dashoffset: 0;
    }
}

/* 状态文本 */
.status-text {
    font-size: clamp(1.2rem, 3vw, 1.8rem);
    font-weight: 600;
    color: white;
    text-align: center;
    text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    animation: textFadeIn 0.5s ease;
}

@keyframes textFadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* 用户信息卡片 */
.user-info {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16px;
    padding: 1.5rem 2rem;
    display: flex;
    align-items: center;
    gap: 1rem;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    animation: slideUp 0.5s ease;
    width: 100%;
    max-width: 400px;
}

@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.user-avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea, #764ba2);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.avatar-text {
    font-size: 1.5rem;
    font-weight: 700;
    color: white;
}

.user-details {
    flex: 1;
}

.user-name {
    font-size: 1.3rem;
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 0.25rem;
}

.user-role {
    font-size: 1rem;
    color: #6b7280;
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    gap: 1rem;
    animation: slideUp 0.5s ease;
}

.retry-button {
    height: 3.5rem;
    padding: 0 2.5rem;
    font-size: 1.1rem;
    font-weight: 600;
    background: white;
    color: #667eea;
    border: 2px solid white;
    border-radius: 50px;
    transition: all 0.3s ease;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.retry-button:hover {
    background: rgba(255, 255, 255, 0.9);
    transform: translateY(-2px);
    box-shadow: 0 15px 40px rgba(0, 0, 0, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .recognize-container {
        gap: 1.5rem;
        padding: 1.5rem;
    }

    .status-circle {
        width: clamp(200px, 50vw, 280px);
        height: clamp(200px, 50vw, 280px);
    }

    .user-info {
        padding: 1rem 1.5rem;
    }

    .user-avatar {
        width: 50px;
        height: 50px;
    }

    .avatar-text {
        font-size: 1.2rem;
    }

    .user-name {
        font-size: 1.1rem;
    }

    .user-role {
        font-size: 0.9rem;
    }
}

/* 暗色模式支持 */
@media (prefers-color-scheme: dark) {
    .status-circle {
        background: rgba(31, 41, 55, 0.95);
    }

    .user-info {
        background: rgba(31, 41, 55, 0.95);
    }

    .user-name {
        color: #f9fafb;
    }

    .user-role {
        color: #d1d5db;
    }
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    flex-direction: column;
    gap: 1rem;
    width: 100%;
    max-width: 350px;
    animation: textFadeIn 0.5s ease;
}

.action-btn {
    font-size: 1rem;
    font-weight: 500;
    height: 48px !important;
    transition: all 0.3s ease;
}

.action-btn i {
    margin-right: 8px;
    font-size: 16px;
}

/* 密码登录按钮样式 */
:deep(.password-btn) {
    background: rgba(255, 255, 255, 0.15) !important;
    border: 2px solid rgba(255, 255, 255, 0.5) !important;
    color: white !important;
    backdrop-filter: blur(10px);
}

:deep(.password-btn:active) {
    background: rgba(255, 255, 255, 0.25) !important;
}

/* 重启按钮样式 */
:deep(.restart-btn) {
    background: rgba(255, 255, 255, 0.1) !important;
    border: 2px solid rgba(255, 255, 255, 0.3) !important;
    color: rgba(255, 255, 255, 0.9) !important;
    backdrop-filter: blur(10px);
}

:deep(.restart-btn:active) {
    background: rgba(255, 255, 255, 0.2) !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .action-buttons {
        max-width: 100%;
        padding: 0 1rem;
    }
}

/* 减少动画（无障碍支持） */
@media (prefers-reduced-motion: reduce) {
    * {
        animation-duration: 0.01ms !important;
        animation-iteration-count: 1 !important;
        transition-duration: 0.01ms !important;
    }
}
</style>
