<template>
    <div class="chat-container">
        <!-- 最左侧边栏 -->
        <Sidebar />

        <!-- 中间历史记录区域 -->
        <div class="history-sidebar">
            <div class="history-header">
                <span class="section-title">历史记录</span>
                <img
                    src="@/assets/Chat/2.png"
                    alt="新建任务"
                    class="new-chat-btn"
                    @click="createNewChat"
                />
            </div>

            <div class="history-list">
                <!-- 历史记录加载状态 -->
                <div
                    v-if="isLoadingHistory && historyTotal === 0"
                    class="history-loading"
                >
                    <div class="loading-spinner"></div>
                    <div class="loading-text">正在加载历史记录...</div>
                </div>

                <!-- 有数据时显示历史记录列表 -->
                <div
                    v-else-if="historyTotal > 0"
                    v-for="(item, index) in historyData"
                    :key="item.id"
                    :class="['history-item', { active: item.isActive }]"
                    @click="handleHistoryItem(item, $event)"
                >
                    <div class="history-content">
                        <div class="title-row">
                            <div class="history-title">{{ item.title }}</div>
                            <span
                                :class="[
                                    'history-tag',
                                    getTagClass(item.tagType),
                                ]"
                                >{{ getTagText(item.tagType) }}</span
                            >
                        </div>
                        <div class="time-row">
                            <span class="history-time">{{ item.time }}</span>
                        </div>
                        <div class="desc-row">
                            <div class="history-icon">
                                <img
                                    :src="item.originalImageUrl"
                                    alt="隐患图标"
                                    class="history-icon-img"
                                    @error="handleHistoryImageError($event, item)"
                                />
                            </div>
                            <div class="history-desc">
                                {{ item.description }}
                            </div>
                        </div>
                    </div>
                    <div
                        class="delete-btn"
                        @click.stop="deleteHistoryItem(item, index)"
                        :class="{ 'always-visible': item.isActive }"
                    >
                        <img
                            src="/src/assets/AIWriting/8.png"
                            alt="删除"
                            class="delete-icon"
                        />
                    </div>
                </div>

                <!-- 无数据时显示空状态 -->
                <div v-else class="empty-history">
                    <img
                        src="@/assets/Chat/22.png"
                        alt="暂无数据"
                        class="empty-icon"
                    />
                    <div class="empty-text">暂无数据</div>
                </div>
            </div>
        </div>

        <!-- 右侧工作区域 -->
        <div class="main-work">
            <!-- 头部 -->
            <div class="work-header">
                <h2>隐患提示</h2>
            </div>

            <!-- 工作内容区域 -->
            <div class="work-content">
                <!-- 主界面：隐患提示系统 -->
                <div v-if="currentView === 'main'" class="main-layout">
                    <!-- 左侧：隐患提示系统 -->
                    <div
                        class="left-section"
                        :class="{ transitioning: isTransitioning }"
                    >
                        <div class="hazard-system">
                            <div class="system-header">
                                <h3>智能隐患提示系统</h3>
                                <p>
                                    基于AI技术的工程安全智能隐患提示系统，实时检测分析，提供专业评估和预防建议
                                </p>
                            </div>

                            <!-- 步骤一：上传图片 -->
                            <div class="step-section">
                                <h4>步骤一：上传需要识别的场景图片</h4>
                                <p class="step-description">
                                    系统将自动识别场景与关键要素，无需手动选择
                                </p>
                                <div
                                    class="upload-area"
                                    @click="triggerFileUpload"
                                    @drop="handleDrop"
                                    @dragover="handleDragOver"
                                    @dragleave="handleDragLeave"
                                    :class="{ 'drag-over': isDragOver }"
                                >
                                    <!-- 显示上传的图片 -->
                                    <div
                                        v-if="uploadedImageUrl"
                                        class="uploaded-image-container"
                                    >
                                        <img
                                            :src="uploadedImageUrl"
                                            alt="已上传的图片"
                                            class="uploaded-image"
                                        />
                                        <div class="image-overlay">
                                            <button
                                                class="change-image-btn"
                                                @click.stop="reselectImage"
                                            >
                                                更换图片
                                            </button>
                                        </div>
                                    </div>

                                    <!-- 显示上传区域 -->
                                    <div v-else class="upload-content">
                                        <img
                                            src="@/assets/Hazard/5.png"
                                            alt="上传图标"
                                            class="upload-icon"
                                        />
                                        <p class="upload-text">点击上传图片</p>
                                        <p class="upload-format">
                                            支持JPG、PNG格式，单个文件不超过5MB
                                        </p>
                                        <!-- <p class="drag-hint">或拖拽图片到此处</p> -->
                                        <button
                                            class="select-file-btn"
                                            @click.stop="triggerFileUpload"
                                        >
                                            选择图片文件
                                        </button>
                                    </div>

                                    <!-- 上传状态指示器 -->
                                    <div
                                        v-if="isUploading"
                                        class="upload-status"
                                    >
                                        <div class="loading-spinner"></div>
                                        <p>正在上传...</p>
                                    </div>

                                    <!-- 识别状态指示器 -->
                                    <div
                                        v-if="isIdentifying"
                                        class="upload-status"
                                    >
                                        <div class="loading-spinner"></div>
                                        <p>正在识别隐患...</p>
                                    </div>

                                    <input
                                        ref="fileInput"
                                        type="file"
                                        accept="image/*"
                                        @change="handleFileUpload"
                                        style="display: none"
                                    />
                                </div>
                            </div>

                            <!-- 开始识别按钮 -->
                            <div class="action-section">
                                <button
                                    class="start-identify-btn"
                                    @click="startIdentification"
                                    :disabled="isIdentifying"
                                    :class="{ 'btn-disabled': isIdentifying }"
                                >
                                    <img
                                        :src="
                                            uploadedImageUrl
                                                ? startIdentifyActiveImg
                                                : startIdentifyImg
                                        "
                                        alt="开始识别"
                                        class="btn-bg"
                                    />
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 右侧：使用流程 -->
                    <div
                        class="right-section"
                        :class="{ 'slide-out': isTransitioning }"
                    >
                        <div class="process-card">
                            <h3>使用流程</h3>
                            <div class="process-section">
                                <div class="process-flow">
                                    <!-- 流程步骤1 -->
                                    <div class="process-step">
                                        <div class="step-icon-wrapper">
                                            <el-icon
                                                class="step-icon"
                                                :size="40"
                                                color="#3E7BFA"
                                            >
                                                <Upload />
                                            </el-icon>
                                            <div class="step-number">1</div>
                                        </div>
                                        <div class="step-content">
                                            <div class="step-title">
                                                上传图片
                                            </div>
                                            <div class="step-desc">
                                                选择相关场景的图片
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 连接线 -->
                                    <div class="step-connector"></div>

                                    <!-- 流程步骤2 -->
                                    <div class="process-step">
                                        <div class="step-icon-wrapper">
                                            <el-icon
                                                class="step-icon"
                                                :size="40"
                                                color="#3E7BFA"
                                            >
                                                <View />
                                            </el-icon>
                                            <div class="step-number">2</div>
                                        </div>
                                        <div class="step-content">
                                            <div class="step-title">
                                                场景识别
                                            </div>
                                            <div class="step-desc">
                                                智能识别场景要素
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 连接线 -->
                                    <div class="step-connector"></div>

                                    <!-- 流程步骤3 -->
                                    <div class="process-step">
                                        <div class="step-icon-wrapper">
                                            <el-icon
                                                class="step-icon"
                                                :size="40"
                                                color="#3E7BFA"
                                            >
                                                <DataAnalysis />
                                            </el-icon>
                                            <div class="step-number">3</div>
                                        </div>
                                        <div class="step-content">
                                            <div class="step-title">
                                                场景分析
                                            </div>
                                            <div class="step-desc">
                                                智能分析常见隐患
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 连接线 -->
                                    <div class="step-connector"></div>

                                    <!-- 流程步骤4 -->
                                    <div class="process-step">
                                        <div class="step-icon-wrapper">
                                            <el-icon
                                                class="step-icon"
                                                :size="40"
                                                color="#3E7BFA"
                                            >
                                                <Bell />
                                            </el-icon>
                                            <div class="step-number">4</div>
                                        </div>
                                        <div class="step-content">
                                            <div class="step-title">
                                                隐患提示
                                            </div>
                                            <div class="step-desc">
                                                提示场景常见隐患
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 详情页：隐患提示结果 -->
                <div v-if="currentView === 'detail'" class="detail-view">
                    <!-- 顶部标题栏 -->
                    <div class="detail-header">
                        <div class="header-left">
                            <svg
                                class="header-icon-svg"
                                viewBox="0 0 1024 1024"
                                xmlns="http://www.w3.org/2000/svg"
                                fill="currentColor"
                            >
                                <path
                                    d="M957.217391 86.372174C957.217391 86.372174 957.217391 608.211478 957.217391 608.211478 957.217391 639.510261 949.782261 670.630957 934.956522 701.573565 920.086261 732.605217 900.674783 762.568348 876.633043 791.685565 852.591304 820.758261 825.121391 848.317217 794.267826 874.273391 763.369739 900.274087 732.070957 923.425391 700.326957 943.727304 668.538435 964.073739 637.68487 980.992 607.721739 994.437565 577.758609 1007.88313 551.490783 1017.09913 528.918261 1022.130087 528.918261 1022.130087 518.233043 1024 518.233043 1024 518.233043 1024 508.438261 1022.130087 508.438261 1022.130087 485.286957 1017.09913 458.440348 1007.88313 427.853913 994.437565 397.267478 980.992 365.523478 964.073739 332.577391 943.727304 299.631304 923.425391 267.308522 900.274087 235.52 874.273391 203.776 848.317217 175.415652 820.758261 150.483478 791.685565 125.551304 762.568348 105.382957 732.605217 89.978435 701.573565 74.48487 670.630957 66.782609 639.510261 66.782609 608.211478 66.782609 608.211478 66.782609 86.372174 66.782609 86.372174 66.782609 86.372174 103.290435 80.717913 103.290435 80.717913 103.290435 80.717913 512.890435 0 512.890435 0 512.890435 0 930.504348 80.717913 930.504348 80.717913 930.504348 80.717913 957.217391 86.372174 957.217391 86.372174 957.217391 86.372174 957.217391 86.372174 957.217391 86.372174ZM513.024 75.553391C513.024 75.553391 508.082087 74.529391 508.082087 74.529391 508.082087 74.529391 156.538435 137.527652 156.538435 137.527652 156.538435 137.527652 156.538435 466.765913 156.538435 466.765913 156.538435 466.765913 513.024 466.765913 513.024 466.765913 513.024 466.765913 513.024 75.553391 513.024 75.553391 513.024 75.553391 513.024 75.553391 513.024 75.553391ZM867.461565 466.765913C867.461565 466.765913 513.024 466.765913 513.024 466.765913 513.024 466.765913 513.024 935.401739 513.024 935.401739 535.81913 929.881043 560.617739 921.466435 587.419826 910.113391 614.177391 898.760348 640.623304 885.359304 666.713043 869.865739 692.847304 854.372174 717.957565 837.186783 742.13287 818.265043 766.308174 799.343304 787.634087 778.99687 806.288696 757.314783 824.898783 735.677217 839.724522 713.149217 850.810435 689.730783 861.94087 666.35687 867.461565 642.582261 867.461565 618.496 867.461565 618.496 867.461565 466.765913 867.461565 466.765913 867.461565 466.765913 867.461565 466.765913 867.461565 466.765913Z"
                                />
                            </svg>
                            <div class="header-text">
                                <span class="main-title">{{
                                    detectionResult?.scene_name
                                        ? scenarios[detectionResult.scene_name]
                                              ?.name
                                        : "隐患提示结果"
                                }}</span>
                            </div>
                        </div>
                        <div class="header-right">
                            <div class="current-time">
                                {{
                                    selectedHistoryItem?.time ||
                                    getCurrentTime()
                                }}
                            </div>
                        </div>
                    </div>

                    <!-- 主要内容区域 -->
                    <div class="detail-content">
                        <!-- 加载状态 -->
                        <div
                            v-if="isLoadingDetail || isImageLoading"
                            class="loading-overlay"
                        >
                            <div class="loading-spinner"></div>
                            <p>
                                {{
                                    isLoadingDetail
                                        ? "正在加载详情..."
                                        : "正在加载图片..."
                                }}
                            </p>
                        </div>

                        <!-- 图片显示区域 -->
                        <div class="image-section">
                            <!-- 点评状态 -->
                            <div
                                class="evaluation-status"
                                @click="openEvaluationModal"
                            >
                                <span
                                    :class="[
                                        'status-badge',
                                        selectedHistoryItem?.effect_evaluation >
                                        0
                                            ? 'evaluated'
                                            : 'not-evaluated',
                                    ]"
                                >
                                    {{
                                        selectedHistoryItem?.effect_evaluation >
                                        0
                                            ? "已点评"
                                            : "未点评"
                                    }}
                                </span>
                            </div>

                            <div class="image-container" ref="imageContainerRef">
                                <!-- 显示图片：扫描时显示原图，扫描完成后显示标注图 -->
                                <img
                                    ref="mainImageRef"
                                    :src="
                                        showScanningEffect
                                            ? uploadedImageUrl
                                            : annotatedImageUrl
                                    "
                                    :alt="
                                        showScanningEffect
                                            ? '用户上传图片'
                                            : '隐患提示图片'
                                    "
                                    class="main-image"
                                    @click="openImagePreview()"
                                    style="
                                        cursor: pointer;
                                        transform: none !important;
                                    "
                                    @load="handleMainImageLoad"
                                    @error="handleMainImageError"
                                />

                                <div
                                    v-if="
                                        !showScanningEffect &&
                                        selectedKeyElement &&
                                        elementOverlayStyle
                                    "
                                    ref="elementCardRef"
                                    class="element-overlay-card"
                                    :style="elementOverlayStyle"
                                    @click.stop
                                >
                                    <div class="element-card-title">
                                        当前选中：{{ selectedKeyElement }}
                                    </div>
                                    <ul
                                        v-if="filteredHazards.length"
                                        class="element-card-list"
                                    >
                                        <li
                                            v-for="(
                                                hazard, index
                                            ) in filteredHazards"
                                            :key="index"
                                        >
                                            {{ hazard }}
                                        </li>
                                    </ul>
                                    <div v-else class="element-card-empty">
                                        暂无对应隐患
                                    </div>
                                </div>

                                <!-- 扫描效果覆盖层 -->
                                <div
                                    v-if="showScanningEffect"
                                    class="scanning-overlay"
                                >
                                    <div class="scanning-line"></div>
                                </div>
                            </div>
                        </div>

                        <!-- 识别结果分析 -->
                        <div class="analysis-section">
                            <div class="analysis-header">
                                <div class="robot-avatar">
                                    <img
                                        src="@/assets/Hazard/21.png"
                                        alt="蜀安AI助手"
                                        class="robot-img"
                                    />
                                </div>
                                <div class="header-title">
                                    <!-- 扫描期间显示分析提示 -->
                                    <div
                                        v-if="showAnalysisPrompt"
                                        class="analysis-prompt"
                                    >
                                        <div class="typing-indicator">
                                            <span class="dot"></span>
                                            <span class="dot"></span>
                                            <span class="dot"></span>
                                        </div>
                                        <span class="prompt-text"
                                            >蜀安AI助手正在为您智能分析图片，请稍候…</span
                                        >
                                    </div>
                                    <!-- 扫描完成后显示标题 -->
                                    <h3 v-else class="analysis-title">
                                        蜀道安全管理AI智能助手慧眼识图分析出以下结果
                                    </h3>
                                </div>
                            </div>

                            <!-- 分析结果内容区域 -->
                            <div
                                class="analysis-body"
                                v-if="!showAnalysisPrompt"
                            >
                                <div class="analysis-text">
                                    <span
                                        v-if="isStreamingAnalysis"
                                        v-html="streamingAnalysis"
                                        class="streaming-text"
                                    ></span>
                                    <span
                                        v-else-if="
                                            !isStreamingAnalysis &&
                                            detectionResult
                                        "
                                    >
                                        我识别到这是一个<span
                                            class="scene-tag"
                                            >{{
                                                detectionResult?.scene_name
                                                    ? scenarios[
                                                          detectionResult
                                                              .scene_name
                                                      ]?.name
                                                    : "未知场景"
                                            }}</span
                                        >场景，检测到的关键要素为<span
                                            v-for="(label, index) in displayLabels"
                                            :key="index"
                                            class="label-tag"
                                            >{{ label }}</span
                                        >
                                    </span>
                                </div>
                                <p
                                    class="hazards-intro"
                                    v-if="
                                        !isStreamingAnalysis && detectionResult
                                    "
                                >
                                    根据安全规范和施工标准，我为您梳理出以下需要重点关注的安全隐患
                                </p>

                                <div
                                    v-if="
                                        !isStreamingAnalysis &&
                                        detectionResult &&
                                        keyElements.length
                                    "
                                    class="key-elements-section"
                                >
                                    <div class="key-elements-title">
                                        关键要素
                                    </div>
                                    <div class="key-elements-buttons">
                                        <button
                                            v-for="element in keyElements"
                                            :key="element"
                                            :class="[
                                                'key-element-btn',
                                                {
                                                    active:
                                                        selectedKeyElement ===
                                                        element,
                                                },
                                            ]"
                                            @click="
                                                toggleKeyElement(element)
                                            "
                                        >
                                            {{ element }}
                                        </button>
                                    </div>
                                    <div
                                        v-if="!selectedKeyElement"
                                        class="key-elements-hint"
                                    >
                                        点击关键要素可查看对应隐患
                                    </div>
                                </div>

                                <!-- 场景隐患列表 -->
                                <div
                                    class="hazards-section"
                                    v-if="!showAnalysisPrompt"
                                >
                                    <div
                                        class="hazards-content"
                                        :class="{
                                            'scanning-mode': showScanningEffect,
                                        }"
                                    >
                                        <!-- 扫描期间的遮罩层 -->
                                        <div
                                            v-if="showScanningEffect"
                                            class="hazards-loading-overlay"
                                        >
                                            <div class="loading-spinner"></div>
                                            <p>正在分析场景隐患...</p>
                                        </div>

                                        <!-- 隐患内容 -->
                                        <div
                                            v-else
                                            class="hazard-cards-container"
                                        >
                                            <div
                                                v-if="!filteredHazards.length"
                                                class="hazard-empty"
                                            >
                                                暂无对应隐患
                                            </div>
                                            <div
                                                v-for="(
                                                    hazard, index
                                                ) in filteredHazards"
                                                :key="index"
                                                class="hazard-card"
                                                :class="{
                                                    show: visibleHazardCards[
                                                        index
                                                    ],
                                                }"
                                            >
                                                <div class="hazard-number">
                                                    {{ index + 1 }}
                                                </div>
                                                <div
                                                    class="hazard-text-container"
                                                >
                                                    <p class="hazard-desc">
                                                        {{ hazard }}
                                                    </p>
                                                    <a
                                                        href="javascript:void(0);"
                                                        class="example-link"
                                                        @click.prevent="
                                                            openExampleModal({
                                                                number:
                                                                    index + 1,
                                                                description:
                                                                    hazard,
                                                            })
                                                        "
                                                    >
                                                        示例
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 图片预览弹窗 -->
                    <teleport to="body">
                        <div
                            v-if="showImagePreview"
                            class="image-preview-overlay"
                            @click="closeImagePreview"
                        >
                            <img
                                :src="previewImageUrl || annotatedImageUrl"
                                alt="预览图片"
                                class="preview-image"
                                style="transform: none !important"
                            />
                        </div>
                    </teleport>

                    <!-- 示例对比弹窗 -->
                    <div
                        v-if="showExampleModal"
                        class="modal-backdrop"
                        @click="closeExampleModal"
                    >
                        <div class="example-comparison-modal" @click.stop>
                            <!-- 弹窗头部 -->
                            <div class="modal-header-section">
                                <div class="modal-title-area">
                                    <div class="hazard-info">
                                        <span class="hazard-number">{{
                                            selectedHazard?.number
                                        }}</span>
                                        <span class="hazard-text">{{
                                            selectedHazard?.description
                                        }}</span>
                                    </div>
                                </div>
                                <button
                                    class="close-button"
                                    @click="closeExampleModal"
                                >
                                    <svg
                                        width="24"
                                        height="24"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                    >
                                        <path
                                            d="M18 6L6 18M6 6L18 18"
                                            stroke="currentColor"
                                            stroke-width="2"
                                            stroke-linecap="round"
                                        />
                                    </svg>
                                </button>
                            </div>

                            <!-- 弹窗内容 -->
                            <div class="modal-content-section">
                                <!-- 加载状态 -->
                                <div
                                    v-if="isLoadingExample"
                                    class="loading-state"
                                >
                                    <div class="spinner"></div>
                                    <p>正在加载示例图片...</p>
                                </div>

                                <!-- 对比内容 -->
                                <div v-else class="comparison-container">
                                    <!-- 正确示例 -->
                                    <div class="example-card correct-example">
                                        <div class="card-header">
                                            <div class="status-badge correct">
                                                <svg
                                                    width="16"
                                                    height="16"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                >
                                                    <path
                                                        d="M20 6L9 17L4 12"
                                                        stroke="currentColor"
                                                        stroke-width="2"
                                                        stroke-linecap="round"
                                                        stroke-linejoin="round"
                                                    />
                                                </svg>
                                                正确示例
                                            </div>
                                        </div>
                                        <div class="card-content">
                                            <div
                                                v-if="
                                                    imageLoadingStates.correct
                                                "
                                                class="image-loading"
                                            >
                                                <div class="spinner"></div>
                                                <p>加载中...</p>
                                            </div>
                                            <img
                                                v-else-if="
                                                    exampleImages.correctImageUrl
                                                "
                                                :src="
                                                    exampleImages.correctImageUrl
                                                "
                                                alt="正确示例"
                                                class="example-image clickable-image"
                                                @error="
                                                    handleImageError(
                                                        $event,
                                                        'correct'
                                                    )
                                                "
                                                @load="
                                                    handleImageLoad(
                                                        $event,
                                                        'correct'
                                                    )
                                                "
                                                @click="
                                                    openImagePreview(
                                                        exampleImages.correctImageUrl
                                                    )
                                                "
                                            />
                                            <div v-else class="no-image">
                                                <svg
                                                    width="48"
                                                    height="48"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                >
                                                    <rect
                                                        x="3"
                                                        y="3"
                                                        width="18"
                                                        height="18"
                                                        rx="2"
                                                        ry="2"
                                                        stroke="currentColor"
                                                        stroke-width="2"
                                                    />
                                                    <circle
                                                        cx="8.5"
                                                        cy="8.5"
                                                        r="1.5"
                                                        stroke="currentColor"
                                                        stroke-width="2"
                                                    />
                                                    <path
                                                        d="M21 15L16 10L5 21"
                                                        stroke="currentColor"
                                                        stroke-width="2"
                                                    />
                                                </svg>
                                                <p>暂无示例图片</p>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 错误示例 -->
                                    <div class="example-card error-example">
                                        <div class="card-header">
                                            <div class="status-badge error">
                                                <svg
                                                    width="16"
                                                    height="16"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                >
                                                    <path
                                                        d="M18 6L6 18M6 6L18 18"
                                                        stroke="currentColor"
                                                        stroke-width="2"
                                                        stroke-linecap="round"
                                                    />
                                                </svg>
                                                错误示例
                                            </div>
                                        </div>
                                        <div class="card-content">
                                            <div
                                                v-if="imageLoadingStates.error"
                                                class="image-loading"
                                            >
                                                <div class="spinner"></div>
                                                <p>加载中...</p>
                                            </div>
                                            <img
                                                v-else-if="
                                                    exampleImages.errorImageUrl
                                                "
                                                :src="
                                                    exampleImages.errorImageUrl
                                                "
                                                alt="错误示例"
                                                class="example-image clickable-image"
                                                @error="
                                                    handleImageError(
                                                        $event,
                                                        'error'
                                                    )
                                                "
                                                @load="
                                                    handleImageLoad(
                                                        $event,
                                                        'error'
                                                    )
                                                "
                                                @click="
                                                    openImagePreview(
                                                        exampleImages.errorImageUrl
                                                    )
                                                "
                                            />
                                            <div v-else class="no-image">
                                                <svg
                                                    width="48"
                                                    height="48"
                                                    viewBox="0 0 24 24"
                                                    fill="none"
                                                >
                                                    <rect
                                                        x="3"
                                                        y="3"
                                                        width="18"
                                                        height="18"
                                                        rx="2"
                                                        ry="2"
                                                        stroke="currentColor"
                                                        stroke-width="2"
                                                    />
                                                    <circle
                                                        cx="8.5"
                                                        cy="8.5"
                                                        r="1.5"
                                                        stroke="currentColor"
                                                        stroke-width="2"
                                                    />
                                                    <path
                                                        d="M21 15L16 10L5 21"
                                                        stroke="currentColor"
                                                        stroke-width="2"
                                                    />
                                                </svg>
                                                <p>暂无示例图片</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 点评弹窗 -->
        <teleport to="body">
            <div
                v-if="showEvaluationModal"
                class="evaluation-modal-overlay"
                @click="closeEvaluationModal"
            >
                <div class="evaluation-modal" @click.stop>
                    <div class="modal-header">
                        <span class="modal-title">点评确认</span>
                        <img
                            src="@/assets/Hazard/11.png"
                            alt="关闭"
                            class="close-icon"
                            @click="closeEvaluationModal"
                        />
                    </div>

                    <div class="modal-body">
                        <!-- 问题1：场景是否匹配 -->
                        <div class="question-section">
                            <div class="question-title">1.场景是否匹配?</div>
                            <div class="answer-buttons">
                                <button
                                    :class="[
                                        'answer-btn',
                                        {
                                            active:
                                                evaluationData.sceneMatch ===
                                                true,
                                            disabled:
                                                selectedHistoryItem?.effect_evaluation >
                                                0,
                                        },
                                    ]"
                                    @click="
                                        selectedHistoryItem?.effect_evaluation >
                                        0
                                            ? null
                                            : (evaluationData.sceneMatch = true)
                                    "
                                >
                                    是
                                </button>
                                <button
                                    :class="[
                                        'answer-btn',
                                        {
                                            active:
                                                evaluationData.sceneMatch ===
                                                false,
                                            disabled:
                                                selectedHistoryItem?.effect_evaluation >
                                                0,
                                        },
                                    ]"
                                    @click="
                                        selectedHistoryItem?.effect_evaluation >
                                        0
                                            ? null
                                            : (evaluationData.sceneMatch = false)
                                    "
                                >
                                    否
                                </button>
                            </div>
                        </div>

                        <!-- 问题2：提示是否准确 -->
                        <div class="question-section">
                            <div class="question-title">2.提示是否准确?</div>
                            <div class="answer-buttons">
                                <button
                                    :class="[
                                        'answer-btn',
                                        {
                                            active:
                                                evaluationData.promptAccurate ===
                                                true,
                                            disabled:
                                                selectedHistoryItem?.effect_evaluation >
                                                0,
                                        },
                                    ]"
                                    @click="
                                        selectedHistoryItem?.effect_evaluation >
                                        0
                                            ? null
                                            : (evaluationData.promptAccurate = true)
                                    "
                                >
                                    是
                                </button>
                                <button
                                    :class="[
                                        'answer-btn',
                                        {
                                            active:
                                                evaluationData.promptAccurate ===
                                                false,
                                            disabled:
                                                selectedHistoryItem?.effect_evaluation >
                                                0,
                                        },
                                    ]"
                                    @click="
                                        selectedHistoryItem?.effect_evaluation >
                                        0
                                            ? null
                                            : (evaluationData.promptAccurate = false)
                                    "
                                >
                                    否
                                </button>
                            </div>
                        </div>

                        <!-- 问题3：效果评价 -->
                        <div class="question-section">
                            <div class="question-title">3.效果评价</div>
                            <div class="star-rating">
                                <span
                                    v-for="star in 5"
                                    :key="star"
                                    :class="[
                                        'star',
                                        {
                                            active:
                                                star <= evaluationData.rating,
                                            disabled:
                                                selectedHistoryItem?.effect_evaluation >
                                                0,
                                        },
                                    ]"
                                    @click="
                                        selectedHistoryItem?.effect_evaluation >
                                        0
                                            ? null
                                            : (evaluationData.rating = star)
                                    "
                                >
                                    ★
                                </span>
                            </div>
                        </div>

                        <!-- 问题4：用户意见 -->
                        <div
                            v-if="shouldShowRemarkSection"
                            class="question-section"
                        >
                            <div class="question-title">4.您的意见</div>
                            <div class="remark-input-container">
                                <textarea
                                    v-model="evaluationData.userRemark"
                                    :disabled="
                                        selectedHistoryItem?.effect_evaluation >
                                        0
                                    "
                                    placeholder="请输入您的意见和建议（最多200字）"
                                    class="remark-textarea"
                                    maxlength="200"
                                    @input="handleRemarkInput"
                                ></textarea>
                                <div class="character-count">
                                    <span
                                        :class="{
                                            'over-limit':
                                                evaluationData.userRemark
                                                    .length > 200,
                                        }"
                                    >
                                        {{
                                            evaluationData.userRemark.length
                                        }}/200
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div
                        class="modal-footer"
                        v-if="
                            !selectedHistoryItem?.effect_evaluation ||
                            selectedHistoryItem.effect_evaluation === 0
                        "
                    >
                        <button class="submit-btn" @click="submitEvaluation">
                            <img
                                src="@/assets/Hazard/13.png"
                                alt="提交反馈"
                                class="submit-icon"
                            />
                        </button>
                    </div>
                </div>
            </div>
        </teleport>

        <!-- 删除确认弹窗 -->
        <DeleteConfirmModal
            :visible="showDeleteModal"
            title="删除历史记录"
            :message="deleteConfirmMessage"
            @confirm="confirmDeleteHistory"
            @cancel="cancelDeleteHistory"
            @close="cancelDeleteHistory"
        />
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { Upload, View, DataAnalysis, Bell } from "@element-plus/icons-vue";
import Sidebar from "@/components/Sidebar.vue";
import DeleteConfirmModal from "@/components/DeleteConfirmModal.vue";
import { apis } from "@/request/apis.js";
import startIdentifyImg from "@/assets/Hazard/2.png";
import startIdentifyActiveImg from "@/assets/Hazard/3.png";

// 响应式数据
const messageText = ref("");
const selectedScenario = ref(""); // 自动识别出的场景
const uploadedImage = ref(null);
const uploadedImageUrl = ref(""); // 新增：存储上传后的图片URL
const fileInput = ref(null);
const currentView = ref("main"); // 当前视图：main-主界面，detail-详情页
const isTransitioning = ref(false); // 控制过渡动画状态
const selectedHistoryItem = ref(null); // 选中的历史记录项
const showExampleModal = ref(false); // 控制示例弹窗显示
const selectedHazard = ref(null); // 选中的隐患项目
const exampleImages = ref({}); // 存储示例图数据
const isLoadingExample = ref(false); // 控制示例图加载状态
// 移除了 lastClickTime，不再需要防抖
const imageLoadingStates = ref({
    correct: false, // 正确示例图加载状态
    error: false, // 错误示例图加载状态
}); // 控制每张图片的加载状态

// 删除相关状态
const showDeleteModal = ref(false); // 控制是否显示删除确认弹窗
const deleteTargetItem = ref(null); // 要删除的目标项
const isUploading = ref(false); // 新增：上传状态标识
const isDragOver = ref(false); // 新增：拖拽上传区域是否悬停
const isIdentifying = ref(false); // 新增：识别状态标识

// 隐患提示结果相关数据
const detectionResult = ref(null); // 存储识别结果
const annotatedImageUrl = ref(""); // 存储标注后的图片URL

// 图片预览相关数据
const showImagePreview = ref(false); // 控制图片预览弹窗显示
const previewImageUrl = ref(""); // 预览图片的URL
const showScanningEffect = ref(false); // 控制扫描效果显示
const isLoadingLabels = ref(false); // 控制标签加载状态
const isStreamingLabels = ref(false); // 控制标签流式输出状态
const streamingLabels = ref(""); // 流式输出的标签内容
const isStreamingAnalysis = ref(false); // 控制整个分析文本流式输出状态
const streamingAnalysis = ref(""); // 流式输出的完整分析文本
const showAnalysisPrompt = ref(false); // 控制分析提示显示
const visibleHazardCards = ref({}); // 控制每个隐患卡片的显示状态
const selectedKeyElement = ref(null); // 当前选中的关键要素
const imageContainerRef = ref(null); // 图片容器引用
const mainImageRef = ref(null); // 主图引用
const elementCardRef = ref(null); // 关键要素卡片引用
const elementOverlayStyle = ref(null); // 关键要素卡片定位样式

// 历史记录相关数据
const historyData = ref([]); // 存储历史记录数据
const historyTotal = ref(0); // 历史记录总数
const isLoadingDetail = ref(false); // 控制详情加载状态
const isImageLoading = ref(false); // 控制图片加载状态
const isLoadingHistory = ref(false); // 是否正在加载历史记录

// 点评弹窗相关数据
const showEvaluationModal = ref(false); // 控制点评弹窗显示
const evaluationData = ref({
    sceneMatch: null, // 场景是否匹配
    promptAccurate: null, // 提示是否准确
    rating: 0, // 效果评价评分 1-5
    userRemark: "", // 用户意见
});

// ===== 已删除：getUserId - 不再需要，改用token =====
// import { getUserId } from "@/utils/userManager.js";
// 删除确认消息
const deleteConfirmMessage = computed(() => {
    const title = deleteTargetItem.value?.item?.title || "";
    return `确定要删除历史记录"${title}"吗？删除后将无法恢复。`;
});

// 控制是否显示备注区域
const shouldShowRemarkSection = computed(() => {
    // 如果是已点评状态，只有当有备注内容时才显示
    if (selectedHistoryItem.value?.effect_evaluation > 0) {
        return (
            evaluationData.value.userRemark &&
            evaluationData.value.userRemark.trim() !== ""
        );
    }
    // 如果是未点评状态，始终显示（让用户可以输入）
    return true;
});

// 场景配置
const scenarios = {
    tunnel: { name: "隧道工程", color: "#3366E6" },
    simple_supported_bridge: { name: "桥梁工程", color: "#22B850" },
    gas_station: { name: "加油站", color: "#FF4D4F" },
    special_equipment: { name: "特种设备", color: "#0080FF" },
    operate_highway: { name: "运营高速公路", color: "#722ED1" },
};

const autoSceneOrder = [
    "tunnel",
    "simple_supported_bridge",
    "gas_station",
    "special_equipment",
    "operate_highway",
];

// 历史记录数据结构 - 初始为空数组，等待后端数据
// const historyData = ref([]);

// 标签类型配置，便于后端动态管理
const tagTypeConfig = {
    tunnel: {
        class: "tag-tunnel",
        background: "rgba(62, 123, 250, 0.1)",
        color: "#3366E6",
        text: "隧道",
    },
    simple_supported_bridge: {
        class: "tag-bridge",
        background: "rgba(34, 184, 80, 0.1)",
        color: "#22B850",
        text: "桥梁",
    },
    special_equipment: {
        class: "tag-equipment",
        background: "rgba(0, 128, 255, 0.1)",
        color: "#0080FF",
        text: "特种设备",
    },
    operate_highway: {
        class: "tag-highway",
        background: "rgba(114, 46, 209, 0.1)",
        color: "#722ED1",
        text: "运营高速公路",
    },
    gas_station: {
        class: "tag-gas-station",
        background: "rgba(255, 77, 79, 0.1)",
        color: "#FF4D4F",
        text: "加油站",
    },
};

// 根据标签类型获取样式类名
const getTagClass = (tagType) => {
    return tagTypeConfig[tagType]?.class || "tag-tunnel";
};

// 根据标签类型获取显示文字
const getTagText = (tagType) => {
    return tagTypeConfig[tagType]?.text || "隧道";
};

const getUniqueLabels = (labels) => {
    const seen = new Set();
    return labels.filter((label) => {
        if (!label || seen.has(label)) return false;
        seen.add(label);
        return true;
    });
};

const displayLabels = computed(() => {
    const labels =
        detectionResult.value?.display_labels || detectionResult.value?.labels;
    if (!labels) return [];

    const normalizedLabels = (Array.isArray(labels) ? labels : String(labels).split(/[，,、]/))
        .map((label) => normalizeLabel(String(label).trim()))
        .filter((label) => label);

    return getUniqueLabels(normalizedLabels);
});

const keyElements = computed(() => displayLabels.value);

const normalizeLabel = (label) => {
    if (!label) return "";
    const parts = String(label).split("_").filter((part) => part);
    if (parts.length <= 1) return String(label);
    return parts.slice(1).join("_");
};

const hazardMatchesElement = (hazard, element) => {
    if (!hazard || !element) return false;
    return hazard.includes(element) || element.includes(hazard);
};

const hazardsMap = computed(() => {
    const map = {};
    keyElements.value.forEach((element) => {
        map[element] = [];
    });
    const hazards = detectionResult.value?.third_scenes || [];
    hazards.forEach((hazard) => {
        let matched = false;
        for (const element of keyElements.value) {
            if (hazardMatchesElement(hazard, element)) {
                map[element].push(hazard);
                matched = true;
                break;
            }
        }
        if (!matched) {
            if (!map.__unmatched) map.__unmatched = [];
            map.__unmatched.push(hazard);
        }
    });
    return map;
});

const filteredHazards = computed(() => {
    if (!detectionResult.value) return [];
    if (!selectedKeyElement.value) {
        return detectionResult.value?.third_scenes || [];
    }
    const backendHazards =
        detectionResult.value?.element_hazards?.[selectedKeyElement.value];
    if (Array.isArray(backendHazards)) {
        return backendHazards;
    }
    return hazardsMap.value[selectedKeyElement.value] || [];
});

const selectedDetection = computed(() => {
    if (!selectedKeyElement.value) return null;
    const detections = detectionResult.value?.detections || [];
    return (
        detections.find((detection) => {
            const label = normalizeLabel(detection?.label || "");
            return (
                label === selectedKeyElement.value ||
                label.includes(selectedKeyElement.value) ||
                selectedKeyElement.value.includes(label)
            );
        }) || null
    );
});

const resetKeyElementState = () => {
    selectedKeyElement.value = null;
    elementOverlayStyle.value = null;
};

const toggleKeyElement = async (element) => {
    if (selectedKeyElement.value === element) {
        resetKeyElementState();
    } else {
        selectedKeyElement.value = element;
    }
    await nextTick();
    updateElementOverlayPosition();
};

const setVisibleHazardCards = (hazards = filteredHazards.value) => {
    const nextVisibleHazards = {};
    hazards.forEach((_, index) => {
        nextVisibleHazards[index] = true;
    });
    visibleHazardCards.value = nextVisibleHazards;
};

const getAutoSceneCandidates = () => {
    if (
        selectedScenario.value &&
        autoSceneOrder.includes(selectedScenario.value)
    ) {
        return [
            selectedScenario.value,
            ...autoSceneOrder.filter(
                (sceneKey) => sceneKey !== selectedScenario.value
            ),
        ];
    }
    return autoSceneOrder;
};

const detectSceneAutomatically = async (baseRequestData) => {
    let lastErrorMessage = "";

    for (const sceneKey of getAutoSceneCandidates()) {
        try {
            const response = await apis.hazardDetection({
                ...baseRequestData,
                scene_name: sceneKey,
            });
            const isSuccess =
                response.code === 200 || response.statusCode === 200;

            if (isSuccess) {
                return {
                    response,
                    sceneKey,
                };
            }

            lastErrorMessage =
                response.msg || response.message || lastErrorMessage;
        } catch (error) {
            lastErrorMessage =
                error?.msg || error?.message || lastErrorMessage;
        }
    }

    throw new Error(
        lastErrorMessage || "暂未识别到支持的场景，请尝试更换更清晰的图片"
    );
};

const updateElementOverlayPosition = async () => {
    if (
        !selectedKeyElement.value ||
        showScanningEffect.value ||
        currentView.value !== "detail"
    ) {
        elementOverlayStyle.value = null;
        return;
    }

    const container = imageContainerRef.value;
    const imageElement = mainImageRef.value;
    const detection = selectedDetection.value;

    if (
        !container ||
        !imageElement ||
        !detection ||
        !Array.isArray(detection.box) ||
        detection.box.length < 4 ||
        !imageElement.naturalWidth ||
        !imageElement.naturalHeight
    ) {
        elementOverlayStyle.value = null;
        return;
    }

    const containerWidth = container.clientWidth;
    const containerHeight = container.clientHeight;
    const naturalWidth = imageElement.naturalWidth;
    const naturalHeight = imageElement.naturalHeight;

    if (!containerWidth || !containerHeight) {
        elementOverlayStyle.value = null;
        return;
    }

    const scale = Math.min(
        containerWidth / naturalWidth,
        containerHeight / naturalHeight
    );
    const renderedWidth = naturalWidth * scale;
    const renderedHeight = naturalHeight * scale;
    const offsetX = (containerWidth - renderedWidth) / 2;
    const offsetY = (containerHeight - renderedHeight) / 2;

    const [x1, y1, x2, y2] = detection.box.map((value) => Number(value) || 0);

    const boxLeft = offsetX + x1 * scale;
    const boxTop = offsetY + y1 * scale;
    const boxRight = offsetX + x2 * scale;

    let cardLeft = boxRight + 12;
    let cardTop = boxTop;
    const cardWidth = elementCardRef.value?.offsetWidth || 260;
    const cardHeight = elementCardRef.value?.offsetHeight || 148;
    const safePadding = 12;

    if (cardLeft + cardWidth > containerWidth - safePadding) {
        cardLeft = Math.max(safePadding, boxLeft - cardWidth - 12);
    }
    if (cardTop + cardHeight > containerHeight - safePadding) {
        cardTop = Math.max(
            safePadding,
            containerHeight - cardHeight - safePadding
        );
    }

    elementOverlayStyle.value = {
        left: `${cardLeft}px`,
        top: `${Math.max(safePadding, cardTop)}px`,
    };

    await nextTick();
};

const handleMainImageLoad = async () => {
    await nextTick();
    updateElementOverlayPosition();
};

// 删除历史记录
const deleteHistoryItem = (historyItem, index) => {
    console.log("准备删除隐患提示历史记录:", historyItem);

    // 设置要删除的项目并显示确认弹窗
    deleteTargetItem.value = { item: historyItem, index: index };
    showDeleteModal.value = true;
};

// 确认删除历史记录
const confirmDeleteHistory = async () => {
    if (!deleteTargetItem.value) return;

    const { item: historyItem, index } = deleteTargetItem.value;

    try {
        // 调用删除接口
        const response = await apis.deleteRecognitionRecord({
            recognition_record_id: historyItem.id,
        });

        if (response.statusCode === 200) {
            // 删除成功，从列表中移除
            historyData.value.splice(index, 1);
            historyTotal.value = historyTotal.value - 1;

            // 如果删除的是当前激活的历史记录，需要清空界面并调用新建任务
            if (historyItem.isActive) {
                await createNewChat();
            }

            console.log("隐患提示历史记录删除成功");
            ElMessage.success("删除成功");
        } else {
            console.error("删除隐患提示历史记录失败:", response.msg);
            ElMessage.error(response.msg || "删除失败");
        }
    } catch (error) {
        console.error("删除隐患提示历史记录失败:", error);
        ElMessage.error("删除失败，请稍后重试");
    } finally {
        // 关闭弹窗并清除目标项
        showDeleteModal.value = false;
        deleteTargetItem.value = null;
    }
};

// 取消删除
const cancelDeleteHistory = () => {
    showDeleteModal.value = false;
    deleteTargetItem.value = null;
};

// 处理历史记录图片加载错误
const handleHistoryImageError = (event, item) => {
    console.log("历史记录图片加载失败:", item.originalImageUrl);
    // 避免无限循环，设置一个简单的占位符
    event.target.onerror = null; // 移除错误处理，防止再次触发
    event.target.src = "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHZpZXdCb3g9IjAgMCA0MCA0MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjQwIiBoZWlnaHQ9IjQwIiBmaWxsPSIjRjVGNUY1Ii8+CjxwYXRoIGQ9Ik0yMCAyNkMyMy4zMTM3IDI2IDI2IDIzLjMxMzcgMjYgMjBDMjYgMTYuNjg2MyAyMy4zMTM3IDE0IDIwIDE0QzE2LjY4NjMgMTQgMTQgMTYuNjg2MyAxNCAyMEMxNCAyMy4zMTM3IDE2LjY4NjMgMjYgMjAgMjZaIiBmaWxsPSIjQ0NDQ0NDIi8+Cjx0ZXh0IHg9IjIwIiB5PSIzMiIgZm9udC1mYW1pbHk9IkFyaWFsIiBmb250LXNpemU9IjgiIGZpbGw9IiM5OTk5OTkiIHRleHQtYW5jaG9yPSJtaWRkbGUiPuWbvueJhzwvdGV4dD4KPHN2Zz4K";
};

// 方法
const createNewChat = () => {
    console.log("createNewChat 被调用");

    // 重置所有状态
    currentView.value = "main";
    selectedScenario.value = "";
    uploadedImage.value = null;
    uploadedImageUrl.value = "";
    selectedHistoryItem.value = null;
    showExampleModal.value = false;
    selectedHazard.value = null;
    isUploading.value = false;
    isDragOver.value = false; // 重置拖拽状态
    isIdentifying.value = false; // 重置识别状态
    annotatedImageUrl.value = "";
    exampleImages.value = {}; // 清空示例图数据
    isLoadingExample.value = false; // 重置示例图加载状态
    imageLoadingStates.value = { correct: false, error: false }; // 重置图片加载状态
    // 移除了防抖时间重置
    isImageLoading.value = false; // 重置图片加载状态
    showScanningEffect.value = false; // 重置扫描效果状态
    isLoadingLabels.value = false; // 重置标签加载状态
    isStreamingLabels.value = false; // 重置标签流式输出状态
    streamingLabels.value = ""; // 清空流式输出内容
    isStreamingAnalysis.value = false; // 重置分析文本流式输出状态
    streamingAnalysis.value = ""; // 清空分析文本流式输出内容
    showAnalysisPrompt.value = false; // 重置分析提示状态
    detectionResult.value = null;
    resetKeyElementState();
    // 清空文件输入
    if (fileInput.value) {
        fileInput.value.value = "";
        console.log("文件输入已清空");
    } else {
        console.log("fileInput 引用为空，无法清空");
    }

    // 重置所有历史记录的active状态
    if (historyData.value.length > 0) {
        historyData.value.forEach((item) => {
            item.isActive = false;
        });
    }

    // ElMessage.success("已创建新的隐患提示任务");
    console.log("新任务创建完成");
};

// 点击历史记录
const handleHistoryItem = async (historyItem, event) => {
    try {
        console.log("handleHistoryItem 被调用，历史记录:", historyItem);

        // 如果当前记录已经是选中状态，则不执行任何操作
        if (historyItem.isActive) {
            console.log("当前记录已经是选中状态，忽略点击");
            return;
        }

        selectedHistoryItem.value = historyItem;
        currentView.value = "detail";
        isDragOver.value = false; // 重置拖拽状态
        isLoadingDetail.value = true; // 开始加载详情
        isImageLoading.value = true; // 开始加载图片

        // 调用详情接口获取完整数据
        console.log("开始获取记录详情，ID:", historyItem.id);
        const detailResponse = await apis.getRecognitionRecordDetail({
            recognition_record_id: historyItem.id,
        });

        if (detailResponse.statusCode === 200 || detailResponse.code === 200) {
            const detailData = detailResponse.data;
            console.log("获取详情成功:", detailData);

            // 设置识别结果数据
            detectionResult.value = {
                scene_name:
                    detailData.tag_type ||
                    getTagTypeFromLabels(detailData.labels),
                labels: detailData.labels,
                display_labels: detailData.display_labels || [],
                total_detections: detailData.labels
                    ? Array.isArray(detailData.labels)
                        ? detailData.labels.length
                        : 0
                    : 0,
                third_scenes: detailData.third_scenes || [],
                element_hazards: detailData.element_hazards || {},
                detections: detailData.detections || [],
            };
            selectedScenario.value = detectionResult.value.scene_name || "";
            resetKeyElementState();

            // 设置图片URL并检测加载完成
            const newImageUrl =
                detailData.recognition_image_url ||
                detailData.original_image_url;
            annotatedImageUrl.value = newImageUrl;

            // 检测图片是否加载完成
            if (newImageUrl) {
                await waitForImageLoad(newImageUrl);
            }

            // 更新历史记录中的标签类型（优先使用后端返回的tag_type，如果没有则根据labels推断）
            const tagType =
                detailData.tag_type || getTagTypeFromLabels(detailData.labels);
            historyItem.tagType = tagType;

            // 显示所有隐患卡片（历史记录不需要动画效果）
            setVisibleHazardCards(
                detectionResult.value?.third_scenes || []
            );
        } else {
            console.error("获取详情失败:", detailResponse.message);
            ElMessage.error("获取记录详情失败");

            // 使用历史记录中的基础数据作为后备
            detectionResult.value = {
                scene_name: historyItem.tagType || "simple_supported_bridge",
                labels: historyItem.labels,
                display_labels: [],
                total_detections: 0,
                third_scenes: [],
                element_hazards: {},
                detections: [],
            };
            const fallbackImageUrl =
                historyItem.recognitionImageUrl || historyItem.originalImageUrl;
            annotatedImageUrl.value = fallbackImageUrl;

            // 检测后备图片是否加载完成
            if (fallbackImageUrl) {
                await waitForImageLoad(fallbackImageUrl);
            }

            // 显示所有隐患卡片
            setVisibleHazardCards([]);
        }

        // 更新数据层的active状态
        historyData.value.forEach((item) => {
            item.isActive = item.id === historyItem.id;
        });
        console.log("历史记录状态已更新");
    } catch (error) {
        console.error("处理历史记录失败:", error);
        ElMessage.error("获取记录详情失败");
        isDragOver.value = false; // 重置拖拽状态
    } finally {
        isLoadingDetail.value = false; // 结束加载详情
        isImageLoading.value = false; // 结束加载图片
    }
};

// 触发文件上传
const triggerFileUpload = () => {
    try {
        console.log("triggerFileUpload 被调用");
        console.log("fileInput.value:", fileInput.value);
        isDragOver.value = false; // 重置拖拽状态
        if (fileInput.value) {
            fileInput.value.click();
            console.log("已触发文件选择器");
        } else {
            console.error("fileInput 引用为空");
        }
    } catch (error) {
        console.error("触发文件上传失败:", error);
        isDragOver.value = false; // 重置拖拽状态
    }
};

// 新增：上传文件到服务器
const uploadFileToServer = async (file) => {
    try {
        console.log("uploadFileToServer 被调用，文件:", file);
        isUploading.value = true;

        // 创建FormData对象
        const formData = new FormData();
        formData.append("image", file);
        console.log("FormData 已创建:", formData);

        // 调用后端上传接口
        console.log("开始调用后端API...");
        const response = await apis.uploadImage(formData);
        console.log("后端API响应:", response);

        if (response.statusCode === 200) {
            uploadedImageUrl.value = response.fileUrl || response.fileURL;
            console.log("上传成功:", uploadedImageUrl.value);
            ElMessage.success("图片上传成功！");
        } else {
            throw new Error(response.message || "上传失败");
        }
    } catch (error) {
        console.error("上传失败:", error);
        ElMessage.error("图片上传失败: " + (error.message || "未知错误"));
        uploadedImage.value = null;
        uploadedImageUrl.value = "";
        isDragOver.value = false; // 重置拖拽状态
    } finally {
        isUploading.value = false;
        isDragOver.value = false; // 重置拖拽状态
    }
};

// 开始识别
const startIdentification = async () => {
    try {
        console.log("startIdentification 被调用");

        // 防抖检查：如果正在识别中，直接返回
        if (isIdentifying.value) {
            console.log("识别正在进行中，忽略重复点击");
            ElMessage.warning("识别正在进行中，请勿重复点击");
            return;
        }

        if (!uploadedImageUrl.value) {
            // 使用 uploadedImageUrl.value 判断
            console.log("未上传图片");
            ElMessage.warning("请先上传图片");
            isDragOver.value = false; // 重置拖拽状态
            return;
        }

        // 检查用户最新识别记录是否已点评
        try {
            console.log("检查最新识别记录是否已点评");
            const latestRecordResponse = await apis.getLatestRecognitionRecord({
                // ===== 已删除：user_id - 后端从token解析 =====
            });

            if (
                latestRecordResponse.statusCode === 200 &&
                latestRecordResponse.data
            ) {
                const latestRecord = latestRecordResponse.data;
                console.log("最新识别记录:", latestRecord);

                // 如果最新记录存在且未点评，提示用户
                if (
                    latestRecord.effect_evaluation === 0 ||
                    !latestRecord.effect_evaluation
                ) {
                    ElMessage.warning(
                        "请先对上一次识别结果进行点评，再进行新的识别"
                    );
                    isDragOver.value = false; // 重置拖拽状态
                    return;
                }
            }
        } catch (error) {
            console.error("检查最新识别记录失败:", error);
            // 如果检查失败，继续执行识别流程
        }

        console.log("开始自动识别图片场景:", uploadedImageUrl.value);

        // 开始识别状态
        isIdentifying.value = true;
        resetKeyElementState();

        // 调用后端API进行隐患提示
        // ElMessage.success("开始进行隐患提示，请稍候...");

        // 模拟用户信息（暂时不从后端获取）
        const account = "";
        const username = "蜀道用户";

        // 获取当日日期，格式：2025/10/23
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, "0");
        const day = String(today.getDate()).padStart(2, "0");
        const currentDate = `${year}/${month}/${day}`;

        // 截取手机号后四位
        const accountLastFour =
            account.length >= 4 ? account.slice(-4) : account;

        const requestData = {
            // ===== 已删除：user_id - 后端从token解析 =====
            image: uploadedImageUrl.value,
            account: accountLastFour,
            username: username,
            date: currentDate,
        };

        console.log("发送自动场景识别请求:", requestData);
        const { response, sceneKey } = await detectSceneAutomatically(
            requestData
        );
        console.log("隐患提示响应:", response);

        // 检查响应结构，兼容不同的字段名
        const isSuccess = response.code === 200 || response.statusCode === 200;

        if (isSuccess) {
            ElMessage.success("隐患提示完成！");

            // 保存识别结果
            detectionResult.value = {
                ...response.data,
                scene_name: response.data.scene_name || sceneKey,
                display_labels: response.data.display_labels || [],
                element_hazards: response.data.element_hazards || {},
            };
            selectedScenario.value = detectionResult.value.scene_name || sceneKey;

            // 处理标注后的图片
            if (response.data.annotated_image) {
                annotatedImageUrl.value = `${response.data.annotated_image}`;
            }

            // 开始过渡动画
            isTransitioning.value = true;

            // 等待右侧卡片滑出和左侧卡片拉伸动画完成（1秒）
            setTimeout(() => {
                // 跳转到详情页
                currentView.value = "detail";
                isTransitioning.value = false;

                // 开始扫描效果
                showScanningEffect.value = true;
                showAnalysisPrompt.value = true; // 显示分析提示
            }, 1000);

            // 延迟4秒后显示识别结果（1秒过渡 + 3秒扫描）
            setTimeout(() => {
                showScanningEffect.value = false;
                showAnalysisPrompt.value = false; // 隐藏分析提示
                // 开始整个分析文本流式输出效果
                startAnalysisStreaming();
            }, 4000);

            // 刷新历史记录
            await getHistoryRecords();

            // 自动选中最新创建的历史记录
            if (historyData.value.length > 0) {
                const latestRecord = historyData.value[0]; // 假设最新的记录在数组第一位
                latestRecord.tagType =
                    detectionResult.value.scene_name || latestRecord.tagType;
                latestRecord.detections =
                    detectionResult.value.detections || [];
                selectedHistoryItem.value = latestRecord;

                // 更新所有记录的active状态
                historyData.value.forEach((item) => {
                    item.isActive = item.id === latestRecord.id;
                });

                console.log("自动选中最新记录:", latestRecord);
            }

            console.log("识别结果:", response.data);
            console.log("标注图片URL:", annotatedImageUrl.value);
        } else {
            ElMessage.error(response.msg || "隐患提示失败");
        }
    } catch (error) {
        console.error("开始识别失败:", error);
        ElMessage.error("隐患提示失败: " + (error.msg || "未知错误"));
        isDragOver.value = false; // 重置拖拽状态
    } finally {
        // 清除识别状态
        isIdentifying.value = false;
    }
};

// 打开示例弹窗
const openExampleModal = async (hazardInfo) => {
    try {
        console.log("openExampleModal 被调用，隐患信息:", hazardInfo);

        // 如果正在加载中，直接返回避免重复请求
        if (isLoadingExample.value) {
            console.log("正在加载示例图，忽略重复点击");
            return;
        }

        selectedHazard.value = hazardInfo;
        isDragOver.value = false; // 重置拖拽状态

        // 开始加载示例图
        isLoadingExample.value = true;

        // 调用API获取示例图
        const response = await apis.getThirdSceneExampleImage({
            third_scene_name: hazardInfo.description,
        });

        console.log("获取示例图响应:", response);

        if (response.statusCode === 200) {
            const exampleData = response.data;

            // 检查是否有示例图数据
            if (
                exampleData &&
                (exampleData.correct_example_image ||
                    exampleData.wrong_example_image)
            ) {
                exampleImages.value = {
                    correctImageUrl: exampleData.correct_example_image || "",
                    errorImageUrl: exampleData.wrong_example_image || "",
                };

                // 重置图片加载状态
                imageLoadingStates.value = {
                    correct: false,
                    error: false,
                };

                showExampleModal.value = true;
                console.log("示例弹窗已打开，示例图数据:", exampleImages.value);
                console.log("API返回的原始数据:", exampleData);
                console.log(
                    "正确示例图URL:",
                    exampleData.correct_example_image
                );
                console.log("错误示例图URL:", exampleData.wrong_example_image);
            } else {
                // 没有示例图数据，显示提示
                ElMessage.warning("暂无示例图");
                console.log("没有找到示例图数据");
            }
        } else {
            ElMessage.error("获取示例图失败: " + (response.msg || "未知错误"));
            console.error("获取示例图失败:", response.msg);
        }
    } catch (error) {
        console.error("打开示例弹窗失败:", error);
        ElMessage.error("获取示例图失败，请稍后重试");
        isDragOver.value = false; // 重置拖拽状态
    } finally {
        isLoadingExample.value = false;
    }
};

// 关闭示例弹窗
const closeExampleModal = () => {
    try {
        console.log("closeExampleModal 被调用");
        showExampleModal.value = false;
        // 清空示例图数据
        exampleImages.value = {};
        selectedHazard.value = null;
        isLoadingExample.value = false;
        imageLoadingStates.value = { correct: false, error: false };
        console.log("示例弹窗已关闭");
    } catch (error) {
        console.error("关闭示例弹窗失败:", error);
    }
};

// 处理图片加载错误
const handleImageError = (event, type) => {
    console.log(`图片加载失败 (${type}):`, event.target.src);
    // 清空对应的图片URL，这样会显示"暂无示例图"
    if (type === "correct") {
        exampleImages.value.correctImageUrl = "";
        imageLoadingStates.value.correct = false;
    } else if (type === "error") {
        exampleImages.value.errorImageUrl = "";
        imageLoadingStates.value.error = false;
    }
};

// 处理图片加载完成，检测图片方向
const handleImageLoad = (event, type) => {
    const img = event.target;
    const aspectRatio = img.naturalWidth / img.naturalHeight;

    // 根据宽高比判断图片方向
    if (aspectRatio > 1) {
        // 横图
        img.setAttribute("data-orientation", "landscape");
        console.log(
            `图片加载完成 (${type}): 横图, 宽高比: ${aspectRatio.toFixed(2)}`
        );
    } else {
        // 竖图
        img.setAttribute("data-orientation", "portrait");
        console.log(
            `图片加载完成 (${type}): 竖图, 宽高比: ${aspectRatio.toFixed(2)}`
        );
    }

    // 设置对应图片的加载状态为完成
    if (type === "correct") {
        imageLoadingStates.value.correct = false;
    } else if (type === "error") {
        imageLoadingStates.value.error = false;
    }

    console.log(`图片加载完成 (${type}):`, img.src);
};

// 打开图片预览（支持自定义URL）
const openImagePreview = (imageUrl = null) => {
    try {
        console.log("openImagePreview 被调用");
        if (imageUrl) {
            // 如果提供了URL，使用它作为预览图片
            previewImageUrl.value = imageUrl;
        } else {
            // 否则使用默认的标注图片
            previewImageUrl.value = annotatedImageUrl.value;
        }
        showImagePreview.value = true;
        console.log("图片预览已打开，URL:", previewImageUrl.value);
    } catch (error) {
        console.error("打开图片预览失败:", error);
    }
};

// 关闭图片预览
const closeImagePreview = () => {
    try {
        console.log("closeImagePreview 被调用");
        showImagePreview.value = false;
        previewImageUrl.value = "";
        console.log("图片预览已关闭");
    } catch (error) {
        console.error("关闭图片预览失败:", error);
    }
};

// 处理主图片加载错误
const handleMainImageError = (event) => {
    try {
        console.log("主图片加载失败");
        // 可以在这里添加其他错误处理逻辑
    } catch (error) {
        console.error("处理主图片错误失败:", error);
    }
};

// 开始整个分析文本流式输出效果
const startAnalysisStreaming = () => {
    try {
        console.log("开始整个分析文本流式输出效果");

        // 重置状态
        isStreamingAnalysis.value = false;
        streamingAnalysis.value = "";
        resetKeyElementState();
        visibleHazardCards.value = {}; // 重置隐患卡片显示状态

        // 立即开始流式输出，不需要延迟
        // 构建完整的分析文本（带HTML标签）
        const sceneName = detectionResult.value?.scene_name;
        const sceneText = sceneName ? scenarios[sceneName]?.name : "未知场景";
        const labelsArray = displayLabels.value;

        // 构建带HTML的完整文本
        const labelsTags = labelsArray
            .map((label) => `<span class="label-tag">${label}</span>`)
            .join("");
        const fullAnalysisText = `我识别到这是一个<span class="scene-tag">${sceneText}</span>场景，检测到的关键要素为${labelsTags}`;

        // 将HTML文本分解为可见字符数组（处理标签）
        const segments = [];
        let tempText = fullAnalysisText;
        let inTag = false;
        let currentSegment = "";

        for (let i = 0; i < tempText.length; i++) {
            const char = tempText[i];

            if (char === "<") {
                // 如果之前有文本，先保存
                if (currentSegment && !inTag) {
                    segments.push(currentSegment);
                    currentSegment = "";
                }
                inTag = true;
                currentSegment += char;
            } else if (char === ">") {
                currentSegment += char;
                // 标签结束，保存整个标签
                segments.push(currentSegment);
                currentSegment = "";
                inTag = false;
            } else if (inTag) {
                // 在标签内，继续累积
                currentSegment += char;
            } else {
                // 在标签外，每个字符单独作为一个segment
                segments.push(char);
            }
        }

        if (currentSegment) {
            segments.push(currentSegment);
        }

        // 开始流式输出
        isStreamingAnalysis.value = true;
        let currentIndex = 0;
        const streamInterval = setInterval(() => {
            if (currentIndex < segments.length) {
                streamingAnalysis.value += segments[currentIndex];
                currentIndex++;
            } else {
                // 输出完成
                clearInterval(streamInterval);
                isStreamingAnalysis.value = false;
                console.log("分析文本流式输出完成");

                // 文本流式输出完成后，延迟500ms开始显示隐患卡片
                setTimeout(() => {
                    showHazardCardsSequentially();
                }, 500);
            }
        }, 30); // 每30ms输出一个segment
    } catch (error) {
        console.error("开始分析文本流式输出失败:", error);
        // 出错时直接显示完整内容
        isStreamingAnalysis.value = false;
    }
};

// 逐个显示隐患卡片
const showHazardCardsSequentially = () => {
    try {
        console.log("开始逐个显示隐患卡片");
        const hazards = filteredHazards.value || [];
        visibleHazardCards.value = {};

        // 在第一个卡片显示之前，先滚动到隐患section
        setTimeout(() => {
            const hazardsSection = document.querySelector(".hazards-section");
            if (hazardsSection) {
                hazardsSection.scrollIntoView({
                    behavior: "smooth",
                    block: "start",
                });
            }
        }, 100);

        hazards.forEach((hazard, index) => {
            setTimeout(() => {
                visibleHazardCards.value[index] = true;
                console.log(`显示第${index + 1}个隐患卡片`);

                // 每显示一个卡片，平滑滚动确保可见
                setTimeout(() => {
                    const cards = document.querySelectorAll(".hazard-card");
                    if (cards[index]) {
                        cards[index].scrollIntoView({
                            behavior: "smooth",
                            block: "nearest",
                            inline: "nearest",
                        });
                    }
                }, 50);
            }, index * 150); // 每个卡片延迟150ms显示
        });
    } catch (error) {
        console.error("显示隐患卡片失败:", error);
    }
};

// 新增：清除上传的图片
const clearUploadedImage = () => {
    try {
        console.log("clearUploadedImage 被调用");
        uploadedImage.value = null;
        uploadedImageUrl.value = "";
        annotatedImageUrl.value = "";
        detectionResult.value = null;
        resetKeyElementState();
        isDragOver.value = false; // 重置拖拽状态
        if (fileInput.value) {
            fileInput.value.value = ""; // 清空input的value
            console.log("文件输入已清空");
        } else {
            console.log("fileInput 引用为空，无法清空");
        }
        console.log("上传图片已清除");
    } catch (error) {
        console.error("清除上传图片失败:", error);
    }
};

// 新增：重新选择图片
const reselectImage = () => {
    try {
        console.log("reselectImage 被调用");
        clearUploadedImage();
        isDragOver.value = false; // 重置拖拽状态
        triggerFileUpload();
        console.log("重新选择图片完成");
    } catch (error) {
        console.error("重新选择图片失败:", error);
    }
};

// 新增：处理拖拽上传
const handleDrop = (event) => {
    try {
        console.log("handleDrop 被调用");
        event.preventDefault();
        isDragOver.value = false;
        const file = event.dataTransfer.files[0];
        console.log("拖拽的文件:", file);
        if (file) {
            processFile(file); // 使用通用的文件处理函数
        } else {
            console.log("没有拖拽文件");
            isDragOver.value = false; // 如果没有文件，确保重置拖拽状态
        }
    } catch (error) {
        console.error("拖拽处理失败:", error);
        isDragOver.value = false; // 重置拖拽状态
    }
};

// 新增：处理拖拽进入
const handleDragOver = (event) => {
    try {
        console.log("handleDragOver 被调用");
        event.preventDefault();
        isDragOver.value = true;
        console.log("拖拽进入状态已设置");
    } catch (error) {
        console.error("拖拽进入处理失败:", error);
        isDragOver.value = false; // 重置拖拽状态
    }
};

// 新增：处理拖拽离开
const handleDragLeave = (event) => {
    try {
        console.log("handleDragLeave 被调用");
        event.preventDefault();
        isDragOver.value = false;
        console.log("拖拽离开状态已设置");
    } catch (error) {
        console.error("拖拽离开处理失败:", error);
        isDragOver.value = false; // 重置拖拽状态
    }
};

// 新增：处理图片方向，确保保持原始方向
const processImageOrientation = (file) => {
    return new Promise((resolve) => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        const img = new Image();

        img.onload = () => {
            // 设置画布尺寸为图片的原始尺寸
            canvas.width = img.naturalWidth;
            canvas.height = img.naturalHeight;

            // 绘制图片，保持原始方向
            ctx.drawImage(img, 0, 0);

            // 将画布转换为Blob
            canvas.toBlob((blob) => {
                // 创建一个新的File对象，保持原始文件名和类型
                const processedFile = new File([blob], file.name, {
                    type: file.type,
                    lastModified: file.lastModified,
                });
                resolve(processedFile);
            }, file.type);
        };

        img.src = URL.createObjectURL(file);
    });
};

// 新增：通用的文件处理函数
const processFile = async (file) => {
    try {
        console.log("processFile 被调用，文件:", file);
        // 检查文件大小（5MB限制）
        if (file.size > 5 * 1024 * 1024) {
            console.log("文件大小超过限制:", file.size);
            ElMessage.error("文件大小不能超过5MB");
            isDragOver.value = false; // 重置拖拽状态
            return;
        }

        // 检查文件格式
        const allowedTypes = ["image/jpeg", "image/jpg", "image/png"];
        console.log("文件类型:", file.type);
        if (!allowedTypes.includes(file.type)) {
            console.log("不支持的文件类型:", file.type);
            ElMessage.error("只支持JPG、PNG格式的图片");
            isDragOver.value = false; // 重置拖拽状态
            return;
        }

        // 处理图片方向，确保保持原始方向
        const processedFile = await processImageOrientation(file);
        uploadedImage.value = processedFile;
        console.log("选择文件:", processedFile.name);

        // 自动上传文件到后端
        console.log("开始上传文件到服务器");
        await uploadFileToServer(processedFile);
    } catch (error) {
        console.error("处理文件失败:", error);
        isDragOver.value = false; // 重置拖拽状态
    }
};

// 处理文件上传
const handleFileUpload = async (event) => {
    try {
        console.log("handleFileUpload 被调用", event);
        const file = event.target.files[0];
        console.log("选择的文件:", file);
        if (file) {
            await processFile(file);
        } else {
            console.log("没有选择文件");
        }
    } catch (error) {
        console.error("文件上传处理失败:", error);
        isDragOver.value = false; // 重置拖拽状态
    }
};

// 获取历史记录
const getHistoryRecords = async () => {
    try {
        console.log("📋 开始获取隐患识别历史记录...");
        isLoadingHistory.value = true;
        const startTime = performance.now();

        const response = await apis.getHazardHistory({
            // ===== 已删除：user_id - 后端从token解析 =====
        });

        const endTime = performance.now();
        console.log(
            `📋 隐患识别历史记录API调用耗时: ${(endTime - startTime).toFixed(
                2
            )}ms`
        );
        console.log("📋 历史记录响应:", response);

        if (response.statusCode === 200 || response.code === 200) {
            // 设置历史记录总数
            historyTotal.value = response.total || 0;

            // 处理历史记录数据（简化版本）
            const records = response.data || [];
            historyData.value = records.map((record, index) => ({
                id: record.id || index,
                title: record.title || "隐患提示记录",
                description: record.description || "暂无描述",
                time: formatTime(record.created_at),
                tagType: record.tag_type, // 默认标签，详情加载时会更新
                isActive: false,
                originalImageUrl: record.original_image_url,
                recognitionImageUrl: record.recognition_image_url,
                labels: record.labels || "",
                third_scenes: [], // 历史记录中不包含详细数据
                effect_evaluation: record.effect_evaluation || 0, // 添加点评状态参数
            }));
            console.log(
                `✅ 隐患识别历史记录处理完成: ${historyData.value.length}条记录，总数: ${historyTotal.value}`
            );
        } else {
            console.error("❌ 获取历史记录失败:", response.message);
        }
    } catch (error) {
        console.error("❌ 获取历史记录失败:", error);
    } finally {
        isLoadingHistory.value = false;
    }
};

// 格式化时间
const formatTime = (timestamp) => {
    if (!timestamp) return "未知时间";

    console.log(
        "formatTime 被调用，原始时间戳:",
        timestamp,
        "类型:",
        typeof timestamp
    );

    // 处理时间戳
    let date;
    if (typeof timestamp === "string") {
        // 如果是ISO字符串格式，直接创建Date对象
        date = new Date(timestamp);
    } else {
        // 如果是数字时间戳
        let timestampMs = timestamp;
        if (timestamp.toString().length === 10) {
            timestampMs = timestamp * 1000;
        } else if (timestamp.toString().length === 11) {
            timestampMs = timestamp * 1000;
        } else if (timestamp.toString().length === 13) {
            // 13位时间戳，直接使用
        } else {
            timestampMs = timestamp * 1000;
        }
        date = new Date(timestampMs);
    }

    console.log("转换后的日期:", date);

    const now = new Date();

    // 获取今天的开始时间（0点0分0秒）
    const todayStart = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate()
    );
    // 获取昨天的开始时间
    const yesterdayStart = new Date(todayStart.getTime() - 24 * 60 * 60 * 1000);

    console.log("今天开始时间:", todayStart);
    console.log("昨天开始时间:", yesterdayStart);
    console.log("记录时间:", date);

    // 今天的对话（日期相同）
    if (date >= todayStart) {
        const result = date.toLocaleTimeString("zh-CN", {
            hour: "2-digit",
            minute: "2-digit",
        });
        console.log("今天对话，返回:", result);
        return result;
    }

    // 昨天的对话（日期是昨天）
    if (date >= yesterdayStart && date < todayStart) {
        const result =
            "昨天 " +
            date.toLocaleTimeString("zh-CN", {
                hour: "2-digit",
                minute: "2-digit",
            });
        console.log("昨天对话，返回:", result);
        return result;
    }

    // 更早的对话：显示为 "8月30日 15:30" 格式
    const month = date.getMonth() + 1; // getMonth() 返回 0-11
    const day = date.getDate();
    const time = date.toLocaleTimeString("zh-CN", {
        hour: "2-digit",
        minute: "2-digit",
    });

    const result = `${month}月${day}日 ${time}`;
    console.log("更早对话，返回:", result);
    return result;
};

// 根据标签获取标签类型
const getTagTypeFromLabels = (labels) => {
    if (!labels) return "gas_station";

    let labelStr = "";

    // 处理数组格式的labels
    if (Array.isArray(labels)) {
        labelStr = labels.join(" ").toLowerCase();
    } else {
        // 处理字符串格式的labels
        labelStr = String(labels).toLowerCase();
    }

    if (labelStr.includes("隧道")) return "tunnel";
    if (labelStr.includes("桥梁")) return "simple_supported_bridge";
    if (labelStr.includes("加油站")) return "gas_station";
    if (labelStr.includes("设备")) return "special_equipment";
    if (labelStr.includes("高速")) return "operate_highway";

    return "simple_supported_bridge"; // 默认返回桥梁工程
};

// 获取当前时间
const getCurrentTime = () => {
    const now = new Date();
    const month = now.getMonth() + 1;
    const day = now.getDate();
    const hours = now.getHours().toString().padStart(2, "0");
    const minutes = now.getMinutes().toString().padStart(2, "0");
    return `${month}月${day}日 ${hours}:${minutes}`;
};

// 等待图片加载完成
const waitForImageLoad = (imageUrl) => {
    return new Promise((resolve, reject) => {
        if (!imageUrl) {
            resolve();
            return;
        }

        const img = new Image();
        const timeout = setTimeout(() => {
            console.warn("图片加载超时:", imageUrl);
            resolve(); // 超时也resolve，避免阻塞
        }, 10000); // 10秒超时

        img.onload = () => {
            clearTimeout(timeout);
            console.log("图片加载完成:", imageUrl);
            resolve();
        };

        img.onerror = () => {
            clearTimeout(timeout);
            console.error("图片加载失败:", imageUrl);
            resolve(); // 即使失败也resolve，避免阻塞
        };

        img.src = imageUrl;
    });
};

// 打开点评弹窗
const openEvaluationModal = () => {
    try {
        console.log("打开点评弹窗");
        showEvaluationModal.value = true;

        // 如果是已点评状态，回显数据
        if (selectedHistoryItem.value?.effect_evaluation > 0) {
            // 从后端获取详细的点评数据
            loadEvaluationData();
        } else {
            // 重置评价数据
            evaluationData.value = {
                sceneMatch: null,
                promptAccurate: null,
                rating: 0,
                userRemark: "",
            };
        }
    } catch (error) {
        console.error("打开点评弹窗失败:", error);
    }
};

// 加载点评数据
const loadEvaluationData = async () => {
    try {
        console.log("加载点评数据");
        // 从详情接口获取完整的点评数据
        const detailResponse = await apis.getRecognitionRecordDetail({
            recognition_record_id: selectedHistoryItem.value.id,
        });

        if (detailResponse.statusCode === 200 || detailResponse.code === 200) {
            const detailData = detailResponse.data;
            // 回显数据，将整数转换为布尔值
            evaluationData.value = {
                sceneMatch: detailData.scene_match === 1,
                promptAccurate: detailData.tip_accuracy === 1,
                rating: detailData.effect_evaluation || 0,
                userRemark: detailData.user_remark || "",
            };
            console.log("点评数据回显成功:", evaluationData.value);
        } else {
            console.error("获取点评数据失败:", detailResponse.message);
            // 如果获取失败，使用默认值
            evaluationData.value = {
                sceneMatch: null,
                promptAccurate: null,
                rating: selectedHistoryItem.value.effect_evaluation || 0,
                userRemark: "",
            };
        }
    } catch (error) {
        console.error("加载点评数据失败:", error);
        // 如果获取失败，使用默认值
        evaluationData.value = {
            sceneMatch: null,
            promptAccurate: null,
            rating: selectedHistoryItem.value.effect_evaluation || 0,
            userRemark: "",
        };
    }
};

// 关闭点评弹窗
const closeEvaluationModal = () => {
    try {
        console.log("关闭点评弹窗");
        showEvaluationModal.value = false;
    } catch (error) {
        console.error("关闭点评弹窗失败:", error);
    }
};

// 处理用户意见输入
const handleRemarkInput = (event) => {
    const value = event.target.value;
    // 限制输入长度
    if (value.length > 200) {
        evaluationData.value.userRemark = value.substring(0, 200);
    } else {
        evaluationData.value.userRemark = value;
    }
};

// 提交评价
const submitEvaluation = async () => {
    try {
        console.log("提交评价:", evaluationData.value);

        // 验证是否所有问题都已回答
        if (
            evaluationData.value.sceneMatch === null ||
            evaluationData.value.promptAccurate === null ||
            evaluationData.value.rating === 0
        ) {
            ElMessage.warning("请完成所有评价项目");
            return;
        }

        // 调用后端API提交评价
        const response = await apis.submitEvaluation({
            id: selectedHistoryItem.value?.id,
            scene_match: evaluationData.value.sceneMatch ? 1 : 0,
            tip_accuracy: evaluationData.value.promptAccurate ? 1 : 0,
            effect_evaluation: evaluationData.value.rating,
            user_remark: evaluationData.value.userRemark,
        });

        if (response.statusCode === 200 || response.code === 200) {
            ElMessage.success("评价提交成功");

            // 更新当前历史记录的点评状态
            if (selectedHistoryItem.value) {
                selectedHistoryItem.value.effect_evaluation =
                    evaluationData.value.rating;
            }

            // 更新历史记录列表中的对应项
            const historyItem = historyData.value.find(
                (item) => item.id === selectedHistoryItem.value?.id
            );
            if (historyItem) {
                historyItem.effect_evaluation = evaluationData.value.rating;
            }

            // 关闭弹窗
            closeEvaluationModal();
        } else {
            ElMessage.error("评价提交失败: " + (response.msg || "未知错误"));
        }
    } catch (error) {
        console.error("提交评价失败:", error);
        ElMessage.error("评价提交失败，请稍后重试");
    }
};

watch(
    filteredHazards,
    (hazards) => {
        if (
            showScanningEffect.value ||
            showAnalysisPrompt.value ||
            isStreamingAnalysis.value
        ) {
            return;
        }
        setVisibleHazardCards(hazards);
    },
    { deep: false }
);

watch(
    [
        selectedKeyElement,
        currentView,
        showScanningEffect,
        () => detectionResult.value?.detections,
    ],
    async () => {
        if (
            !selectedKeyElement.value ||
            currentView.value !== "detail" ||
            showScanningEffect.value
        ) {
            elementOverlayStyle.value = null;
            return;
        }
        await nextTick();
        updateElementOverlayPosition();
    }
);

const handleWindowResize = () => {
    updateElementOverlayPosition();
};

onMounted(() => {
    getHistoryRecords();
    window.addEventListener("resize", handleWindowResize);
});

onBeforeUnmount(() => {
    window.removeEventListener("resize", handleWindowResize);
});
</script>

<style lang="less" scoped>
// 删除图标样式
.delete-icon {
    width: 16px;
    height: 16px;
}

.chat-container {
    display: flex;
    height: 100vh;
    font-family: "Alibaba PuHuiTi 3.0", sans-serif;
}

/* 中间历史记录栏 */
.history-sidebar {
    width: 280px;
    background: #e8f0ff;
    display: flex;
    flex-direction: column;
}

/* 中间历史记录栏样式 */
.history-sidebar {
    padding: 24px 16px 0 16px;
    .history-header {
        background: transparent;

        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
        }

        .new-chat-btn {
            width: 248px;
            height: 40px;
            cursor: pointer;
            transition: opacity 0.3s ease;
            object-fit: contain;
            display: block;
            margin-top: 16px;
            margin-bottom: 16px;

            &:hover {
                opacity: 0.8;
            }
        }
    }

    .history-list {
        flex: 1;
        overflow-y: auto;
        width: 248px;
        height: 120px;

        /* 隐藏滚动条 */
        &::-webkit-scrollbar {
            display: none;
        }

        -ms-overflow-style: none;
        scrollbar-width: none;

        /* 空状态样式 */
        .empty-history {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            margin-top: 236px;

            .empty-icon {
                width: 147px;
                height: 148px;
                object-fit: contain;
                margin-bottom: 16px;
            }

            .empty-text {
                font-size: 16px;
                color: #9c9fa7;
                text-align: center;
            }
        }

        .history-item {
            background: white;
            border-radius: 8px;
            padding: 12px 18px 12px 15px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            border-left: 3px solid transparent;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            display: flex;
            position: relative;

            &:hover {
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);

                .delete-btn {
                    opacity: 1;
                    visibility: visible;
                }
            }

            &.active {
                border-left-color: #3e7bfa;
                box-shadow: 0 2px 8px rgba(62, 123, 250, 0.2);
            }

            .history-content {
                width: 100%;

                .title-row {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    // margin-bottom: 4px;

                    .history-title {
                        font-size: 14px;
                        font-weight: 600;
                        line-height: 1.4;
                        color: #1f2937;
                        flex: 1;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                        margin-right: 8px;
                    }

                    .history-tag {
                        font-size: 11px;
                        padding: 2px 8px;
                        border-radius: 4px;
                        font-weight: 500;
                        flex-shrink: 0;

                        &.tag-tunnel {
                            background: rgba(62, 123, 250, 0.1);
                            color: #3366e6;
                        }

                        &.tag-bridge {
                            background: rgba(34, 184, 80, 0.1);
                            color: #22b850;
                        }

                        &.tag-equipment {
                            background: rgba(0, 128, 255, 0.1);
                            color: #0080ff;
                        }

                        &.tag-highway {
                            background: rgba(114, 46, 209, 0.1);
                            color: #722ed1;
                        }

                        &.tag-gas-station {
                            background: rgba(255, 77, 79, 0.1);
                            color: #ff4d4f;
                        }
                    }
                }

                .time-row {
                    margin-bottom: 4px;

                    .history-time {
                        font-size: 12px;
                        color: #6b7280;
                    }
                }

                .desc-row {
                    display: flex;
                    align-items: flex-start;
                    gap: 12px;

                    .history-icon {
                        width: 48px;
                        height: 48px;
                        flex-shrink: 0;

                        .history-icon-img {
                            width: 100%;
                            height: 100%;
                            object-fit: contain;
                            border-radius: 4px;
                        }
                    }

                    .history-desc {
                        flex: 1;
                        font-size: 12px;
                        line-height: 1.4;
                        color: #6b7280;
                        overflow: hidden;
                        display: -webkit-box;
                        -webkit-line-clamp: 3;
                        line-clamp: 3;
                        -webkit-box-orient: vertical;
                        text-overflow: ellipsis;
                    }
                }
            }

            .delete-btn {
                opacity: 0;
                visibility: hidden;
                transition: all 0.2s ease;
                cursor: pointer;
                padding: 4px 4px;
                border-radius: 4px;
                color: #7c8db5;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-left: 8px;
                flex-shrink: 0;
                position: absolute;
                top: 35px;
                right: 2px;

                &:hover {
                    color: #ff4757;
                    background-color: rgba(255, 71, 87, 0.1);
                }

                &.always-visible {
                    opacity: 1;
                    visibility: visible;
                }
            }
        }
    }
}
/* 主工作区域 */
.main-work {
    flex: 1;
    background: #ebf3ff;
    display: flex;
    flex-direction: column;
}

/* 工作头部 */
.work-header {
    background: transparent;
    padding: 30px 0px 0px 18px;

    h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #2c3e50;
    }
}

/* 工作内容区域 */
.work-content {
    flex: 1;
    padding: 22px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    scroll-behavior: smooth;
}

/* 主布局：左右分栏 */
.main-layout {
    display: flex;
    gap: 20px;
    height: 100%;
    // min-height: 600px;
}

/* 左侧：隐患提示系统 */
.left-section {
    width: 100%;
    background: white;
    border-radius: 16px;
    padding: 30px 30px 15px 30px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    align-items: center;
    min-height: min-content;
    transition: all 0.8s cubic-bezier(0.4, 0, 0.2, 1);

    &.transitioning {
        width: 100%;
        max-width: 100%;
        padding: 40px;
        transform: scale(1.02);
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
    }
    .hazard-system {
        flex: 1;
        display: flex;
        flex-direction: column;
        width: 687px;

        .system-header {
            text-align: center;
            margin-bottom: 66px;

            h3 {
                font-size: 24px;
                font-weight: 600;
                color: #1f2937;
                margin: 0 0 10px 0;
            }

            p {
                font-size: 16px;
                color: #6b7280;
                margin: 0;
                line-height: 1.4;
            }
        }

        .step-section {
            margin-bottom: 51px;

            h4 {
                font-size: 16px;
                font-weight: 600;
                color: #1f2937;
                margin: 0 0 8px 0;
            }

            .step-description {
                font-size: 14px;
                color: #6b7280;
                margin: 0 0 12px 0;
                line-height: 1.4;
            }

            .scenario-tags {
                display: flex;
                flex-wrap: wrap;
                gap: 12px;

                .scenario-tag {
                    padding: 10px 20px;
                    border-radius: 8px;
                    font-size: 14px;
                    font-weight: 500;
                    cursor: pointer;
                    transition: all 0.3s ease;
                    border: 2px solid transparent;
                    background: #f8faff;
                    color: #1f2937;

                    &.active {
                        background: rgba(62, 123, 250, 0.1);
                        color: #3366e6;
                        border-color: #3366e6;
                        box-shadow: 0 2px 8px rgba(62, 123, 250, 0.2);
                    }

                    &.disabled {
                        background: #f3f4f6;
                        color: #9ca3af;
                        border-color: #d1d5db;
                        cursor: not-allowed;
                        opacity: 0.6;

                        &:hover {
                            transform: none;
                            box-shadow: none;
                        }
                    }

                    &.identifying-disabled {
                        background: #f3f4f6;
                        color: #9ca3af;
                        border-color: #d1d5db;
                        cursor: not-allowed;
                        opacity: 0.6;
                        pointer-events: none;

                        &:hover {
                            transform: none;
                            box-shadow: none;
                        }
                    }

                    &:hover:not(.disabled) {
                        transform: translateY(-2px);
                        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                    }
                }
            }

            .upload-area {
                position: relative;
                border: 2px dashed #3e7bfa;
                border-radius: 12px;
                margin-top: 12px;
                height: 380px;
                text-align: center;
                cursor: pointer;
                transition: all 0.3s ease;

                &:hover {
                    border-color: #3e7bfa;
                    background: rgba(62, 123, 250, 0.02);
                }

                &.drag-over {
                    border-color: #3e7bfa;
                    background: rgba(62, 123, 250, 0.05);
                    box-shadow: 0 0 10px rgba(62, 123, 250, 0.2);
                }

                .uploaded-image-container {
                    position: relative;
                    width: 100%;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background-color: #f1f6ff;
                    border-radius: 8px;
                    overflow: hidden;

                    .uploaded-image {
                        width: 100%;
                        height: 100%;
                        object-fit: contain;
                        border-radius: 8px;
                    }

                    .image-overlay {
                        position: absolute;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background: rgba(0, 0, 0, 0.5);
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        border-radius: 8px;
                        cursor: pointer;

                        .change-image-btn {
                            background: #3e7bfa;
                            color: white;
                            border: none;
                            border-radius: 8px;
                            padding: 8px 16px;
                            font-size: 14px;
                            font-weight: 600;
                            cursor: pointer;
                            transition: background-color 0.3s ease;

                            &:hover {
                                background: #3366e6;
                            }
                        }
                    }
                }

                .upload-content {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    height: 100%;
                    padding: 20px;

                    .upload-icon {
                        width: 48px;
                        height: 48px;
                        margin-bottom: 12px;
                    }

                    .upload-text {
                        font-size: 16px;
                        font-weight: 600;
                        color: #2c3e50;
                        margin: 0 0 6px 0;
                    }

                    .upload-format {
                        font-size: 12px;
                        color: #6b7280;
                        margin: 0 0 50px 0;
                    }

                    .select-file-btn {
                        background: #e5eeff;
                        border: 1px solid #3e7bfa;
                        border-radius: 8px;
                        width: 120px;
                        height: 40px;
                        font-size: 14px;
                        color: #3e7bfa;
                        cursor: pointer;
                        transition: all 0.3s ease;

                        &:hover {
                            background: #e5e7eb;
                            border-color: #9ca3af;
                        }
                    }
                }
            }

            .upload-status {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(255, 255, 255, 0.7);
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                border-radius: 12px;
                z-index: 10;
                backdrop-filter: blur(1px);

                .loading-spinner {
                    border: 4px solid #f8f9fa;
                    border-top: 4px solid #3e7bfa;
                    border-radius: 50%;
                    width: 40px;
                    height: 40px;
                    animation: spin 1s linear infinite;
                    margin-bottom: 10px;
                }

                p {
                    font-size: 16px;
                    color: #4b5563;
                    font-weight: 500;
                }
            }
        }

        .action-section {
            text-align: center;
            // margin-top: -16px;

            .start-identify-btn {
                position: relative;
                border: none;
                background: none;
                cursor: pointer;
                padding: 0;
                transition: opacity 0.3s ease;

                &.btn-disabled {
                    opacity: 0.6;
                    cursor: not-allowed;
                    pointer-events: none;
                }

                .btn-bg {
                    width: 100%;
                    // max-width: 400px;
                    height: 48px;
                    object-fit: contain;
                }
            }
        }
    }
}

/* 右侧：使用流程 */
.right-section {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    transition: all 0.8s cubic-bezier(0.4, 0, 0.2, 1);

    &.slide-out {
        transform: translateX(100%);
        opacity: 0;
    }

    .process-card {
        width: 250px;
        background: white;
        border-radius: 16px;
        padding: 12px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        height: 100%;
        display: flex;
        flex-direction: column;
        min-height: max-content;

        h3 {
            font-size: 18px;
            // font-weight: 600;
            color: #1f2937;
            // margin: 0 0 8px 0;
            text-align: center;
        }

        .process-section {
            flex: 1;
            display: flex;
            flex-direction: column;

            .process-flow {
                flex: 1;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: space-between;
                padding: 20px 0;

                .process-step {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    width: 100%;
                    // margin-bottom: 20px;

                    .step-icon-wrapper {
                        position: relative;
                        width: 80px;
                        height: 80px;
                        margin-bottom: 12px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        background: linear-gradient(
                            135deg,
                            #ebf3ff 0%,
                            #f5f9ff 100%
                        );
                        border-radius: 50%;
                        box-shadow: 0 4px 12px rgba(62, 123, 250, 0.15);

                        .step-icon {
                            transition: transform 0.3s ease;
                        }

                        &:hover .step-icon {
                            transform: scale(1.1);
                        }

                        .step-number {
                            position: absolute;
                            top: 0;
                            right: 0;
                            width: 24px;
                            height: 24px;
                            background: linear-gradient(
                                135deg,
                                rgba(51, 102, 230, 1),
                                rgba(51, 102, 230, 1)
                            );
                            border-radius: 50%;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            font-size: 14px;
                            font-weight: 600;
                            color: #ffffff;
                        }
                    }

                    .step-content {
                        text-align: center;

                        .step-title {
                            font-size: 16px;
                            font-weight: 600;
                            color: #1f2937;
                            margin-bottom: 4px;
                        }

                        .step-desc {
                            font-size: 14px;
                            color: #6b7280;
                            line-height: 1.4;
                        }
                    }
                }

                .step-connector {
                    width: 3px;
                    height: 60px;
                    background-color: #e4e4e4;
                    margin: 5px 0;
                }
            }
        }
    }
}

/* 固定布局，支持横向滚动 */
.chat-container {
    min-width: 1000px; /* 设置最小宽度，确保内容完整显示 */
}

.work-content {
    min-width: 1000px; /* 工作内容区域最小宽度 */

    /* 隐藏垂直滚动条 */
    &::-webkit-scrollbar {
        display: none;
    }
    -ms-overflow-style: none;
    scrollbar-width: none;
}

.detail-view {
    min-width: 1000px; /* 详情页最小宽度 */
}

/* 详情页样式 */
.detail-view {
    width: 100%;
    max-width: 1528px;
    height: calc(100vh - 88px); /* 固定高度，减去头部高度 */
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    animation: fadeInUp 0.6s ease-out;
    opacity: 0;
    animation-fill-mode: forwards;

    .detail-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 24px;

        .header-left {
            display: flex;
            align-items: center;
            gap: 8px;

            .header-icon {
                width: 48px;
                height: 48px;
            }

            .header-icon-svg {
                width: 20px;
                height: 20px;
                color: #1296db;
                flex-shrink: 0;
            }

            .header-text {
                display: flex;
                align-items: center;
                gap: 8px;

                .main-title {
                    font-size: 15px;
                    font-weight: 500;
                    color: #ffffff;
                    background-color: #3b82f6;
                    padding: 4px 12px;
                    border-radius: 6px;
                    display: inline-flex;
                    align-items: center;
                }

                .sub-title-tag {
                    font-size: 11px;
                    padding: 2px 8px;
                    border-radius: 4px;
                    font-weight: 500;
                    flex-shrink: 0;

                    &.tag-tunnel {
                        background: rgba(62, 123, 250, 0.1);
                        color: #3366e6;
                    }

                    &.tag-bridge {
                        background: rgba(34, 184, 80, 0.1);
                        color: #22b850;
                    }

                    &.tag-equipment {
                        background: rgba(0, 128, 255, 0.1);
                        color: #0080ff;
                    }

                    &.tag-highway {
                        background: rgba(114, 46, 209, 0.1);
                        color: #722ed1;
                    }

                    &.tag-gas-station {
                        background: rgba(255, 77, 79, 0.1);
                        color: #ff4d4f;
                    }
                }
            }
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 16px;

            .back-btn {
                display: flex;
                align-items: center;
                gap: 8px;
                background: #e5eeff;
                border: 1px solid #3e7bfa;
                border-radius: 8px;
                padding: 8px 16px;
                font-size: 14px;
                color: #3e7bfa;
                cursor: pointer;
                transition: all 0.3s ease;

                &:hover {
                    background: #e5e7eb;
                    border-color: #9ca3af;
                }

                .back-icon {
                    width: 16px;
                    height: 16px;
                }
            }

            .current-time {
                font-size: 14px;
                color: #6b7280;
            }
        }
    }

    .detail-content {
        padding: 1rem;
        max-width: 56rem;
        width: 56rem;
        margin: 0 auto;
        position: relative;
        display: flex;
        flex-direction: column;
        min-height: 0;
        flex: 1;
        overflow-y: auto;
        scroll-behavior: smooth;

        /* 隐藏滚动条 */
        &::-webkit-scrollbar {
            display: none;
        }
        -ms-overflow-style: none;
        scrollbar-width: none;

        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 100;

            .loading-spinner {
                border: 4px solid #f3f3f3;
                border-top: 4px solid #3e7bfa;
                border-radius: 50%;
                width: 40px;
                height: 40px;
                animation: spin 1s linear infinite;
                margin-bottom: 16px;
            }

            p {
                font-size: 16px;
                color: #666;
                margin: 0;
            }
        }

        .image-section {
            background-color: #dbeafe;
            border-radius: 0.5rem;
            padding: 1rem;
            text-align: center;
            margin-bottom: 1rem;
            position: relative;

            .evaluation-status {
                position: absolute;
                top: 12px;
                right: 12px;
                z-index: 10;
                cursor: pointer;

                .status-badge {
                    display: inline-block;
                    padding: 4px 12px;
                    border-radius: 12px;
                    font-size: 12px;
                    font-weight: 500;
                    // line-height: 1.2;
                    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

                    &.evaluated {
                        background: #d1fae5;
                        color: #065f46;
                        border: 1px solid #a7f3d0;
                        cursor: default;
                    }

                    &.not-evaluated {
                        background: #fef3c7;
                        color: #92400e;
                        border: 1px solid #fde68a;
                        cursor: pointer;
                    }
                }
            }

            .image-container {
                position: relative;
                width: 100%;
                height: 350px;
                border-radius: 0.5rem;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
                border: 2px dashed #86efac;
                overflow: hidden;
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: #dbeafe;
            }

            .original-image,
            .main-image {
                width: 100%;
                height: 100%;
                display: block;
                object-fit: contain;
                transform: none !important;
                image-orientation: from-image;
                -webkit-image-orientation: from-image;
            }

            .main-image {
                cursor: pointer;
            }

            .element-overlay-card {
                position: absolute;
                width: 260px;
                max-height: 180px;
                overflow-y: auto;
                text-align: left;
                padding: 14px 16px;
                background: rgba(255, 255, 255, 0.96);
                border: 1px solid rgba(239, 68, 68, 0.25);
                border-radius: 14px;
                box-shadow: 0 16px 32px rgba(15, 23, 42, 0.18);
                backdrop-filter: blur(10px);
                z-index: 6;

                .element-card-title {
                    font-size: 14px;
                    font-weight: 600;
                    color: #b91c1c;
                    margin-bottom: 10px;
                }

                .element-card-list {
                    margin: 0;
                    padding-left: 18px;
                    color: #374151;
                    font-size: 13px;
                    line-height: 1.6;
                }

                .element-card-empty {
                    font-size: 13px;
                    color: #6b7280;
                }
            }

            .scanning-overlay {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                pointer-events: none;
                overflow: hidden;
                border-radius: 0.5rem;
                background: rgba(255, 255, 255, 0.3);
                backdrop-filter: blur(2px);

                .scanning-line {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 4px;
                    background: linear-gradient(
                        90deg,
                        transparent 0%,
                        #3b82f6 20%,
                        #60a5fa 50%,
                        #3b82f6 80%,
                        transparent 100%
                    );
                    box-shadow: 0 0 15px rgba(59, 130, 246, 0.8),
                        0 0 30px rgba(59, 130, 246, 0.5);
                    animation: scanning 1s ease-in-out 3; /* 扫描3次，每次1秒，共3秒 */
                }
            }
        }

        .analysis-section {
            background-color: #f9fafb;
            border-left: 0;
            padding: 1rem;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);

            .analysis-header {
                display: flex;
                align-items: center;
                margin-bottom: 0;

                .robot-avatar {
                    flex-shrink: 0;
                    margin-right: 0.75rem;

                    .robot-img {
                        width: 4rem;
                        height: 4rem;
                        object-fit: contain;
                        animation: robot-float 3s ease-in-out infinite;
                    }
                }
            }

            .header-title {
                flex: 1;

                .analysis-title {
                    font-size: 1rem;
                    font-weight: 600;
                    color: #1f2937;
                    margin: 0;
                    line-height: 1.5;
                }

                .analysis-prompt {
                    display: flex;
                    align-items: center;
                    gap: 0.75rem;
                    color: #6b7280;
                    font-weight: 400;
                    font-size: 0.9375rem;

                    .typing-indicator {
                        display: inline-flex;
                        align-items: center;
                        gap: 4px;

                        .dot {
                            width: 6px;
                            height: 6px;
                            border-radius: 50%;
                            background-color: #3b82f6;
                            animation: typing-dot 1.4s infinite ease-in-out;

                            &:nth-child(1) {
                                animation-delay: 0s;
                            }

                            &:nth-child(2) {
                                animation-delay: 0.2s;
                            }

                            &:nth-child(3) {
                                animation-delay: 0.4s;
                            }
                        }
                    }

                    .prompt-text {
                        font-style: italic;
                    }
                }
            }
        }

        .analysis-body {
            margin-left: 4.75rem;

            .analysis-text {
                font-size: 0.9375rem;
                line-height: 1.8;
                color: #374151;
                margin-bottom: 1rem;

                .scene-tag {
                    color: #3b82f6;
                    font-weight: 600;
                }

                .label-tag {
                    display: inline-block;
                    padding: 0.125rem 0.625rem;
                    margin: 0.125rem 0.25rem;
                    background-color: #eff6ff;
                    color: #3b82f6;
                    border: 1px solid #bfdbfe;
                    border-radius: 1rem;
                    font-weight: 500;
                    font-size: 0.8125rem;
                }

                .streaming-text {
                    border-right: 2px solid #3b82f6;
                    animation: blink 1s infinite;
                }
            }

            .result-blockquote {
                background-color: #ffffff;
                border-left: 4px solid #3b82f6;
                padding: 1rem;
                margin: 0;
                margin-bottom: 0.75rem;
                border-radius: 0.5rem;
                box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
                position: relative;
                overflow: hidden;

                .blockquote-label {
                    font-size: 0.875rem;
                    font-weight: 600;
                    color: #6b7280;
                    margin: 0 0 0.25rem 0;
                }

                .blockquote-content {
                    margin: 0;
                    color: #4b5563;
                    font-size: 0.9375rem;
                    line-height: 1.6;

                    .scene-highlight {
                        color: #3b82f6;
                        font-weight: 600;
                    }

                    .streaming-text {
                        border-right: 2px solid #3b82f6;
                        animation: blink 1s infinite;
                    }
                }
            }

            .hazards-intro {
                margin: 0;
                color: #1f2937;
                font-size: 0.9375rem;
                font-weight: 400;
                line-height: 1.6;
                margin-bottom: 0.75rem;
            }

            .key-elements-section {
                margin-bottom: 1rem;
                padding: 0.875rem 1rem;
                border-radius: 16px;
                background: linear-gradient(135deg, #eef4ff 0%, #f8fbff 100%);
                border: 1px solid #dbeafe;

                .key-elements-title {
                    font-size: 0.875rem;
                    font-weight: 600;
                    color: #1e3a8a;
                    margin-bottom: 0.75rem;
                }

                .key-elements-buttons {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 0.625rem;
                }

                .key-element-btn {
                    border: 1px solid #bfdbfe;
                    background: #ffffff;
                    color: #1d4ed8;
                    border-radius: 9999px;
                    padding: 0.45rem 0.9rem;
                    font-size: 0.875rem;
                    line-height: 1;
                    cursor: pointer;
                    transition: all 0.2s ease;

                    &:hover {
                        border-color: #60a5fa;
                        background: #eff6ff;
                    }

                    &.active {
                        background: #2563eb;
                        border-color: #2563eb;
                        color: #ffffff;
                        box-shadow: 0 10px 24px rgba(37, 99, 235, 0.22);
                    }
                }

                .key-elements-hint {
                    margin-top: 0.75rem;
                    font-size: 0.8125rem;
                    color: #64748b;
                }
            }

            /* 场景隐患列表样式 - 移到analysis-section内部 */
            .hazards-section {
                margin-top: 0;

                .hazards-content {
                    position: relative;

                    &.scanning-mode {
                        min-height: 200px;
                    }

                    .hazard-cards-container {
                        display: flex;
                        flex-direction: column;
                        gap: 0.75rem;
                        margin-top: 0.75rem;
                    }

                    .hazard-empty {
                        padding: 1rem 1.25rem;
                        margin-top: 0.75rem;
                        background: #ffffff;
                        border: 1px dashed #cbd5e1;
                        border-radius: 16px;
                        font-size: 0.875rem;
                        color: #64748b;
                        text-align: center;
                    }

                    .hazard-card {
                        background-color: #ffffff;
                        border-radius: 9999px;
                        border: 1px solid #f3f4f6;
                        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
                        padding: 0.75rem;
                        display: flex;
                        align-items: flex-start;
                        cursor: pointer;
                        opacity: 0;
                        transform: translateX(-20px);
                        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                        position: relative;
                        overflow: hidden;

                        &.show {
                            opacity: 1;
                            transform: translateX(0);
                        }

                        &:hover {
                            transform: translateX(8px) scale(1.02) !important;
                            box-shadow: 0 10px 25px -5px rgba(59, 130, 246, 0.3),
                                0 8px 10px -6px rgba(59, 130, 246, 0.2);
                            border-color: rgba(59, 130, 246, 0.5);
                        }

                        .hazard-number {
                            width: 24px;
                            height: 24px;
                            background-color: #3b82f6;
                            border-radius: 50%;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            font-size: 14px;
                            font-weight: 500;
                            color: #ffffff;
                            flex-shrink: 0;
                            margin-right: 0.75rem;
                            margin-top: 0.125rem;
                        }

                        .hazard-text-container {
                            display: flex;
                            justify-content: space-between;
                            align-items: center;
                            flex-grow: 1;

                            .hazard-desc {
                                flex: 1;
                                font-size: 0.9375rem;
                                color: #1f2937;
                                margin: 0;
                                line-height: 1.5;
                            }

                            .example-link {
                                color: #3b82f6;
                                font-size: 0.875rem;
                                font-weight: 400;
                                padding: 0.25rem 0.75rem;
                                background-color: #eff6ff;
                                border-radius: 9999px;
                                text-decoration: none;
                                transition: all 0.2s ease;
                                flex-shrink: 0;
                                margin-left: 0.75rem;

                                &:hover {
                                    background-color: #dbeafe;
                                }
                            }
                        }
                    }

                    /* 隐患区域加载遮罩层样式 */
                    .hazards-loading-overlay {
                        position: absolute;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background: rgba(249, 250, 251, 0.9);
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        justify-content: center;
                        z-index: 10;
                        border-radius: 8px;
                        backdrop-filter: blur(2px);

                        .loading-spinner {
                            border: 4px solid #f3f3f3;
                            border-top: 4px solid #3e7bfa;
                            border-radius: 50%;
                            width: 40px;
                            height: 40px;
                            animation: spin 1s linear infinite;
                            margin-bottom: 16px;
                        }

                        p {
                            font-size: 16px;
                            color: #6b7280;
                            margin: 0;
                            font-weight: 500;
                        }
                    }
                }
            }
        }
    }

    /* 新的示例对比弹窗样式 */
    .modal-backdrop {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.6);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
        backdrop-filter: blur(4px);
    }

    .example-comparison-modal {
        width: 90vw;
        max-width: 1200px;
        max-height: 80vh;
        background: white;
        border-radius: 16px;
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        overflow: hidden;
        animation: modalSlideIn 0.3s ease-out;
        display: flex;
        flex-direction: column;
    }

    .modal-header-section {
        padding: 24px 32px;
        border-bottom: 1px solid #e5e7eb;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
    }

    .modal-title-area h3 {
        margin: 0 0 8px 0;
        font-size: 20px;
        font-weight: 600;
        color: #1f2937;
    }

    .hazard-info {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .hazard-number {
        width: 24px;
        height: 24px;
        background: #3b82f6;
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: 600;
    }

    .hazard-text {
        color: #6b7280;
        font-size: 16px;
        font-weight: 500;
    }

    .close-button {
        background: none;
        border: none;
        padding: 8px;
        border-radius: 8px;
        cursor: pointer;
        color: #6b7280;
        transition: all 0.2s ease;
    }

    .close-button:hover {
        background: #f3f4f6;
        color: #374151;
    }

    .modal-content-section {
        flex: 1;
        padding: 32px;
        overflow-y: auto;
    }

    .loading-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        min-height: 300px;
        gap: 16px;
    }

    .spinner {
        width: 40px;
        height: 40px;
        border: 4px solid #f3f4f6;
        border-top: 4px solid #3b82f6;
        border-radius: 50%;
        animation: spin 1s linear infinite;
    }

    .comparison-container {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 32px;
        min-height: 400px;
    }

    .example-card {
        background: #f9fafb;
        border-radius: 12px;
        overflow: hidden;
        border: 2px solid transparent;
        transition: all 0.3s ease;
    }

    .example-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 12px 32px rgba(0, 0, 0, 0.1);
    }

    .correct-example {
        border-color: #10b981;
    }

    .error-example {
        border-color: #ef4444;
    }

    .card-header {
        padding: 16px 20px;
        background: white;
        border-bottom: 1px solid #e5e7eb;
    }

    .status-badge {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 14px;
        font-weight: 500;
    }

    .status-badge.correct {
        background: #d1fae5;
        color: #065f46;
    }

    .status-badge.error {
        background: #fee2e2;
        color: #991b1b;
    }

    .card-content {
        padding: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 300px;
    }

    .example-image {
        max-width: 100%;
        max-height: 300px;
        object-fit: contain;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .clickable-image {
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .clickable-image:hover {
        transform: scale(1.02);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    }

    .image-loading {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 12px;
        color: #6b7280;
    }

    .no-image {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 16px;
        color: #9ca3af;
        text-align: center;
    }

    .no-image svg {
        opacity: 0.5;
    }

    .no-image p {
        margin: 0;
        font-size: 14px;
    }

    /* 弹窗动画 */
    @keyframes modalSlideIn {
        from {
            opacity: 0;
            transform: scale(0.9) translateY(-20px);
        }
        to {
            opacity: 1;
            transform: scale(1) translateY(0);
        }
    }

    @keyframes imageZoomIn {
        from {
            opacity: 0;
            transform: scale(0.8);
        }
        to {
            opacity: 1;
            transform: scale(1);
        }
    }

    /* 响应式设计 */
    @media (max-width: 768px) {
        .comparison-container {
            grid-template-columns: 1fr;
            gap: 20px;
        }

        .modal-content-section {
            padding: 20px;
        }

        .modal-header-section {
            padding: 16px 20px;
        }

        .example-comparison-modal {
            width: 95vw;
            max-height: 90vh;
        }
    }

    .modal-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 24px 52px 0px 76px;

        .modal-title {
            font-size: 22px;
            font-weight: 600;
            color: #1f2937;
        }
        .close-icon {
            width: 24px;
            height: 24px;
            cursor: pointer;
            transition: opacity 0.3s ease;

            &:hover {
                opacity: 0.7;
            }
        }
    }

    .modal-hazard-info {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;

        .hazard-number {
            width: 24px;
            height: 24px;
            background: #3e7bfa;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            font-weight: 600;
            color: #ffffff;
            flex-shrink: 0;
        }

        .hazard-description {
            font-size: 16px;
            color: #374151;
            line-height: 1.5;
        }
    }

    .modal-body {
        display: flex;
        gap: 24px;
        padding: 32px 81px;
        height: calc(100% - 120px);
        position: relative;

        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 100;

            .loading-spinner {
                border: 4px solid #f3f3f3;
                border-top: 4px solid #3e7bfa;
                border-radius: 50%;
                width: 40px;
                height: 40px;
                animation: spin 1s linear infinite;
                margin-bottom: 16px;
            }

            p {
                font-size: 16px;
                color: #666;
                margin: 0;
            }
        }

        .example-panel {
            flex: 1;
            // background: #f9fafb;
            border-radius: 12px;
            // padding: 24px;
            display: flex;
            flex-direction: column;

            .panel-image {
                flex: 1;
                display: flex;
                align-items: center;
                justify-content: center;
                position: relative;
                max-height: 480px;
                overflow: hidden;

                img {
                    max-width: 100%;
                    max-height: 100%;
                    width: 100%;
                    height: 100%;
                    object-fit: contain;
                    border-radius: 8px;
                    display: block;
                    margin: 0 auto;

                    // 横图充满容器
                    &[data-orientation="landscape"] {
                        object-fit: cover;
                    }

                    // 竖图保持完整显示
                    &[data-orientation="portrait"] {
                        object-fit: contain;
                    }
                }

                .no-image-placeholder {
                    width: 100%;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background-color: #f5f5f5;
                    border: 2px dashed #d1d5db;
                    border-radius: 8px;

                    .placeholder-text {
                        color: #6b7280;
                        font-size: 16px;
                        font-weight: 500;
                        text-align: center;
                    }
                }

                .image-loading {
                    width: 100%;
                    height: 100%;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    background-color: #f9fafb;
                    border: 2px dashed #d1d5db;
                    border-radius: 8px;

                    .loading-spinner {
                        border: 3px solid #f3f3f3;
                        border-top: 3px solid #3e7bfa;
                        border-radius: 50%;
                        width: 32px;
                        height: 32px;
                        animation: spin 1s linear infinite;
                        margin-bottom: 12px;
                    }

                    p {
                        color: #6b7280;
                        font-size: 14px;
                        font-weight: 500;
                        margin: 0;
                        text-align: center;
                    }
                }

                .image-label {
                    position: absolute;
                    top: 0px;
                    left: 0px;
                    z-index: 10;

                    .label-icon {
                        width: 95px;
                        height: 30px;
                    }
                }
            }

            &.correct-panel {
                .panel-image > img:first-child {
                    border: 1px solid #34d399;
                    border-radius: 8px;
                }
            }

            &.error-panel {
                .panel-image > img:first-child {
                    border: 1px solid #ef4444;
                    border-radius: 8px;
                }
            }
        }
    }

    .empty-history {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin-top: 236px;

        .empty-icon {
            width: 147px;
            height: 148px;
            object-fit: contain;
            margin-bottom: 16px;
        }

        .empty-text {
            font-size: 16px;
            color: #9c9fa7;
            text-align: center;
        }
    }
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}

/* Toast提示组件样式 */
.toast {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 9999;
    animation: slideIn 0.3s ease-out;
}

.toast-content {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    min-width: 300px;
}

.toast-success {
    background: #f0f9ff;
    border: 1px solid #0ea5e9;

    .toast-icon img {
        width: 20px;
        height: 20px;
    }

    .toast-message {
        color: #0c4a6e;
        font-weight: 500;
    }
}

.toast-error {
    background: #fef2f2;
    border: 1px solid #ef4444;

    .toast-icon img {
        width: 20px;
        height: 20px;
    }

    .toast-message {
        color: #991b1b;
        font-weight: 500;
    }
}

@keyframes slideIn {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

/* 图片预览弹窗样式 */
.image-preview-overlay {
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    right: 0 !important;
    bottom: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    background: rgba(0, 0, 0, 0.8) !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    z-index: 9999 !important;
    cursor: pointer !important;
    margin: 0 !important;
    padding: 0 !important;
    box-sizing: border-box !important;
}

.preview-image {
    max-width: 90%;
    max-height: 90%;
    object-fit: contain;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    transform: none !important;
    image-orientation: from-image;
    -webkit-image-orientation: from-image;
}

/* 历史记录加载状态样式 */
.history-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    min-height: 200px;
}

.history-loading .loading-spinner {
    width: 32px;
    height: 32px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #409eff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin: 0 auto 16px auto;
}

.history-loading .loading-text {
    color: #6b7280;
    font-size: 14px;
    margin: 0;
    font-weight: 400;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}

@keyframes scanning {
    0% {
        top: 0;
        opacity: 0;
    }
    10% {
        opacity: 1;
    }
    90% {
        opacity: 1;
    }
    100% {
        top: 100%;
        opacity: 0;
    }
}

/* 机器人浮动动画 */
@keyframes robot-float {
    0%,
    100% {
        transform: translateY(0px) rotate(0deg);
    }
    50% {
        transform: translateY(-5px) rotate(2deg);
    }
}

/* 眼睛眨眼动画 */
@keyframes blink {
    0%,
    90%,
    100% {
        opacity: 1;
    }
    95% {
        opacity: 0.2;
    }
}

/* 天线波动动画 */
@keyframes antenna-wave {
    0%,
    100% {
        transform: rotate(0deg);
    }
    25% {
        transform: rotate(-8deg);
    }
    75% {
        transform: rotate(8deg);
    }
}

/* 信号脉冲动画 */
@keyframes signal-pulse {
    0%,
    100% {
        opacity: 1;
        transform: scale(1);
    }
    50% {
        opacity: 0.4;
        transform: scale(1.3);
    }
}

/* 微笑动画 */
@keyframes smile {
    0%,
    90%,
    100% {
        d: path("M 35 60 Q 50 70 65 60");
    }
    95% {
        d: path("M 35 58 Q 50 68 65 58");
    }
}

/* 心跳动画 */
@keyframes heartbeat {
    0%,
    100% {
        transform: scale(1);
    }
    10%,
    30% {
        transform: scale(1.15);
    }
    20%,
    40% {
        transform: scale(1);
    }
}

/* 打字指示器动画 */
@keyframes typing-dot {
    0%,
    60%,
    100% {
        transform: translateY(0);
        opacity: 0.7;
    }
    30% {
        transform: translateY(-10px);
        opacity: 1;
    }
}

/* 淡入上升动画 */
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes loadingDots {
    0%,
    80%,
    100% {
        transform: scale(0);
        opacity: 0.5;
    }
    40% {
        transform: scale(1);
        opacity: 1;
    }
}

/* 点评弹窗样式 */
.evaluation-modal-overlay {
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    right: 0 !important;
    bottom: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    background: rgba(0, 0, 0, 0.5) !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    z-index: 9999 !important;
    margin: 0 !important;
    padding: 0 !important;
    box-sizing: border-box !important;
}

.evaluation-modal {
    width: 442px;
    background: linear-gradient(135deg, rgb(239, 246, 255) 0%, #ffffff 100%);
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
    overflow: hidden;
}

.modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24px 24px 0 24px;

    .modal-title {
        font-size: 20px;
        font-weight: 600;
        color: #1f2937;
    }

    .close-icon {
        width: 24px;
        height: 24px;
        cursor: pointer;
        transition: opacity 0.3s ease;

        &:hover {
            opacity: 0.7;
        }
    }
}

.modal-body {
    padding: 24px;

    .question-section {
        margin-bottom: 32px;

        &:last-child {
            margin-bottom: 0;
        }

        .question-title {
            font-size: 16px;
            font-weight: 500;
            color: #374151;
            margin-bottom: 16px;
        }

        .answer-buttons {
            display: flex;
            gap: 12px;

            .answer-btn {
                flex: 1;
                padding: 12px 24px;
                border: 2px solid #d1d5db;
                border-radius: 8px;
                background: white;
                color: #6b7280;
                font-size: 14px;
                font-weight: 500;
                cursor: pointer;
                transition: all 0.3s ease;

                &:hover {
                    border-color: #3e7bfa;
                    color: #3e7bfa;
                }

                &.active {
                    border-color: #3e7bfa;
                    background: #3e7bfa;
                    color: white;
                }

                &.disabled {
                    cursor: not-allowed;
                }
            }
        }

        .star-rating {
            display: flex;
            gap: 8px;

            .star {
                font-size: 32px;
                color: #d1d5db;
                cursor: pointer;
                transition: color 0.2s ease;

                &:hover {
                    color: #fbbf24;
                }

                &.active {
                    color: #fbbf24;
                }

                &.disabled {
                    cursor: not-allowed;
                }
            }
        }

        .remark-input-container {
            position: relative;

            .remark-textarea {
                width: 100%;
                min-height: 100px;
                padding: 12px;
                border: 2px solid #d1d5db;
                border-radius: 8px;
                font-size: 14px;
                font-family: inherit;
                resize: vertical;
                transition: border-color 0.3s ease;

                &:focus {
                    outline: none;
                    border-color: #3e7bfa;
                }

                &:disabled {
                    background-color: #f9fafb;
                    color: #6b7280;
                    cursor: not-allowed;
                }

                &::placeholder {
                    color: #9ca3af;
                }
            }

            .character-count {
                position: absolute;
                bottom: 8px;
                right: 12px;
                font-size: 12px;
                color: #6b7280;

                span {
                    &.over-limit {
                        color: #ef4444;
                        font-weight: 500;
                    }
                }
            }
        }
    }
}

.modal-footer {
    padding: 0 24px 24px 24px;
    text-align: center;

    .submit-btn {
        background: none;
        border: none;
        cursor: pointer;
        padding: 0;

        .submit-icon {
            width: 120px;
            height: 48px;
            object-fit: contain;
        }
    }
}

/* 全局弹窗样式 - 确保 teleport 弹窗正确显示 */
body > .example-modal-overlay,
body > .image-preview-overlay,
body > .evaluation-modal-overlay {
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    right: 0 !important;
    bottom: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    z-index: 9999 !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    margin: 0 !important;
    padding: 0 !important;
    box-sizing: border-box !important;
}
</style>
