<script setup lang="ts">
import { ref, onMounted, computed } 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, User } 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
    options?: {
      id: number
      option_text: string
      is_correct: boolean
      sort: number
    }[]
    answer_data?: {
      text_answer: string
      selected_options: number[]
      selected_option_details: {
        id: number
        is_correct: boolean
        option_text: 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[]
    }
    comprehensiveVerification: string
    handVerification: string
    handBrightness: string
    handIntegrity: string
    handPoseRecognition: string
  }
  strengths?: string[]
  weaknesses?: string[]
  hireRecommendation?: string
  hireReason?: string
}

interface UserProfile {
  user_info: {
    id: number;
    name: string;
    phone: string;
    age: number;
    birth_date: string;
    gender: number;
    gender_name: string;
    professional_skills: string | null;
    id_card: string;
    status: number;
    examine: string;
    source: string;
    create_datetime: string;
    update_datetime: string;
  };
  profile: {
    political_status: string;
    ethnicity: string;
    height: string;
    weight: string;
    native_place: string;
    household_location: string;
    current_address: string;
    female_status: number;
    female_status_name: string;
    marital_status: number;
    marital_status_name: string;
    has_children: boolean;
    expected_salary: string;
    emergency_contact: string;
    emergency_phone: string;
    specialties: string;
    life_motto: string;
    recruitment_source: number;
    recruitment_source_name: string;
    recruitment_source_detail: string;
  };
  educations: Array<{
    id: number;
    education_type: number;
    education_type_name: string;
    degree: number;
    degree_name: string;
    start_date: string;
    end_date: string;
    school_name: string;
    major: string;
    create_datetime: string;
    update_datetime: string;
  }>;
  family_members: Array<{
    id: number;
    relation: string;
    name: string;
    workplace: string;
    position: string;
    phone: string;
    create_datetime: string;
    update_datetime: string;
  }>;
  trainings: Array<{
    id: number;
    training_name: string;
    institution: string;
    start_date: string;
    end_date: string;
    description: string;
    certificate: string;
    create_datetime: string;
    update_datetime: string;
  }>;
  work_experiences: Array<{
    id: number;
    company_name: string;
    start_date: string;
    end_date: string;
    department: string;
    position: string;
    company_size: number;
    monthly_salary: string;
    supervisor_name: string;
    supervisor_phone: string;
    job_description: string | null;
    achievements: string | null;
    resignation_reason: string | null;
    create_datetime: string;
    update_datetime: string;
  }>;
}

// 首先添加类型定义
interface PhotoResult {
  url: string;
  status: string;
  photo_id: number;
  detections: any[];
  description: string;
  photo_index: number;
  analysis_model: string;
  part_verification: {
    explanation: string;
    is_correct_part: boolean;
  } | null;
  analysis_timestamp: string;
  overall_assessment: string;
}

interface VisualAnalysisResults {
  status: string;
  timestamp: string;
  total_photos: number;
  photo_results: PhotoResult[];
  application_id: number;
  failed_analyses: number;
  successful_analyses: number;
  verification_summary: {
    correct_parts: number;
    total_verified: number;
    incorrect_parts: number;
    all_parts_correct: boolean;
  };
}

// 修改 apiData 的类型定义
interface ApiData {
  applicant?: any;
  application?: any;
  position?: any;
  interview_progress?: any[];
  posture_photos?: any[];
  scoring_summary?: {
    total_score_obtained: number;
    max_possible_score: number;
    answered_scoring_questions_count: number;
    scoring_details: any[];
  };
  required_questions_summary?: {
    all_correct: boolean;
    failed_questions_details: any[];
  };
  visual_analysis_results?: VisualAnalysisResults;
}

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: '',
      options: [],
      answer_data: {
        text_answer: '',
        selected_options: [],
        selected_option_details: []
      }
    },
    {
      question: '',
      answer: '',
      analysis: '',
      score: '',
      videoUrl: '',
      thumbnail: '',
      question_form: 0,
      is_correct: false,
      question_image_url: '',
      options: [],
      answer_data: {
        text_answer: '',
        selected_options: [],
        selected_option_details: []
      }
    }
  ],
  videoRecords: [
    {
      category: '服务态度测评',
      videos: [
        {
          url: '',
          thumbnail: '',
          description: ''
        },
        {
          url: '',
          thumbnail: '',
          description: ''
        }
      ]
    }
  ],
  additionalInfo: {
    idVerification: '通过',
    phoneVerification: '通过',
    leftHandGestures: {
      passed: true,
      images: [
     
      ]
    },
    rightHandGestures: {
      passed: true,
      images: [
       
      ]
    },
    faceVerification: {
      passed: true,
      images: [
       
      ]
    },
    comprehensiveVerification: '通过',
    handVerification: '通过',
    handBrightness: '通过',
    handIntegrity: '通过',
    handPoseRecognition: '通过'
  },
  strengths: [],
  weaknesses: [],
  hireRecommendation: '',
  hireReason: ''
})

// 修改 apiData 的声明
const apiData = ref<ApiData | null>(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
      console.log(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 (position.salary_range && typeof position.salary_range === 'string') {
      // 尝试从薪资范围字符串中提取最小值和最大值
      // 支持多种格式：'5000-8000'、'5,000-8,000'、'5000元-8000元'等
      let min = 0, max = 0;
      
      if (position.salary_range.includes('-')) {
        // 处理范围格式 (例如 "5000-8000")
        const parts = position.salary_range.split('-');
        min = parseInt(parts[0].trim().replace(/[^\d]/g, ''), 10);
        max = parseInt(parts[1].trim().replace(/[^\d]/g, ''), 10);
      } else if (position.salary_range.includes('~')) {
        // 处理波浪线格式 (例如 "5000~8000")
        const parts = position.salary_range.split('~');
        min = parseInt(parts[0].trim().replace(/[^\d]/g, ''), 10);
        max = parseInt(parts[1].trim().replace(/[^\d]/g, ''), 10);
      } else if (position.salary_range.includes('至')) {
        // 处理中文格式 (例如 "5000至8000")
        const parts = position.salary_range.split('至');
        min = parseInt(parts[0].trim().replace(/[^\d]/g, ''), 10);
        max = parseInt(parts[1].trim().replace(/[^\d]/g, ''), 10);
      }
      
      // 如果成功解析出最小值和最大值，则根据分数计算建议薪资
      if (!isNaN(min) && !isNaN(max) && min > 0 && max > 0 && max > min) {
        // 薪资计算逻辑
        // 1. 分数低于60分：给予最低薪资
        // 2. 分数在60-80分之间：给予中等薪资（最低薪资 + 薪资范围的1/3）
        // 3. 分数在80分以上：给予最高薪资
        console.log("score",application.comprehensive_score)
        const score = application.comprehensive_score;
        console.log(score)
        let suggested = min; // 默认给最低薪资
        
        if (score >= 80) {
          // 80分以上给最高薪资
          console.log(max)
          suggested = max;
        } else if (score >= 60) {
          // 60-80分给中等薪资（最低薪资 + 薪资范围的1/3）
          suggested = min + Math.floor((max - min) / 3);
        }else{
          // 低于60分保持最低薪资
          suggested = 0;
        }
        
        // 格式化薪资显示
        if (suggested >= 10000) {
          // 如果大于等于10000，显示为"x.x万"
          const inWan = (suggested / 10000).toFixed(1);
          candidateInfo.value.suggestedSalary = `${inWan}万`;
        } else {
          // 否则直接显示数字
          candidateInfo.value.suggestedSalary = `${suggested}`;
        }
      } else {
        // 如果无法解析薪资范围，则直接使用原始值
        candidateInfo.value.suggestedSalary = position.salary_range;
      }
    } else {
      // 如果没有薪资范围信息，设为面议
      candidateInfo.value.suggestedSalary = '面议';
    }
  } 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 || q.answer_data)
      .map((q: any) => {
        const record: InterviewRecord = {
          question: q.question_text || '未提供问题',
          answer: '',
          analysis: '',
          score: '',
          question_form: q.question_form,
          options: q.options,
          answer_data: q.answer_data
        }

        // 处理视频答案
        if (q.video_answer) {
          record.answer = q.video_answer.transcript || ''
          record.analysis = q.video_answer.ai_analysis?.comment || ''
          record.score = q.video_answer.ai_score ? `${q.video_answer.ai_score}分` : ''
          record.videoUrl = q.video_answer.video_url || ''
        }

        // 处理选择题答案
        if (q.answer_data) {
          record.answer = q.answer_data.text_answer || ''
          record.is_correct = q.answer_data.selected_option_details?.some((opt: any) => opt.is_correct) || false
        }

        // 处理图片题
        if (q.question_form === 3) {
          record.question_image_url = q.question_image_url || ''
        }

        return record
      })
      // 按题目类型排序：视频题(0) -> 图片题(3) -> 选择题(1,2,4)
      .sort((a, b) => {
        // 定义题型优先级
        const getPriority = (questionForm: number) => {
          if (questionForm === 0) return 0  // 视频题最优先
          if (questionForm === 3) return 1  // 图片题次之
          return 2  // 其他题型最后
        }
        
        return getPriority(a.question_form || 0) - getPriority(b.question_form || 0)
      })
  }
  
  // 更新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()
  
  // 确保所有主要部分都有正确的ID
  setTimeout(() => {
    console.log('检查页面ID:');
    ['comprehensive-assessment', 'image-analysis', 'answer-records', 'other-info'].forEach(id => {
      const element = document.getElementById(id);
      console.log(`ID ${id} 存在:`, !!element);
    });
  }, 1000);
  
  // 添加滚动监听
  window.addEventListener('scroll', () => {
    const sections = ['comprehensive-assessment', 'image-analysis', 'answer-records', 'other-info'];
    
    // 找到当前在视口中的部分
    for (const sectionId of sections) {
      const element = document.getElementById(sectionId);
      if (element) {
        const rect = element.getBoundingClientRect();
        if (rect.top <= 150 && rect.bottom >= 150) {
          setActiveTab(sectionId);
          break;
        }
      }
    }
  }, { passive: true });
})

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 = async () => {
  try {
    // 从路由获取参数
    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'
    
    // 显示下载开始的提示
    ElMessage.success('报告下载中...')
    
    // 调用下载接口
    const response = await fetch(`${import.meta.env.VITE_API_URL}/api/system/job/export_application_pdf?application_id=${id || application_id}&tenant_id=${tenant_id}`)
    const result = await response.json()
    
    if (result.code === 2000) {
      // 下载任务创建成功，提示用户去下载中心查看
      ElMessage.success('下载任务已创建，请前往下载中心查看')
    } else {
      // 处理错误情况
      ElMessage.error(result.msg || '下载任务创建失败')
    }
  } catch (error) {
    console.error('创建下载任务失败:', error)
    ElMessage.error('创建下载任务失败，请稍后重试')
  }
}

// 添加类型定义
const originalButtonDisplay: string[] = []

// 修改打印函数
const handlePrint = () => {
  // 保存当前页面滚动位置
  const scrollPosition = window.scrollY
  
  // 临时修改样式以确保所有内容都能打印
  const originalOverflow = document.body.style.overflow
  const originalHeight = document.body.style.height
  
  document.body.style.overflow = 'visible'
  document.body.style.height = 'auto'
  
  // 隐藏不需要打印的元素
  const buttonsToHide = document.querySelectorAll('.fixed')
  
  buttonsToHide.forEach((button, index) => {
    // 添加类型断言
    const buttonElement = button as HTMLElement
    originalButtonDisplay[index] = buttonElement.style.display
    buttonElement.style.display = 'none'
  })
  
  // 延迟执行打印，确保样式已应用
  setTimeout(() => {
    window.print()
    
    // 打印完成后恢复原始样式
    document.body.style.overflow = originalOverflow
    document.body.style.height = originalHeight
    
    // 恢复隐藏的按钮
    buttonsToHide.forEach((button, index) => {
      // 添加类型断言
      const buttonElement = button as HTMLElement
      buttonElement.style.display = originalButtonDisplay[index]
    })
    
    // 恢复滚动位置
    window.scrollTo(0, scrollPosition)
    
    ElMessage.success('打印完成')
  }, 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('视频加载错误')
  }
}

// 修改 DUV 得分解释函数
const getDuvScoreInterpretation = (score: number | undefined): string => {
  if (score === undefined) return '未进行心理测评或数据缺失'
  
  if (score <= 20) {
    return '心理状态健康，情绪稳定、认知正常。候选人在心理测评中表现出稳定的情绪状态和健康的心理特质，适合岗位要求。'
  } else if (score <= 35) {
    return '轻微焦虑或负面情绪，仍具备岗位适应力。候选人在某些方面可能存在轻微的心理压力，但总体上仍保持稳定，基本符合岗位要求。'
  } else if (score <= 55) {
    return '存在一定情绪波动或压力反应。候选人在测评中表现出一定程度的心理压力或情绪波动，建议进一步面谈评估。'
  } else if (score <= 70) {
    return '心理压力较大，可能影响工作稳定性。候选人在测评中表现出较明显的心理压力或情绪不稳定性，建议慎重录用或考虑调岗。'
  } else {
    return '可能存在较严重心理或精神问题。候选人在测评中表现出明显的心理或情绪问题，不建议录用。'
  }
}

// 更新 DUV 得分显示的 CSS 类判断逻辑
const getDuvScoreClass = (score: number | undefined): string => {
  if (score === undefined) return 'text-gray-500'
  
  if (score <= 20) {
    return 'text-green-500' // 优秀
  } else if (score <= 35) {
    return 'text-blue-500' // 良好
  } else if (score <= 55) {
    return 'text-yellow-500' // 一般
  } else if (score <= 70) {
    return 'text-orange-500' // 偏差
  } else {
    return 'text-red-500' // 严重异常
  }
}

// 获取 DUV 得分等级
const getDuvScoreLevel = (score: number | undefined): string => {
  if (score === undefined) return '未知'
  
  if (score <= 20) {
    return '优秀'
  } else if (score <= 35) {
    return '良好'
  } else if (score <= 55) {
    return '一般'
  } else if (score <= 70) {
    return '偏差'
  } else {
    return '严重异常'
  }
}

// 获取录用建议
const getDuvHireRecommendation = (score: number | undefined): string => {
  if (score === undefined) return '无法给出建议'
  
  if (score <= 20) {
    return '建议优先录取'
  } else if (score <= 35) {
    return '可考虑录取'
  } else if (score <= 55) {
    return '建议进一步面谈评估'
  } else if (score <= 70) {
    return '慎重录用或建议调岗'
  } else {
    return '不建议录用'
  }
}

// 添加安全获取分数值的辅助函数
const getSafeScoreValue = (score: number | undefined): number => {
  return score !== undefined ? score : 0
}

const getSafeMaxScoreValue = (maxScore: number | undefined): number => {
  return maxScore !== undefined ? maxScore : 210
}

// 用户个人信息状态
const userProfileData = ref<UserProfile | null>(null);
const userProfileDialogVisible = ref(false);
const userProfileLoading = ref(false);

// 获取用户个人信息
const fetchUserProfile = async () => {
  userProfileLoading.value = true;
  try {
    // 从应用数据中获取用户ID和租户ID
    const userId = apiData.value?.applicant?.id || route.query.user_id || '30';
    const tenantId = route.query.tenant_id || '1';
    
    const response = await fetch(`${import.meta.env.VITE_API_URL}/api/system/wechat/user/profile/get?user_id=${userId}&tenant_id=${tenantId}`);
    const result = await response.json();
    
    if (result.code === 2000) {
      userProfileData.value = result.data;
      userProfileDialogVisible.value = true;
    } else {
      ElMessage.error(result.msg || '获取用户信息失败');
    }
  } catch (error) {
    console.error('获取用户个人信息失败:', error);
    ElMessage.error('获取用户信息失败，请稍后重试');
  } finally {
    userProfileLoading.value = false;
  }
};

// 格式化日期显示
const formatDate = (dateString: string | null | undefined): string => {
  if (!dateString) return '未设置';
  
  try {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
  } catch (e) {
    return dateString;
  }
};

// 处理查看个人信息按钮点击
const handleViewProfile = () => {
  fetchUserProfile();
};

const handleTabClick = (tab: any) => {
  console.log('点击标签:', tab.props.name);
  
  // 尝试多种方法找到目标元素
  const targetId = tab.props.name;
  const element = document.getElementById(targetId);
  
  if (element) {
    // 找到滚动容器 - 可能是document.body, document.documentElement, 或特定容器
    const scrollContainer = document.querySelector('.max-w-4xl') || 
                           document.documentElement || 
                           document.body;
    
    // 计算元素相对于滚动容器的位置
    const containerRect = scrollContainer.getBoundingClientRect();
    const elementRect = element.getBoundingClientRect();
    const relativeTop = elementRect.top - containerRect.top;
    
    // 滚动容器
    if (scrollContainer === document.documentElement || scrollContainer === document.body) {
      window.scrollTo({
        top: window.scrollY + relativeTop - 100, // 减去100px的偏移
        behavior: 'smooth'
      });
    } else {
      scrollContainer.scrollTo({
        top: scrollContainer.scrollTop + relativeTop - 100,
        behavior: 'smooth'
      });
    }
    
    console.log('执行滚动:', window.scrollY + relativeTop - 100);
  } else {
    console.error('未找到目标元素:', targetId);
  }
};

// 添加一个备用的滚动函数，可以通过按钮直接调用
/* const scrollToSection = (sectionId: string) => {
  console.log('尝试滚动到部分:', sectionId);
  const element = document.getElementById(sectionId);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    setTimeout(() => {
      window.scrollBy({ top: -100, behavior: 'smooth' });
    }, 100);
  }
}; */

// 添加到methods部分或直接在setup中定义
const setActiveTab = (sectionId: string) => {
  // 移除所有标签的active类
  document.querySelectorAll('.tab-item').forEach(tab => {
    tab.classList.remove('active');
  });
  
  // 根据sectionId找到对应的标签并添加active类
  const tabMap = {
    'comprehensive-assessment': 0,
    'image-analysis': 1,
    'answer-records': 2,
    'other-info': 3
  };
  
  const index = tabMap[sectionId];
  if (index !== undefined) {
    document.querySelectorAll('.tab-item')[index].classList.add('active');
  }
};

// 修改scrollToSection函数
const scrollToSection = (sectionId: string) => {
  console.log('尝试滚动到部分:', sectionId);
  const element = document.getElementById(sectionId);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'start' });
    setTimeout(() => {
      window.scrollBy({ top: -100, behavior: 'smooth' });
      setActiveTab(sectionId); // 设置激活的标签
    }, 100);
  }
};

// 修改获取手部照片的方法
const getHandPhotos = (hand: 'left' | 'right'): PhotoResult[] => {
  console.log(apiData.value)
  if (!apiData.value?.application?.visual_analysis_results?.photo_results) {
    console.log('No photo results available');
    return Array(3).fill({
      url: '',
      description: `${hand === 'left' ? '左手' : '右手'}手势`,
      part_verification: null
    });
  }

  const photos = apiData.value.application.visual_analysis_results.photo_results.filter((photo: PhotoResult) => {
    const description = photo.description.toLowerCase();
    const searchTerm = hand === 'left' ? '左手' : '右手';
    const matches = description.includes(searchTerm);
    console.log(`Checking photo ${photo.photo_id}: "${description}" for "${searchTerm}" - ${matches}`);
    return matches;
  });

  console.log(`Found ${photos.length} ${hand} hand photos`);

  // 确保始终返回3张图片的数组
  const result = [...photos];
  while (result.length < 3) {
    result.push({
      url: '',
      status: 'empty',
      photo_id: -result.length,
      detections: [],
      description: `${hand === 'left' ? '左手' : '右手'}手势`,
      photo_index: -result.length,
      analysis_model: '',
      part_verification: null,
      analysis_timestamp: '',
      overall_assessment: ''
    });
  }

  return result;
};

// 在script setup部分添加以下函数
const getScoreLevel = (score: number): string => {
  if (score >= 90) return '优秀';
  if (score >= 80) return '良好';
  if (score >= 70) return '中等';
  if (score >= 60) return '及格';
  return '较差';
}

// 添加一个计算属性来获取competency_scores
const competencyScores = computed(() => {
  return apiData.value?.application?.comprehensive_analysis?.competency_scores || {};
})

// 添加一个函数来获取标签的背景色
const getTagColorClass = (tagName: string): string => {
  const colorMap: Record<string, string> = {
    '沟通表达能力': 'bg-blue-100 text-blue-800',
    '工作经历匹配度': 'bg-green-100 text-green-800', 
    '操作技能水平': 'bg-yellow-100 text-yellow-800',
    '质量意识': 'bg-indigo-100 text-indigo-800',
    '安全意识': 'bg-pink-100 text-pink-800',
    '团队协作能力': 'bg-purple-100 text-purple-800',
    '问题解决能力': 'bg-orange-100 text-orange-800',
    '学习能力': 'bg-red-100 text-red-800',
    '初级统筹能力': 'bg-teal-100 text-teal-800'
  };
  return colorMap[tagName] || 'bg-gray-100 text-gray-800';
}
</script>

<template>
  <!-- 修改最外层容器的类，添加背景样式 -->
  <div class="min-h-screen bg-gradient-custom">
    <div class="max-w-4xl mx-auto p-6 relative overflow-y-auto" style="height: 100vh;">
      <!-- 添加顶部锚点 -->
      <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">{{ apiData?.application?.interview_duration_formatted || 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>
                <div class="flex items-center gap-2">
                  <h1 class="text-2xl font-bold">{{ candidateInfo.name }}</h1>
                  <el-button size="small" style="color: #1d1e3a; text-decoration: underline;" type="text" @click="handleViewProfile">
                    个人信息
                  </el-button>
                </div>
                <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>

          <!-- 在标签导航下方添加备用导航按钮 -->
          <!-- <div class="backup-navigation mt-4 mb-6 flex flex-wrap gap-2">
            <el-button size="small" @click="scrollToSection('comprehensive-assessment')">
              综合评估
            </el-button>
            <el-button size="small" @click="scrollToSection('image-analysis')">
              图片分析
            </el-button>
            <el-button size="small" @click="scrollToSection('answer-records')">
              回答记录
            </el-button>
            <el-button size="small" @click="scrollToSection('other-info')">
              其他信息
            </el-button>
          </div> -->

          <!-- 将原来的标签导航移到更上层，并添加固定定位 -->
          <div class="sticky-tabs">
            <div class="custom-tabs">
              <div class="tab-item active" @click="scrollToSection('comprehensive-assessment')">
                <span>综合评估</span>
              </div>
              <div class="tab-item" @click="scrollToSection('image-analysis')">
                <span>图片分析评估</span>
              </div>
              <div class="tab-item" @click="scrollToSection('answer-records')">
                <span>回答记录</span>
              </div>
              <div class="tab-item" @click="scrollToSection('other-info')">
                <span>其他信息</span>
              </div>
            </div>
          </div>

          <!-- 为每个主要章节添加id -->
          <div id="comprehensive-assessment" class="mb-8 pt-4 border-t border-transparent">
            <!-- 1. 综合评估 -->
            <div class="mb-8">
              <h1 class="font-bold mb-6">1. 综合评估</h1>

              <div class="space-y-4">
                <!-- 为每个部分添加 id -->
                <div id="hire-recommendation" class="border-b pb-4">
                  <!-- 录用建议部分的现有代码 -->
                  <div class=" pb-4" style="font-size: 16px;">
                    <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" style="font-size: 14px;">{{ candidateInfo.hireReason || '无详细说明' }}</p>
                  </div>
                </div>
                  <!-- 替换原有的评分详情部分 -->
                <div id="red-line" class="border-b pb-4">
                  <!-- 红线题检测部分的现有代码 -->
                  <div class="flex items-center justify-between mb-2">
                    <span class="text-gray-600" style="color: red;">红线题检测结果</span>
                    <span :class="{
                      'text-green-500': apiData?.required_questions_summary?.all_correct,
                      'text-red-500': apiData?.required_questions_summary && !apiData.required_questions_summary.all_correct
                    }">
                      {{ apiData?.required_questions_summary?.all_correct ? '全部正确' : '存在错误,建议不录用' }}
                    </span>
                  </div>
                  <div v-if="apiData?.required_questions_summary && !apiData.required_questions_summary.all_correct" 
                       class="mt-2 border-l-4 border-red-500 pl-3 bg-red-50 p-2 rounded">
                    <p class="text-red-700 font-medium mb-1">未通过的红线题：</p>
                    <ul v-if="apiData.required_questions_summary.failed_questions_details.length > 0" 
                        class="list-disc pl-5 text-gray-600 text-sm">
                      <li v-for="(question, index) in apiData.required_questions_summary.failed_questions_details" 
                          :key="'failed-'+index">
                        {{ question.question_text || `问题 ${index + 1}` }}
                      </li>
                    </ul>
                    <p v-else class="text-gray-600 text-sm">未提供详细信息</p>
                  </div>
                </div>
                
                <div id="strengths" 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 id="weaknesses" 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 id="duv-analysis" class="border-b pb-4">
                  <!-- DUV心理测评部分的现有代码 -->
                  <div class="flex items-center justify-between mt-4 mb-2">
                    <span class="text-gray-600">DUV 心理测评得分</span>
                    <span :class="getDuvScoreClass(apiData?.scoring_summary?.total_score_obtained)">
                      {{ getSafeScoreValue(apiData?.scoring_summary?.total_score_obtained) }}
                      <span class="ml-2 text-sm">({{ getDuvScoreLevel(apiData?.scoring_summary?.total_score_obtained) }})</span>
                    </span>
                  </div>
                  <p class="text-gray-600 text-sm">
                    {{ getDuvScoreInterpretation(apiData?.scoring_summary?.total_score_obtained) }}
                  </p>
                  <p class="text-sm mt-1" :class="getDuvScoreClass(apiData?.scoring_summary?.total_score_obtained)">
                    <strong>录用建议：</strong> {{ getDuvHireRecommendation(apiData?.scoring_summary?.total_score_obtained) }}
                  </p>
                </div>

                <!-- 替换原有的评分详情部分 -->
                <div id="score-calculation" class="border-b pb-4">
                    <div class="rounded-lg space-y-3">
                      <!-- 动态渲染competency_scores中的标签 -->
                      <div v-for="(score, tagId) in competencyScores" 
                           :key="tagId"
                           class="flex items-start space-x-2" 
                           style="font-size: 14px;">
                        <div :class="[getTagColorClass(score.tag_name), 'px-2 py-1 rounded text-sm whitespace-nowrap']" 
                             style="font-size: 14px;">
                          {{ score.tag_name }}
                        </div>
                        <div class="flex-1">
                          <p class="text-gray-700">
                            {{ getScoreLevel(score.normalized_score) }}
                           <!--  <span class="text-sm text-gray-500 ml-2">({{ score.normalized_score }}分)</span> -->
                          </p>
                        </div>
                      </div>
                      <!-- 人脸一致性 (保留原有的) -->
                    <div class="flex items-start space-x-2" style="font-size: 14px;">
                      <div style="font-size: 14px;" class="bg-purple-100 text-purple-800 px-2 py-1 rounded text-sm whitespace-nowrap">人脸一致性</div>
                      <div class="flex-1">
                        <p class="text-gray-700">{{ apiData?.application?.comprehensive_analysis?.score_calculation?.face_consistency_score || '暂无数据' }}</p>
                      </div>
                    </div>
                    </div>
                  </div>
              </div>
            </div>
          </div>

          <div id="image-analysis" class="mb-8 pt-4 border-t border-transparent">
            <h2 class=" font-bold mb-6">2. 图片分析评估</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>

          <div id="answer-records" class="mb-8 pt-4 border-t border-transparent">
            <h2 class="font-bold mb-6">3. 回答记录</h2>
            <div class="space-y-4">
              <div v-for="(record, index) in candidateInfo.interviewRecord" :key="index" class="bg-gray-50 rounded-lg p-4">
                <!-- 题目标题部分 -->
                 
                <div class="mb-4">
                  <div class="flex items-start space-x-2">
                    <div class="bg-blue-100 text-blue-800 px-2 py-1 rounded text-sm">第{{ index + 1 }}题</div>
                    <div class="flex-1">
                      <h3 class="font-semibold text-gray-800">{{ record.question }}</h3>
                    </div>
                  </div>

                  <!-- 选择题布局 -->
                  <div v-if="record.question_form === 1 || record.question_form === 2 || record.question_form === 4" class="mt-4">
                    <div class="bg-white p-4 rounded-lg">
                      <!-- 显示选项 -->
                      <div v-if="record.options && record.options.length > 0" class="space-y-3">
                        <div v-for="(option, optIndex) in record.options" :key="optIndex"
                             :class="[
                               'p-3 rounded border',
                               record.answer_data?.selected_option_details?.some(
                                 (selected: { id: number }) => selected.id === option.id
                               )
                                 ? 'border-blue-300 bg-blue-50'
                                 : 'border-gray-200'
                             ]">
                          <div class="flex items-center justify-between">
                            <div class="flex-1">
                              <span class="text-gray-700">{{ option.option_text }}</span>
                            </div>
                            <div class="flex items-center space-x-2">
                              <!-- 只在非问卷调查题(question_form !== 4)时显示正确答案和对错状态 -->
                              <template v-if="record.question_form !== 4">
                                <span v-if="option.is_correct" class="text-green-500">✓ 正确答案</span>
                                <span v-if="record.answer_data?.selected_option_details?.some(
                                        (selected: { id: number }) => selected.id === option.id
                                      )"
                                      :class="option.is_correct ? 'text-green-500' : 'text-red-500'">
                                  {{ option.is_correct ? '(已选 - 正确)' : '(已选 - 错误)' }}
                                </span>
                              </template>
                              <!-- 问卷调查题只显示是否选中 -->
                              <template v-else>
                                <span v-if="record.answer_data?.selected_option_details?.some(
                                        (selected: { id: number }) => selected.id === option.id
                                      )"
                                      class="text-blue-500">
                                  (已选)
                                </span>
                              </template>
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <!-- 显示答案状态 -->
                      <div class="mt-4 flex justify-between items-center">
                        <div class="text-gray-600">
                          候选人: {{ record.answer_data?.selected_option_details?.map(
                            (opt: { option_text: string }) => opt.option_text
                          ).join(', ') || '未作答' }}
                        </div>
                        <!-- 只在非问卷调查题时显示对错状态 -->
                        <div v-if="record.question_form !== 4">
                          <span :class="[
                            'px-3 py-1 rounded-full text-sm',
                            record.answer_data?.selected_option_details?.every(
                              (opt: { is_correct: boolean }) => opt.is_correct
                            )
                              ? 'bg-green-100 text-green-800'
                              : 'bg-red-100 text-red-800'
                          ]">
                            {{ record.answer_data?.selected_option_details?.every(
                                 (opt: { is_correct: boolean }) => opt.is_correct
                               ) ? '正确' : '错误' }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 视频问答题布局 -->
                  <div v-else-if="record.question_form === 0" class="mt-4 flex space-x-4">
                   
                    
                    <!-- 右侧答案和评分 -->
                    <div class="w-2/3">
                      <div class="bg-white p-4 rounded-lg">
                        <div class="mb-4">
                          <div class="flex items-start space-x-2">
                            <div class="bg-green-100 text-green-800 px-2 py-1 rounded text-sm">候选人</div>
                            <div class="flex-1">
                              <p class="text-gray-700">{{ record.answer }}</p>
                            </div>
                          </div>
                        </div>
                        
                        <div>
                          <div class="flex items-start space-x-2">
                            <div class="bg-yellow-100 text-yellow-800 px-2 py-1 rounded text-sm">AI评分</div>
                            <div class="flex-1">
                              <p class="text-gray-600 m-0">{{ record.analysis }}</p>
                              <div class="mt-1 text-blue-500">得分：{{ record.score }}</div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                     <!-- 左侧视频播放器 -->
                    <div class="w-1/3">
                      <div class="video-container">
                        <video
                          class="w-full h-full object-cover rounded-lg"
                          controls
                          :src="record.videoUrl"
                          preload="metadata"
                          :poster="fallbackImageBase64Ref"
                          @loadeddata="handleVideoLoaded"
                          @error="handleVideoError"
                        >
                          您的浏览器不支持视频播放。
                        </video>
                      </div>
                    </div>
                  </div>

                  <!-- 图片题布局 -->
                  <div v-else-if="record.question_form === 3" class="mt-4">
                    <div class="grid grid-cols-2 gap-4">
                      <!-- 左侧图片显示 -->
                      <div class="bg-white p-4 rounded-lg">
                        <div class="aspect-w-16 aspect-h-9 rounded-lg overflow-hidden bg-gray-100">
                          <img 
                            :src="record.question_image_url" 
                            alt="题目图片" 
                            class="w-full h-full object-contain"
                            @error="handleImageError"
                          >
                        </div>
                      </div>
                      
                      <!-- 右侧选项和答案 -->
                      <div class="bg-white p-4 rounded-lg">
                        <!-- 显示选项 -->
                        <div v-if="record.options && record.options.length > 0" class="space-y-3">
                          <div v-for="(option, optIndex) in record.options" :key="optIndex"
                               :class="[
                                 'p-3 rounded border',
                                 record.answer_data?.selected_option_details?.some(
                                   (selected: { id: number }) => selected.id === option.id
                                 )
                                   ? 'border-blue-300 bg-blue-50'
                                   : 'border-gray-200'
                               ]">
                            <div class="flex items-center justify-between">
                              <div class="flex-1">
                                <span class="text-gray-700">{{ option.option_text }}</span>
                              </div>
                              <div class="flex items-center space-x-2">
                                <span v-if="option.is_correct" class="text-green-500">✓ 正确答案</span>
                                <span v-if="record.answer_data?.selected_option_details?.some(
                                        (selected: { id: number }) => selected.id === option.id
                                      )"
                                      :class="option.is_correct ? 'text-green-500' : 'text-red-500'">
                                  {{ option.is_correct ? '(已选 - 正确)' : '(已选 - 错误)' }}
                                </span>
                              </div>
                            </div>
                          </div>
                        </div>
                        
                        <!-- 显示答案状态 -->
                        <div class="mt-4 flex justify-between items-center">
                          <div class="text-gray-600">
                            答案: {{ record.answer_data?.selected_option_details?.map(
                              (opt: { option_text: string }) => opt.option_text
                            ).join(', ') || '未作答' }}
                          </div>
                          <div>
                            <span :class="[
                              'px-3 py-1 rounded-full text-sm',
                              record.answer_data?.selected_option_details?.every(
                                (opt: { is_correct: boolean }) => opt.is_correct
                              )
                                ? 'bg-green-100 text-green-800'
                                : 'bg-red-100 text-red-800'
                            ]">
                              {{ record.answer_data?.selected_option_details?.every(
                                   (opt: { is_correct: boolean }) => opt.is_correct
                                 ) ? '正确' : '错误' }}
                            </span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div id="other-info" class="mb-8 pt-4 border-t border-transparent">
            <h2 class="font-bold mb-6">4. 其他信息</h2>
            <div class="space-y-6">
              <!-- 验证状态列表 -->
              <div class="space-y-2">
                <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 class="flex items-center space-x-2">
                  <span class="text-gray-600">综合A类评估:</span>
                  <span class="text-green-500">{{ candidateInfo.additionalInfo.comprehensiveVerification }}</span>
                </div>
                <div class="flex items-center space-x-2">
                  <span class="text-gray-600">综合B类评估:</span>
                  <span class="text-green-500">{{ candidateInfo.additionalInfo.comprehensiveVerification }}</span>
                </div> -->
              </div>

              <!-- 手部综合检测 -->
              <div class="space-y-4">
                <div class="flex items-center space-x-2">
                  <span class="text-gray-600">手部综合检测:</span>
                  <span class="text-green-500">{{ candidateInfo.additionalInfo.handVerification }}</span>
                </div>
                
                <!-- 手部检测详细信息 -->
               <!--  <div class="pl-4 space-y-2">
                  <div class="flex items-center space-x-2">
                    <span class="text-gray-600">手指灵活度:</span>
                    <span class="text-green-500">{{ candidateInfo.additionalInfo.handBrightness }}</span>
                  </div>
                  <div class="flex items-center space-x-2">
                    <span class="text-gray-600">手指完整度:</span>
                    <span class="text-green-500">{{ candidateInfo.additionalInfo.handIntegrity }}</span>
                  </div>
                  <div class="flex items-center space-x-2">
                    <span class="text-gray-600">手部姿态纹身:</span>
                    <span class="text-green-500">{{ candidateInfo.additionalInfo.handPoseRecognition }}</span>
                  </div>
                </div> -->

                <!-- 手势验证图片展示 -->
                <div class="grid grid-cols-2 gap-8 mt-4">
                  <!-- 左手验证结果 -->
                  <div>
                    <h4 class="text-gray-600 mb-2">左手手势验证</h4>
                    <div class="grid grid-cols-3 gap-2">
                      <div v-for="(photo, index) in getHandPhotos('left')" 
                           :key="index"
                           class="relative aspect-square rounded-lg overflow-hidden bg-gray-100"
                           :class="{'border-2': photo.part_verification, 
                                   'border-green-500': photo.part_verification?.is_correct_part,
                                   'border-red-500': photo.part_verification && !photo.part_verification.is_correct_part}"
                      >
                        <!-- 使用 el-tooltip 包裹内容 -->
                        <el-tooltip
                          v-if="photo.part_verification && !photo.part_verification.is_correct_part"
                          :content="photo.part_verification.explanation || '未提供失败原因'"
                          placement="top"
                          effect="dark"
                          :show-after="200"
                        >
                          <div class="w-full h-full">
                            <img :src="photo.url" 
                                 :alt="photo.description" 
                                 class="w-full h-full object-cover"
                                 @error="handleImageError">
                            
                            <!-- 底部状态显示 -->
                            <div v-if="photo.part_verification"
                                 class="absolute bottom-0 left-0 right-0 py-1 px-2 text-xs text-center text-white z-10"
                                 :class="{
                                   'bg-green-500 bg-opacity-90': photo.part_verification.is_correct_part,
                                   'bg-red-500 bg-opacity-90': !photo.part_verification.is_correct_part
                                 }">
                              {{ photo.part_verification.is_correct_part ? '通过' : '未通过' }}
                            </div>
                          </div>
                        </el-tooltip>
                        
                        <!-- 如果不需要显示tooltip，直接显示图片 -->
                        <template v-else>
                          <img :src="photo.url" 
                               :alt="photo.description" 
                               class="w-full h-full object-cover"
                               @error="handleImageError">
                          
                          <!-- 底部状态显示 -->
                          <div v-if="photo.part_verification"
                               class="absolute bottom-0 left-0 right-0 py-1 px-2 text-xs text-center text-white z-10"
                               :class="{
                                 'bg-green-500 bg-opacity-90': photo.part_verification.is_correct_part,
                                 'bg-red-500 bg-opacity-90': !photo.part_verification.is_correct_part
                               }">
                            {{ photo.part_verification.is_correct_part ? '通过' : '未通过' }}
                          </div>
                        </template>
                      </div>
                    </div>
                  </div>

                  <!-- 右手验证结果 -->
                  <div>
                    <h4 class="text-gray-600 mb-2">右手手势验证</h4>
                    <div class="grid grid-cols-3 gap-2">
                      <div v-for="(photo, index) in getHandPhotos('right')" 
                           :key="index"
                           class="relative aspect-square rounded-lg overflow-hidden bg-gray-100"
                           :class="{'border-2': photo.part_verification, 
                                   'border-green-500': photo.part_verification?.is_correct_part,
                                   'border-red-500': photo.part_verification && !photo.part_verification.is_correct_part}"
                      >
                        <!-- 使用 el-tooltip 包裹内容 -->
                        <el-tooltip
                          v-if="photo.part_verification && !photo.part_verification.is_correct_part"
                          :content="photo.part_verification.explanation || '未提供失败原因'"
                          placement="top"
                          effect="dark"
                          :show-after="200"
                        >
                          <div class="w-full h-full">
                            <img :src="photo.url" 
                                 :alt="photo.description" 
                                 class="w-full h-full object-cover"
                                 @error="handleImageError">
                            
                            <!-- 底部状态显示 -->
                            <div v-if="photo.part_verification"
                                 class="absolute bottom-0 left-0 right-0 py-1 px-2 text-xs text-center text-white z-10"
                                 :class="{
                                   'bg-green-500 bg-opacity-90': photo.part_verification.is_correct_part,
                                   'bg-red-500 bg-opacity-90': !photo.part_verification.is_correct_part
                                 }">
                              {{ photo.part_verification.is_correct_part ? '通过' : '未通过' }}
                            </div>
                          </div>
                        </el-tooltip>
                        
                        <!-- 如果不需要显示tooltip，直接显示图片 -->
                        <template v-else>
                          <img :src="photo.url" 
                               :alt="photo.description" 
                               class="w-full h-full object-cover"
                               @error="handleImageError">
                          
                          <!-- 底部状态显示 -->
                          <div v-if="photo.part_verification"
                               class="absolute bottom-0 left-0 right-0 py-1 px-2 text-xs text-center text-white z-10"
                               :class="{
                                 'bg-green-500 bg-opacity-90': photo.part_verification.is_correct_part,
                                 'bg-red-500 bg-opacity-90': !photo.part_verification.is_correct_part
                               }">
                            {{ photo.part_verification.is_correct_part ? '通过' : '未通过' }}
                          </div>
                        </template>
                      </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="handleViewProfile"
        >
          <el-icon><User /></el-icon>
        </el-button>
        <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>
  </div>

  <!-- 用户个人信息弹窗 -->
  <el-dialog
    v-model="userProfileDialogVisible"
    title="个人详细信息"
    width="80%"
    :close-on-click-modal="false"
    class="user-profile-dialog"
  >
    <el-scrollbar height="70vh">
      <el-spin :spinning="userProfileLoading">
        <div v-if="userProfileData" class="user-profile-content">
          <!-- 基本信息 -->
          <div class="profile-section">
            <h3 class="section-title">基本信息</h3>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="姓名">{{ userProfileData.user_info.name }}</el-descriptions-item>
              <el-descriptions-item label="手机号">{{ userProfileData.user_info.phone }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{ userProfileData.user_info.age }}岁</el-descriptions-item>
              <el-descriptions-item label="出生日期">{{ formatDate(userProfileData.user_info.birth_date) }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ userProfileData.user_info.gender_name }}</el-descriptions-item>
              <el-descriptions-item label="身份证号">{{ userProfileData.user_info.id_card }}</el-descriptions-item>
            </el-descriptions>
          </div>
          
          <!-- 个人资料 -->
          <div class="profile-section">
            <h3 class="section-title">个人资料</h3>
            <el-descriptions :column="3" border>
              <el-descriptions-item label="政治面貌">{{ userProfileData.profile.political_status }}</el-descriptions-item>
              <el-descriptions-item label="民族">{{ userProfileData.profile.ethnicity }}</el-descriptions-item>
              <el-descriptions-item label="身高">{{ userProfileData.profile.height }}cm</el-descriptions-item>
              <el-descriptions-item label="体重">{{ userProfileData.profile.weight }}kg</el-descriptions-item>
              <el-descriptions-item label="籍贯">{{ userProfileData.profile.native_place }}</el-descriptions-item>
              <el-descriptions-item label="户口所在地">{{ userProfileData.profile.household_location }}</el-descriptions-item>
              <el-descriptions-item label="现居地址">{{ userProfileData.profile.current_address }}</el-descriptions-item>
              <el-descriptions-item label="婚姻状况">{{ userProfileData.profile.marital_status_name }}</el-descriptions-item>
              <el-descriptions-item label="是否有子女">{{ userProfileData.profile.has_children ? '是' : '否' }}</el-descriptions-item>
              <el-descriptions-item label="期望薪资">{{ userProfileData.profile.expected_salary }}</el-descriptions-item>
              <el-descriptions-item label="紧急联系人">{{ userProfileData.profile.emergency_contact }}</el-descriptions-item>
              <el-descriptions-item label="紧急联系电话">{{ userProfileData.profile.emergency_phone }}</el-descriptions-item>
              <el-descriptions-item label="特长">{{ userProfileData.profile.specialties }}</el-descriptions-item>
              <el-descriptions-item label="人生格言">{{ userProfileData.profile.life_motto }}</el-descriptions-item>
              <el-descriptions-item label="招聘来源">{{ userProfileData.profile.recruitment_source_name }}</el-descriptions-item>
            </el-descriptions>
          </div>
          
          <!-- 教育经历 -->
          <div class="profile-section" v-if="userProfileData.educations && userProfileData.educations.length > 0">
            <h3 class="section-title">教育经历</h3>
            <div v-for="(edu, index) in userProfileData.educations" :key="`edu-${index}`" class="mb-4">
              <el-descriptions :column="3" border>
                <el-descriptions-item label="学历类型">{{ edu.education_type_name }}</el-descriptions-item>
                <el-descriptions-item label="学历">{{ edu.degree_name }}</el-descriptions-item>
                <el-descriptions-item label="时间段">{{ formatDate(edu.start_date) }} 至 {{ formatDate(edu.end_date) }}</el-descriptions-item>
                <el-descriptions-item label="学校名称">{{ edu.school_name }}</el-descriptions-item>
                <el-descriptions-item label="专业">{{ edu.major }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
          
          <!-- 工作经历 -->
          <div class="profile-section" v-if="userProfileData.work_experiences && userProfileData.work_experiences.length > 0">
            <h3 class="section-title">工作经历</h3>
            <div v-for="(work, index) in userProfileData.work_experiences" :key="`work-${index}`" class="mb-4">
              <el-descriptions :column="3" border>
                <el-descriptions-item label="公司名称">{{ work.company_name }}</el-descriptions-item>
                <el-descriptions-item label="时间段">{{ formatDate(work.start_date) }} 至 {{ formatDate(work.end_date) }}</el-descriptions-item>
                <el-descriptions-item label="部门">{{ work.department }}</el-descriptions-item>
                <el-descriptions-item label="职位">{{ work.position }}</el-descriptions-item>
                <el-descriptions-item label="公司规模">{{ work.company_size }}人</el-descriptions-item>
                <el-descriptions-item label="月薪">{{ work.monthly_salary }}</el-descriptions-item>
                <el-descriptions-item label="主管姓名">{{ work.supervisor_name }}</el-descriptions-item>
                <el-descriptions-item label="主管电话">{{ work.supervisor_phone }}</el-descriptions-item>
                <el-descriptions-item label="工作描述" :span="3">{{ work.job_description || '无' }}</el-descriptions-item>
                <el-descriptions-item label="工作成就" :span="3">{{ work.achievements || '无' }}</el-descriptions-item>
                <el-descriptions-item label="离职原因" :span="3">{{ work.resignation_reason || '无' }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
          
          <!-- 培训经历 -->
          <div class="profile-section" v-if="userProfileData.trainings && userProfileData.trainings.length > 0">
            <h3 class="section-title">培训经历</h3>
            <div v-for="(training, index) in userProfileData.trainings" :key="`training-${index}`" class="mb-4">
              <el-descriptions :column="3" border>
                <el-descriptions-item label="培训名称">{{ training.training_name }}</el-descriptions-item>
                <el-descriptions-item label="培训机构">{{ training.institution }}</el-descriptions-item>
                <el-descriptions-item label="时间段">{{ formatDate(training.start_date) }} 至 {{ formatDate(training.end_date) }}</el-descriptions-item>
                <el-descriptions-item label="培训描述" :span="3">{{ training.description }}</el-descriptions-item>
                <el-descriptions-item label="证书">{{ training.certificate }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
          
          <!-- 家庭成员 -->
          <div class="profile-section" v-if="userProfileData.family_members && userProfileData.family_members.length > 0">
            <h3 class="section-title">家庭成员</h3>
            <div v-for="(member, index) in userProfileData.family_members" :key="`family-${index}`" class="mb-4">
              <el-descriptions :column="3" border>
                <el-descriptions-item label="关系">{{ member.relation }}</el-descriptions-item>
                <el-descriptions-item label="姓名">{{ member.name }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ member.phone }}</el-descriptions-item>
                <el-descriptions-item label="工作单位">{{ member.workplace }}</el-descriptions-item>
                <el-descriptions-item label="职位">{{ member.position }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </div>
        <div v-else class="empty-data">
          <el-empty description="暂无个人信息数据"></el-empty>
        </div>
      </el-spin>
    </el-scrollbar>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="userProfileDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
/* 修改背景渐变样式,使用蓝色小精灵的配色 */
.bg-gradient-custom {
  background: linear-gradient(180deg, #0066cc 0%, #3399ff 100%);
  min-height: 100vh;
  width: 100%;
  position: relative;
  overflow-y: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

/* 修改星星背景效果,使其更符合蓝色主题 */
.bg-gradient-custom::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(2px 2px at 20px 30px, #ffffff30 50%, transparent 100%),
    radial-gradient(2px 2px at 40px 70px, #ffffff30 50%, transparent 100%),
    radial-gradient(2px 2px at 50px 160px, #ffffff30 50%, transparent 100%),
    radial-gradient(2px 2px at 90px 40px, #ffffff30 50%, transparent 100%),
    radial-gradient(2px 2px at 130px 80px, #ffffff30 50%, transparent 100%),
    radial-gradient(2px 2px at 160px 120px, #ffffff30 50%, transparent 100%);
  background-repeat: repeat;
  background-size: 200px 200px;
  opacity: 0.6;
  z-index: 0;
  animation: twinkle 4s infinite alternate;
}

/* 添加闪烁动画效果 */
@keyframes twinkle {
  0% {
    opacity: 0.4;
  }
  100% {
    opacity: 0.7;
  }
}

/* 修改页面标题区域样式 */
:deep(.bg-\[#1d1e3a\]) {
  background-color: #004d99 !important; /* 深蓝色标题背景 */
}

/* 修改按钮悬浮效果 */
.el-button--primary {
  background-color: #0066cc !important;
  border-color: #0066cc !important;
}

.el-button--primary:hover {
  background-color: #3399ff !important;
  border-color: #3399ff !important;
  transform: scale(1.05);
  transition: all 0.3s ease;
}

/* 修改内容区域的样式 */
.max-w-4xl {
  position: relative;
  overflow-y: visible;
  min-height: 100%;
  z-index: 1;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.max-w-4xl::-webkit-scrollbar {
  display: none;
}

.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;
  overflow-y: auto !important; /* 强制允许垂直滚动 */
}

/* 确保主容器可以正常滚动 */
.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;
  }

  .bg-gradient-custom {
    background: none !important;
  }
  
  .bg-gradient-custom::before {
    display: none !important;
  }
}

/* 确保内容区域可以正常滚动 */
.max-w-4xl {
  position: relative;
  overflow-y: auto;
  height: 100%;
  padding-bottom: 100px; /* 为底部按钮留出空间 */
}

/* 添加用户个人信息弹窗样式 */
.user-profile-content {
  padding: 0 16px;
}

.profile-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
  color: #0066cc;
}

:deep(.el-descriptions__label) {
  background-color: #f5f7fa;
  font-weight: 500;
}

:deep(.el-descriptions__content) {
  padding: 12px 16px;
}

.empty-data {
  padding: 40px 0;
  display: flex;
  justify-content: center;
}

/* 确保弹窗内容可以滚动 */
:deep(.el-dialog__body) {
  padding: 16px 0;
  max-height: 70vh;
  overflow: hidden;
}

/* 修改弹窗标题样式 */
:deep(.el-dialog__header) {
  padding: 16px 20px;
  background-color: #0066cc;
  margin-right: 0;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

/* 修改弹窗底部样式 */
:deep(.el-dialog__footer) {
  padding: 12px 20px;
  border-top: 1px solid #ebeef5;
}

/* 添加标签样式 */
:deep(.el-tabs__nav-wrap) {
  background-color: white;
  border-radius: 8px;
  padding: 4px;
}

:deep(.el-tabs__item) {
  color: #606266;
  font-size: 14px;
  padding: 0 20px;
  height: 36px;
  line-height: 36px;
  transition: all 0.3s;
}

:deep(.el-tabs__item.is-active) {
  color: #0066cc;
  font-weight: 500;
}

:deep(.el-tabs__active-bar) {
  background-color: #0066cc;
}

/* 确保内容区域有足够的滚动空间 */
.space-y-4 > div {
  scroll-margin-top: 120px; /* 增加滚动边距，避免被固定导航遮挡 */
}

/* 主要章节的滚动定位调整 */
#comprehensive-assessment,
#image-analysis,
#answer-records,
#other-info {
  scroll-margin-top: 120px; /* 增加滚动边距 */
  padding-top: 20px; /* 添加顶部内边距，使内容更清晰可见 */
  border-top: 1px solid transparent; /* 添加透明边框，帮助滚动定位 */
}

/* 打印时隐藏固定导航 */
@media print {
  .sticky-tabs {
    display: none !important;
  }
}

/* 确保固定导航不会干扰滚动 */
.sticky-tabs {
  position: sticky;
  top: -24px;
  z-index: 10;
  background-color: white;
  padding: 10px 0;
  margin-bottom: 20px;
  /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); */
}

/* 自定义标签样式 - 匹配图片中的深色标签 */
:deep(.custom-tabs) {
  background-color: #1d1e3a;
  border-radius: 0;
}

:deep(.custom-tabs .el-tabs__header) {
  margin: 0;
  border: none;
  background-color: #1d1e3a;
}

:deep(.custom-tabs .el-tabs__nav) {
  border: none;
  background-color: #1d1e3a;
}

:deep(.custom-tabs .el-tabs__item) {
  color: white;
  font-size: 14px;
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
  border: none;
  background-color: transparent;
}

:deep(.custom-tabs .el-tabs__item.is-active) {
  color: white;
  font-weight: 500;
  background-color: #4e4e8b;
}

:deep(.custom-tabs .el-tabs__item:hover) {
  color: white;
  background-color: #4e4e8b;
}

:deep(.custom-tabs .el-tabs__nav-wrap::after) {
  display: none;
}

.sticky-tabs {
  position: sticky;
  top: -25px;
  z-index: 10;
  margin-bottom: 20px;
  
}

.custom-tabs {
  display: flex;
  background-color: #1d1e3a;
  width: 100%;
  overflow-x: auto;
  white-space: nowrap;
  border-radius: 5px;
}

.tab-item {
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
  color: white;
  font-size: 14px;
  cursor: pointer;
  text-align: center;
  transition: background-color 0.3s;
  width: 25%;
  /* flex: 1; */
  min-width: max-content;
}

.tab-item:hover {
  background-color: #4e4e8b;
}

.tab-item.active {
  background-color: #4e4e8b;
  font-weight: 500;
}

/* 确保在移动设备上也能正常滚动 */
@media (max-width: 768px) {
  .custom-tabs {
    justify-content: flex-start;
  }
  
  .tab-item {
    flex: 0 0 auto;
  }
}

/* 添加新的样式 */
.group {
  position: relative;
}

.group:hover .group-hover\:opacity-100 {
  opacity: 1;
}

.transition-opacity {
  transition: opacity 0.2s ease-in-out;
}
</style>