<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Share, Download, Printer, ArrowUp } from '@element-plus/icons-vue'

interface CandidateInfo {
  name: string
  idNumber: string
  phoneNumber: string
  score: number
  availabilityPeriod: string
  onboardingTime: string
  suggestedSalary: string
  salaryRange:string 
  dimensions: {
    teamwork: string
    learningAbility: string
    attention: string
    workAdaptability: string
    serviceAwareness: string
  }
  dimensionDetails: {
    teamwork: string
    learningAbility: string
    attention: string
    workAdaptability: string
    serviceAwareness: string
  }
  duvAnalysis: {
    title: string
    content: string
    score: string
    type: 'positive' | 'negative' | 'neutral'
  }[]
  interviewRecord: {
    question: string
    answer: string
    analysis: string
    score: string
    videoUrl?: string
    thumbnail?: string
    question_form?: number
    is_correct?: boolean | string
    question_image_url?: string
  }[]
  videoRecords: {
    category: string
    videos: {
      url: string
      thumbnail: string
      description: string
    }[]
  }[]
  additionalInfo: {
    idVerification: string
    phoneVerification: string
    leftHandGestures: {
      passed: boolean
      images: string[]
    }
    rightHandGestures: {
      passed: boolean
      images: string[]
    }
    faceVerification: {
      passed: boolean
      images: string[]
    }
  }
  strengths?: string[]
  weaknesses?: string[]
  hireRecommendation?: string
  hireReason?: string
}

const candidateInfo = ref<CandidateInfo>({
  name: '',
  idNumber: '',
  phoneNumber: '',
  score: 0,
  availabilityPeriod: '',
  onboardingTime: '',
  suggestedSalary: '',
  salaryRange: '',
  dimensions: {
    teamwork: '欠佳',
    learningAbility: '优秀',
    attention: '欠佳',
    workAdaptability: '优秀',
    serviceAwareness: '中等'
  },
  dimensionDetails: {
    teamwork: '',
    learningAbility: '',
    attention: '',
    workAdaptability: '',
    serviceAwareness: ''
  },
  duvAnalysis: [
    {
      title: '',
      content: '',
      score: '',
      type: 'neutral'
    },
    {
      title: '',
      content: '',
      score: '',
      type: 'neutral'
    }
  ],
  interviewRecord: [
    {
      question: '',
      answer: '',
      analysis: '',
      score: '',
      videoUrl: '',
      thumbnail: '',
      question_form: 0,
      is_correct: false,
      question_image_url: ''
    },
    {
      question: '',
      answer: '',
      analysis: '',
      score: '',
      videoUrl: '',
      thumbnail: '',
      question_form: 0,
      is_correct: false,
      question_image_url: ''
    }
  ],
  videoRecords: [
    {
      category: '服务态度测评',
      videos: [
        {
          url: '',
          thumbnail: '',
          description: ''
        },
        {
          url: '',
          thumbnail: '',
          description: ''
        }
      ]
    }
  ],
  additionalInfo: {
    idVerification: '通过',
    phoneVerification: '通过',
    leftHandGestures: {
      passed: true,
      images: [
     
      ]
    },
    rightHandGestures: {
      passed: true,
      images: [
       
      ]
    },
    faceVerification: {
      passed: true,
      images: [
       
      ]
    }
  },
  strengths: [],
  weaknesses: [],
  hireRecommendation: '',
  hireReason: ''
})

const apiData = ref<any>(null)
const loading = ref<boolean>(true)
const error = ref<string>('')

const route = useRoute()

const fetchApplicationDetail = async () => {
  loading.value = true
  try {
    // 从Vue Router获取参数
    const id = route.query.id as string || '1'
    const tenant_id = route.query.tenant_id as string || '1'
    const application_id = route.query.application_id as string || '1'
    
    console.log('Route params:', { id, tenant_id, application_id })
    
    // 使用正确的参数调用API
    const response = await fetch(`${import.meta.env.VITE_API_URL}/api/job/application_detail?tenant_id=${tenant_id}&application_id=${id || application_id}`)
    const result = await response.json()
    
    if (result.code === 2000) {
      apiData.value = result.data
      updateCandidateInfo(result.data)
    } else {
      error.value = result.msg || '获取数据失败'
    }
  } catch (err) {
    console.error('获取申请详情失败:', err)
    error.value = '获取数据失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const updateCandidateInfo = (data: any) => {
  if (!data) return
  
  const { applicant, application, position, interview_progress, posture_photos } = data
  
  // 更新基本信息
  candidateInfo.value.name = applicant?.name || candidateInfo.value.name
  candidateInfo.value.phoneNumber = applicant?.phone || candidateInfo.value.phoneNumber
  candidateInfo.value.idNumber = applicant?.id_card || candidateInfo.value.idNumber
  
  // 添加薪资相关信息处理
  if (position) {
    // 如果API返回了薪资范围，使用API数据
    if (position.salary_range) {
      candidateInfo.value.salaryRange = position.salary_range || '面议'
      /* candidateInfo.value.salaryRange.max = position.salary_range || '面议' */
    } else {
      // 否则使用默认值
      candidateInfo.value.salaryRange = '面议'
   
    }
    
    // 根据候选人评分计算建议薪资
    if (candidateInfo.value.score >= 80) {
      // 高分候选人，建议给予较高薪资
      candidateInfo.value.suggestedSalary = position.salary_range?.max || '面议'
    } else if (candidateInfo.value.score >= 70) {
      // 中高分候选人，建议给予中等偏上薪资
      const min = parseInt(position.salary_range?.min || '0')
      const max = parseInt(position.salary_range?.max || '0')
      if (min > 0 && max > 0) {
        const suggested = Math.floor(min + (max - min) * 0.7)
        candidateInfo.value.suggestedSalary = suggested.toString()
      } else {
        candidateInfo.value.suggestedSalary = '面议'
      }
    } else if (candidateInfo.value.score >= 60) {
      // 及格候选人，建议给予中等薪资
      const min = parseInt(position.salary_range?.min || '0')
      const max = parseInt(position.salary_range?.max || '0')
      if (min > 0 && max > 0) {
        const suggested = Math.floor(min + (max - min) * 0.5)
        candidateInfo.value.suggestedSalary = suggested.toString()
      } else {
        candidateInfo.value.suggestedSalary = '面议'
      }
    } else {
      // 低分候选人，建议给予较低薪资或不录用
      candidateInfo.value.suggestedSalary = position.salary_range?.min || '面议'
    }
  } else {
    // 如果没有职位信息，设置默认值
    candidateInfo.value.salaryRange = '面议'
    candidateInfo.value.suggestedSalary = '面议'
  }
  
  // 更新综合分析
  if (application?.comprehensive_analysis) {
    // 更新综合评分
    if (application.comprehensive_analysis.comprehensive_score !== null && 
        application.comprehensive_analysis.comprehensive_score !== undefined) {
      candidateInfo.value.score = application.comprehensive_analysis.comprehensive_score
    }
    
    // 更新优缺点分析
    if (application.comprehensive_analysis.video_analysis_data) {
      const videoData = application.comprehensive_analysis.video_analysis_data
      
      // 更新优点
      if (videoData.strengths && videoData.strengths.length > 0) {
        candidateInfo.value.strengths = videoData.strengths.filter((s: string) => 
          s && !s.includes('无法从响应中提取')
        )
      }
      
      // 更新缺点
      if (videoData.weaknesses && videoData.weaknesses.length > 0) {
        candidateInfo.value.weaknesses = videoData.weaknesses.filter((w: string) => 
          w && !w.includes('无法从响应中提取')
        )
      }
      
      // 更新录用建议
      if (application.comprehensive_analysis.hire_recommendation) {
        candidateInfo.value.hireRecommendation = application.comprehensive_analysis.hire_recommendation
      }
      
      // 更新录用理由
      if (application.comprehensive_analysis.hire_reason) {
        candidateInfo.value.hireReason = application.comprehensive_analysis.hire_reason
      }
    }
  }
  
  // 更新能力维度评分
  if (application?.ai_capability_scores) {
    const dimensionMapping: Record<string, keyof typeof candidateInfo.value.dimensions> = {
      '专业性': 'workAdaptability',
      '沟通能力': 'teamwork',
      '技术匹配度': 'learningAbility',
      '解决问题能力': 'attention',
      '服务意识': 'serviceAwareness'
    }
    
    Object.entries(application.ai_capability_scores).forEach(([key, value]) => {
      const mappedKey = dimensionMapping[key]
      if (mappedKey && typeof value === 'number') {
        let rating = '中等'
        if (value >= 80) rating = '优秀'
        else if (value < 65) rating = '欠佳'
        
        candidateInfo.value.dimensions[mappedKey] = rating
      }
    })
  } else {
    // 如果没有AI能力评分，根据面试题目分析生成维度评分
    const dimensionScores: Record<string, number[]> = {
      teamwork: [],
      learningAbility: [],
      attention: [],
      workAdaptability: [],
      serviceAwareness: []
    }
    
    interview_progress?.forEach((q: any) => {
      if (q.video_answer && q.video_answer.ai_score) {
        // 根据问题类型和内容分配到不同维度
        if (q.question_text.includes('团队') || q.question_text.includes('合作')) {
          dimensionScores.teamwork.push(q.video_answer.ai_score)
        }
        if (q.question_text.includes('学习') || q.question_text.includes('技能')) {
          dimensionScores.learningAbility.push(q.video_answer.ai_score)
        }
        if (q.question_text.includes('细致') || q.question_text.includes('严谨') || q.question_text.includes('注意')) {
          dimensionScores.attention.push(q.video_answer.ai_score)
        }
        if (q.question_text.includes('适应') || q.question_text.includes('工作')) {
          dimensionScores.workAdaptability.push(q.video_answer.ai_score)
        }
        if (q.question_text.includes('服务') || q.question_text.includes('客户')) {
          dimensionScores.serviceAwareness.push(q.video_answer.ai_score)
        }
      }
    })
    
    // 计算每个维度的平均分并转换为评级
    Object.entries(dimensionScores).forEach(([key, scores]) => {
      if (scores.length > 0) {
        const avgScore = scores.reduce((sum, score) => sum + score, 0) / scores.length
        let rating = '中等'
        if (avgScore >= 80) rating = '优秀'
        else if (avgScore < 65) rating = '欠佳'
        
        candidateInfo.value.dimensions[key as keyof typeof candidateInfo.value.dimensions] = rating
      }
    })
  }
  
  // 更新维度详情
  const dimensionDetailsMapping: Record<string, string> = {
    teamwork: '候选人在团队协作方面的表现',
    learningAbility: '候选人的学习能力和接受新知识的速度',
    attention: '候选人对细节的关注程度和工作严谨性',
    workAdaptability: '候选人适应工作环境和要求的能力',
    serviceAwareness: '候选人的服务意识和客户导向思维'
  }
  
  Object.keys(candidateInfo.value.dimensionDetails).forEach(key => {
    const dimension = key as keyof typeof candidateInfo.value.dimensionDetails
    const rating = candidateInfo.value.dimensions[dimension]
    let detail = dimensionDetailsMapping[dimension] || ''
    
    if (rating === '优秀') {
      detail += '表现优秀，符合岗位要求。'
    } else if (rating === '中等') {
      detail += '表现一般，基本符合岗位要求。'
    } else {
      detail += '表现欠佳，需要进一步提升。'
    }
    
    candidateInfo.value.dimensionDetails[dimension] = detail
  })
  
  // 更新面试记录
  if (interview_progress && interview_progress.length > 0) {
    candidateInfo.value.interviewRecord = interview_progress
      .filter((q: any) => q.video_answer)
      .map((q: any) => {
        // 处理答案文本
        let answerText = q.video_answer?.transcript || '未提供回答';
        let is_correct = false;
        // 如果有answer_data且包含选项，则使用选项文本
        if (q.answer_data && q.answer_data.selected_option_details && q.answer_data.selected_option_details.length > 0) {
          answerText = q.answer_data.selected_option_details
            .map((option: any) => option.option_text)
            .join(', ');
            is_correct = q.answer_data.selected_option_details
            .map((option: any) => option.is_correct)
            .join(', ');

        }
        console.log(q)
        return {
          question: q.question_text || '未提供问题',
          answer: answerText,
          analysis: q.video_answer?.ai_analysis?.comment || '面试官正在评估中',
          score: q.video_answer?.ai_score ? `${q.video_answer.ai_score}分` : '评估中',
          question_form: q.question_form,
          is_correct:is_correct,
          videoUrl: q.video_answer?.video_url || '',
          question_image_url: q.question_image_url || '',
          thumbnail: '/images/video-placeholder.jpg'
        }
      })
  }
  
  // 更新DUV分析
  if (application?.visual_analysis_results && application.visual_analysis_results.photo_results) {
    // 从photo_results中收集所有detections
    const allDetections: any[] = []
    
    application.visual_analysis_results.photo_results.forEach((photo: any) => {
      if (photo.detections && photo.detections.length > 0) {
        photo.detections.forEach((detection: any) => {
          allDetections.push({
            title: detection.feature || '特征分析',
            content: detection.location ? 
              `在${detection.location}发现${detection.feature}${detection.description ? '，' + detection.description : ''}` : 
              detection.feature + (detection.description ? '，' + detection.description : ''),
            score: detection.confidence >= 0.8 ? '确认' : '疑似',
            type: detection.description && detection.description.includes('影响') ? 'negative' : 'neutral'
          })
        })
      }
    })
    
    // 如果有检测结果，更新DUV分析
    if (allDetections.length > 0) {
      candidateInfo.value.duvAnalysis = allDetections
    } else {
      // 如果没有检测结果，提供默认值
      candidateInfo.value.duvAnalysis = [
        {
          title: '未发现特殊特征',
          content: '未在照片中检测到特殊特征',
          score: '正常',
          type: 'positive'
        }
      ]
    }
  } else if (application?.visual_analysis_results && application.visual_analysis_results.detections) {
    // 兼容旧版API格式
    candidateInfo.value.duvAnalysis = application.visual_analysis_results.detections.map((detection: any) => ({
      title: detection.feature || '特征分析',
      content: detection.location ? `在${detection.location}发现${detection.feature}` : detection.feature,
      score: detection.confidence >= 0.8 ? '确认' : '疑似',
      type: 'neutral'
    }))
  } else {
    // 如果没有视觉分析结果，提供默认值
    candidateInfo.value.duvAnalysis = [
      {
        title: '未进行DUV分析',
        content: '未提供DUV分析数据',
        score: '未知',
        type: 'neutral'
      }
    ]
  }
  
  // 更新手势验证和人脸验证图片
  if (posture_photos && posture_photos.length > 0) {
    const leftHandPhotos = posture_photos.filter((p: any) => 
      p.description.includes('left_') || p.description.includes('左手')
    ).map((p: any) => p.photo_url)
    
    if (leftHandPhotos.length > 0) {
      candidateInfo.value.additionalInfo.leftHandGestures.images = leftHandPhotos
    }
    
    const rightHandPhotos = posture_photos.filter((p: any) => 
      p.description.includes('right_') || p.description.includes('右手')
    ).map((p: any) => p.photo_url)
    
    if (rightHandPhotos.length > 0) {
      candidateInfo.value.additionalInfo.rightHandGestures.images = rightHandPhotos
    }
    
    const facePhotos = posture_photos.filter((p: any) => 
      p.description.includes('面部') || 
      (!p.description.includes('left_') && 
       !p.description.includes('right_') &&
       !p.description.includes('左手') && 
       !p.description.includes('右手'))
    ).map((p: any) => p.photo_url)
    
    if (facePhotos.length > 0) {
      candidateInfo.value.additionalInfo.faceVerification.images = facePhotos
    }
  }
  
  // 更新视频记录
  if (interview_progress && interview_progress.length > 0) {
    const videosByCategory: Record<string, any[]> = {}
    
    interview_progress.forEach((q: any) => {
      if (q.video_answer && q.video_answer.video_url) {
        const category = q.question_type_display || '面试视频'
        if (!videosByCategory[category]) {
          videosByCategory[category] = []
        }
        
        videosByCategory[category].push({
          url: q.video_answer.video_url,
          thumbnail: '/images/video-placeholder.jpg',
          description: q.question_text
        })
      }
    })
    
    candidateInfo.value.videoRecords = Object.entries(videosByCategory).map(([category, videos]) => ({
      category,
      videos
    }))
  }
  
  // 更新入职相关信息
  candidateInfo.value.availabilityPeriod = '无特殊情况'
  candidateInfo.value.onboardingTime = '随时可以入职'
}

onMounted(() => {
  console.log('完整URL:', window.location.href)
  console.log('路径:', window.location.pathname)
  console.log('查询字符串:', window.location.search)
  console.log('哈希:', window.location.hash)
  
  fetchApplicationDetail()
})

const evaluationScore = ref<number>(0)
const evaluationComments = ref<string>('')
const formRef = ref<FormInstance>()

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    message.success('评估已提交')
  } catch (error) {
    message.error('请完成所有必填项')
  }
}

const reportTop = ref<HTMLElement | null>(null)

const scrollToTop = () => {
  console.log('尝试滚动到顶部')
  
  // 使用ref引用直接滚动到顶部元素
  if (reportTop.value) {
    reportTop.value.scrollIntoView({ behavior: 'smooth', block: 'start' })
    console.log('使用ref滚动到顶部')
    return
  }
  
  // 如果ref不可用，尝试通过ID查找元素
  const topElement = document.getElementById('report-top')
  if (topElement) {
    topElement.scrollIntoView({ behavior: 'smooth', block: 'start' })
    console.log('使用ID滚动到顶部')
    return
  }
  
  // 如果以上方法都失败，使用之前的备用方法
  // ... 之前的代码 ...
}

const handleShare = () => {
  ElMessage.success('分享链接已复制')
}

const handleDownload = () => {
  ElMessage.success('报告下载中...')
}

const handlePrint = () => {
  ElMessage.success('准备打印报告...')
  setTimeout(() => {
    window.print()
  }, 300)
}

// 添加base64编码的内联图片作为fallback
const fallbackImageBase64Ref = ref('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgZmlsbD0iI2VlZWVlZSIvPjxwYXRoIGQ9Ik03NSA2NUExMCAxMCAwIDAgMSA4NSA3NUExMCAxMCAwIDAgMSA3NSA4NUExMCAxMCAwIDAgMSA2NSA3NUExMCAxMCAwIDAgMSA3NSA2NVoiIGZpbGw9IiNhYWFhYWEiLz48cGF0aCBkPSJNMTIwIDEzNUw5MCAxMDVMNjAgMTM1TDYwIDE0MEwxNDAgMTQwTDE0MCAxMzVMMTIwIDExNVoiIGZpbGw9IiNhYWFhYWEiLz48L3N2Zz4=')

// 简化的图片错误处理函数
const handleImageError = (event: Event) => {
  const target = event.target as HTMLImageElement
  if (target) {
    target.src = fallbackImageBase64Ref.value
    target.onerror = null // 防止无限循环
  }
}

// 修改视频加载和第一帧捕获的函数
const captureVideoFirstFrame = (videoElement: HTMLVideoElement) => {
  // 创建一个一次性的事件监听器，在视频可以播放时捕获第一帧
  const captureFrame = () => {
    try {
      // 确保视频已加载足够的数据
      if (videoElement.readyState >= 2) {
        // 创建canvas元素
        const canvas = document.createElement('canvas')
        canvas.width = videoElement.videoWidth || 320
        canvas.height = videoElement.videoHeight || 240
        
        // 在canvas上绘制视频当前帧
        const ctx = canvas.getContext('2d')
        if (ctx) {
          // 确保视频当前时间设置为开始位置
          videoElement.currentTime = 0.1
          
          // 绘制视频帧到canvas
          ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height)
          
          // 将canvas转换为图片URL
          const thumbnailUrl = canvas.toDataURL('image/jpeg')
          
          // 设置为视频的poster属性
          videoElement.poster = thumbnailUrl
          
          // 清理
          videoElement.removeEventListener('loadeddata', captureFrame)
        }
      }
    } catch (error) {
      console.error('捕获视频第一帧失败:', error)
      // 设置默认缩略图
      videoElement.poster = fallbackImageBase64Ref.value
    }
  }
  
  // 添加事件监听器
  videoElement.addEventListener('loadeddata', captureFrame)
  
  // 如果视频已经加载，立即尝试捕获
  if (videoElement.readyState >= 2) {
    captureFrame()
  }
  
  // 添加错误处理
  videoElement.addEventListener('error', () => {
    console.error('视频加载失败')
    videoElement.poster = fallbackImageBase64Ref.value
  })
  
  // 设置超时，确保即使视频加载缓慢也能显示默认缩略图
  setTimeout(() => {
    if (!videoElement.poster || videoElement.poster === '') {
      videoElement.poster = fallbackImageBase64Ref.value
    }
  }, 3000)
}

// 视频加载完成后的处理函数
const handleVideoLoaded = (event: Event) => {
  const videoElement = event.target as HTMLVideoElement
  if (videoElement) {
    // 确保视频已经加载元数据
    if (videoElement.readyState >= 1) {
      captureVideoFirstFrame(videoElement)
    } else {
      // 如果元数据尚未加载，添加元数据加载事件
      videoElement.addEventListener('loadedmetadata', () => {
        captureVideoFirstFrame(videoElement)
      })
    }
  }
}

// 添加视频错误处理函数
const handleVideoError = (event: Event) => {
  const videoElement = event.target as HTMLVideoElement
  if (videoElement) {
    videoElement.poster = fallbackImageBase64Ref.value
    console.error('视频加载错误')
  }
}
</script>

<template>
  <div class="max-w-4xl mx-auto p-6 relative overflow-y-auto h-full">
    <!-- 添加顶部锚点 -->
    <div id="report-top" ref="reportTop"></div>
    
    <!-- 加载状态 -->
    <a-spin :spinning="loading" tip="加载中...">
      <!-- 页面标题 -->
      <div class="bg-[#1d1e3a] text-white p-4 rounded-t-lg">
        <div class="flex justify-between items-center">
          <div class="text-sm">No.{{ apiData?.application?.report_id || candidateInfo.idNumber }}</div>
          <div class="text-sm">{{ new Date().toLocaleString() }}</div>
        </div>
      </div>

      <div v-if="error" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
        <strong class="font-bold">错误!</strong>
        <span class="block sm:inline">{{ error }}</span>
      </div>

      <div v-else class="bg-white rounded-b-lg shadow-lg p-6">
        <!-- 头部信息 -->
        <div class="flex justify-between items-center mb-8 pb-4 border-b">
          <div class="flex items-center space-x-4">
            <div class="w-20 h-20 bg-gray-200 rounded-lg overflow-hidden">
              <img 
                :src="candidateInfo.additionalInfo.faceVerification.images[0]" 
                alt="头像" 
                class="w-full h-full object-cover"
                @error="handleImageError"
              >
            </div>
            <div>
              <h1 class="text-2xl font-bold">{{ candidateInfo.name }}</h1>
              <p class="text-gray-600">{{ candidateInfo.phoneNumber }}</p>
              <p v-if="apiData?.position" class="text-gray-500 text-sm">
                应聘职位: {{ apiData.position.title }} - {{ apiData.position.department }}
              </p>
            </div>
          </div>
          <div class="text-right">
            <div class="text-4xl font-bold text-yellow-500">{{ candidateInfo.score }}<span class="text-base ml-1">分</span></div>
            <div class="text-sm text-yellow-500">
              {{ candidateInfo.score >= 70 ? '推荐 👍' : candidateInfo.score >= 60 ? '待定 🤔' : '不推荐 👎' }}
            </div>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
          <div>
            <label class="text-gray-600">身份证号</label>
            <div>{{ candidateInfo.idNumber }}</div>
          </div>
          <div>
            <label class="text-gray-600">入职之后，您缺岗的班次时间段是？</label>
            <div>{{ candidateInfo.availabilityPeriod }}</div>
          </div>
          <div>
            <label class="text-gray-600">请问您通过面试之后多久可以入职？</label>
            <div>{{ candidateInfo.onboardingTime }}</div>
          </div>
          <div>
            <label class="text-gray-600">薪资范围</label>
            <div>{{ candidateInfo.salaryRange }}</div>
          </div>
          <div>
            <label class="text-gray-600">建议薪资</label>
            <div class="font-semibold text-blue-600">{{ candidateInfo.suggestedSalary }}</div>
          </div>
        </div>

        <!-- 1. 综合评估 -->
        <div class="mb-8">
          <h2 class="text-xl font-bold mb-6">1. 综合评估</h2>
          <div class="space-y-4">
            <div class="border-b pb-4">
              <div class="flex items-center justify-between mb-2">
                <span class="text-gray-600">录用建议</span>
                <span :class="{
                  'text-green-500': candidateInfo.hireRecommendation?.includes('推荐'),
                  'text-red-500': candidateInfo.hireRecommendation?.includes('不推荐'),
                  'text-yellow-500': !candidateInfo.hireRecommendation?.includes('推荐') && !candidateInfo.hireRecommendation?.includes('不推荐')
                }">{{ candidateInfo.hireRecommendation || '无建议' }}</span>
              </div>
              <p class="text-gray-600 text-sm">{{ candidateInfo.hireReason || '无详细说明' }}</p>
            </div>
            
            <div v-if="candidateInfo.strengths && candidateInfo.strengths.length > 0" class="border-b pb-4">
              <h3 class="font-semibold mb-2">优点</h3>
              <ul class="list-disc pl-5 text-gray-600 text-sm">
                <li v-for="(strength, index) in candidateInfo.strengths" :key="'strength-'+index">
                  {{ strength }}
                </li>
              </ul>
            </div>
            
            <div v-if="candidateInfo.weaknesses && candidateInfo.weaknesses.length > 0" class="border-b pb-4">
              <h3 class="font-semibold mb-2">需改进的地方</h3>
              <ul class="list-disc pl-5 text-gray-600 text-sm">
                <li v-for="(weakness, index) in candidateInfo.weaknesses" :key="'weakness-'+index">
                  {{ weakness }}
                </li>
              </ul>
            </div>
          </div>
        </div>

        <!-- 2. DUV分析评估 -->
        <div class="mb-8">
          <h2 class="text-xl font-bold mb-6">2. DUV分析评估</h2>
          <div class="space-y-4">
            <div v-for="(item, index) in candidateInfo.duvAnalysis" :key="index" class="border-b pb-4">
              <div class="flex items-center justify-between mb-2">
                <span class="text-gray-600">{{ item.title }}</span>
                <span :class="{
                  'text-green-500': item.type === 'positive',
                  'text-red-500': item.type === 'negative',
                  'text-yellow-500': item.type === 'neutral'
                }">{{ item.score }}</span>
              </div>
              <p class="text-gray-600 text-sm">{{ item.content }}</p>
            </div>
          </div>
        </div>

        <!-- 3. 面试记录 -->
        <div class="mb-8">
          <h2 class="text-xl font-bold mb-6">3. 面试记录</h2>
          <div class="space-y-6">
            <div v-for="(record, index) in candidateInfo.interviewRecord" :key="index" class="border-b pb-4">
              <div class="mb-2">
                <h3 class="font-semibold">问题：{{ record.question }}</h3>
                <p class="text-gray-600 mt-2">答案：{{ record.answer }}</p>
                <p class="text-gray-500 mt-2 text-sm" v-if="record.question_form === 0">分析：{{ record.analysis }}</p>
                <img v-if="record.question_form === 3" :src="record.question_image_url" alt="图片" class="w-5/12 h-full object-cover m-auto">
                <div v-if="record.videoUrl" class="mt-4">
                  <div class="video-container">
                    <video
                      class="w-full h-full object-cover"
                      controls
                      :src="record.videoUrl"
                      preload="metadata"
                      :poster="fallbackImageBase64Ref"
                      @loadeddata="handleVideoLoaded"
                      @error="handleVideoError"
                    >
                      您的浏览器不支持视频播放。
                    </video>
                  </div>
                </div>
                
                <div class="mt-2 flex justify-end">
                  <span class="text-blue-500" v-if="record.question_form === 0">得分：{{ record.score }}</span>
                  <span class="text-gray-500" v-else>
                    <span class="text-green-500" v-if="record.is_correct === true || record.is_correct === 'true'">正确</span>
                    <span class="text-red-500" v-else>错误</span>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 4. 视频记录 -->
        <div class="mb-8">
          <h2 class="text-xl font-bold mb-6">4. 视频记录</h2>
          <div class="space-y-8">
            <div v-for="(category, index) in candidateInfo.videoRecords" :key="index">
              <h3 class="text-lg font-semibold mb-4">{{ category.category }}</h3>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div v-for="(video, vIndex) in category.videos" :key="vIndex" class="bg-gray-50 rounded-lg p-4">
                  <div class="video-container">
                    <video
                      class="w-full h-full object-cover"
                      controls
                      :src="video.url"
                      preload="metadata"
                      :poster="fallbackImageBase64Ref"
                      @loadeddata="handleVideoLoaded"
                      @error="handleVideoError"
                    >
                      您的浏览器不支持视频播放。
                    </video>
                  </div>
                  <p class="text-sm text-gray-600 mt-2">{{ video.description }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 其他信息 -->
        <div class="mb-8">
          <h2 class="text-xl font-bold mb-6">5. 其他信息</h2>
          <div class="space-y-6">
            <!-- 验证状态 -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
              <div class="flex items-center space-x-2">
                <span class="text-gray-600">身份证验证:</span>
                <span class="text-green-500">{{ candidateInfo.additionalInfo.idVerification }}</span>
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-gray-600">手机号验证:</span>
                <span class="text-green-500">{{ candidateInfo.additionalInfo.phoneVerification }}</span>
              </div>
            </div>

            <!-- 手势验证 -->
            <div class="mb-6">
              <h3 class="font-semibold mb-4">手势验证</h3>
              <div class="grid grid-cols-2 gap-8">
                <!-- 左手手势 -->
                <div>
                  <h4 class="text-sm font-medium mb-2">左手手势验证</h4>
                  <div class="grid grid-cols-3 gap-2">
                    <div v-for="(image, index) in candidateInfo.additionalInfo.leftHandGestures.images" :key="index"
                      class="aspect-square rounded-lg overflow-hidden bg-gray-100">
                      <img :src="image" alt="左手手势" class="w-full h-full object-cover"
                        @error="handleImageError">
                    </div>
                  </div>
                </div>
                <!-- 右手手势 -->
                <div>
                  <h4 class="text-sm font-medium mb-2">右手手势验证</h4>
                  <div class="grid grid-cols-3 gap-2">
                    <div v-for="(image, index) in candidateInfo.additionalInfo.rightHandGestures.images" :key="index"
                      class="aspect-square rounded-lg overflow-hidden bg-gray-100">
                      <img :src="image" alt="右手手势" class="w-full h-full object-cover"
                        @error="handleImageError">
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 人脸验证 -->
            <div>
              <h3 class="font-semibold mb-4">人脸验证</h3>
              <div class="grid grid-cols-3 md:grid-cols-6 gap-2">
                <div v-for="(image, index) in candidateInfo.additionalInfo.faceVerification.images" :key="index"
                  class="aspect-square rounded-lg overflow-hidden bg-gray-100">
                  <img :src="image" alt="人脸验证" class="w-full h-full object-cover"
                    @error="handleImageError">
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-spin>

    <!-- 悬浮按钮 (Element Plus 版本) -->
    <div class="fixed right-8 bottom-24 flex flex-col space-y-4">
      <el-button
        type="primary"
        style="margin-left: 12px;"
        circle
        @click="handleShare"
      >
        <el-icon><Share /></el-icon>
      </el-button>
      <el-button
        type="primary"
        circle
        @click="handleDownload"
      >
        <el-icon><Download /></el-icon>
      </el-button>
      <el-button
        type="primary"
        circle
        @click="handlePrint"
      >
        <el-icon><Printer /></el-icon>
      </el-button>
      <el-button
        type="primary"
        circle
        @click="scrollToTop"
      >
        <el-icon><ArrowUp /></el-icon>
      </el-button>
    </div>
  </div>
</template>

<style scoped>
.video-container {
  position: relative;
  width: 100%;
  max-width: 240px;
  aspect-ratio: 3/4;
  margin: 0 auto;
  background: #000;
  border-radius: 12px;
  overflow: hidden;
}

.ant-form-item {
  margin-bottom: 24px;
}

.fixed {
  z-index: 100;
}

.ant-btn-circle {
  width: 40px;
  height: 40px;
  padding: 0;
  border-radius: 50%;
}

/* 修改滚动相关样式 */
html, body {
  height: 100%;
  scroll-behavior: smooth;
}

/* 确保主容器可以正常滚动 */
.max-w-4xl {
  position: relative;
  overflow-y: visible;
  min-height: 100%;
}

/* 添加以下样式确保内容可以正常滚动 */
body {
  margin: 0;
  padding: 0;
  overflow-y: auto !important;
}

#app {
  height: auto;
  min-height: 100vh;
  overflow: visible;
}

/* 确保滚动容器不会被阻止滚动 */
.ant-layout, 
.ant-layout-content,
.el-scrollbar__wrap,
.el-scrollbar__view {
  overflow-y: auto !important;
}

@media (max-width: 768px) {
  .max-w-4xl {
    padding: 1rem;
  }
  
  .grid-cols-3 {
    grid-template-columns: 1fr;
  }
  
  .fixed {
    right: 1rem;
  }
}

/* 打印样式 */
@media print {
  /* 打印时隐藏悬浮按钮 */
  .fixed {
    display: none !important;
  }
  
  /* 确保内容完整显示 */
  .max-w-4xl {
    max-width: 100% !important;
    padding: 0 !important;
    margin: 0 !important;
  }
  
  /* 调整页面边距 */
  @page {
    margin: 1cm;
  }
  
  /* 确保背景色和图片打印 */
  * {
    -webkit-print-color-adjust: exact !important;
    color-adjust: exact !important;
    print-color-adjust: exact !important;
  }
  
  /* 避免视频容器在打印时出现问题 */
  .video-container {
    page-break-inside: avoid;
    break-inside: avoid;
  }
  
  /* 确保每个主要部分在新页面开始 */
  h2.text-xl {
    page-break-before: always;
    break-before: always;
  }
  
  /* 第一个标题不需要分页 */
  h2.text-xl:first-of-type {
    page-break-before: avoid;
    break-before: avoid;
  }
}
</style>