<template>
  <div class="identity-verify-container">
    <div class="digital-human-container">
      <!-- AI数字人视频/图像显示区域 -->
      <div class="digital-human-video">
        <!-- <image v-if="!videoPlaying" src="/static/images/digital-human-placeholder.jpg" mode="aspectFit"></image> -->
        <video 
          :src="videoUrl"
          id="myVideo"
          ref="videoPlayer" 
          autoplay 
          playsinline
          disablePictureInPicture
          controlsList="nodownload nofullscreen noremoteplayback"
          class="video-player"
          :controls="false"
          @error="handleVideoError"
          @ended="handleVideoEnded"
          @timeupdate="handleTimeUpdate">
        </video>
        
        <!-- 添加字幕覆盖层 -->
        <div class="subtitle-overlay" v-if="currentSubtitle">
          {{ currentSubtitle }}
        </div>
        
        <!-- 添加答题按钮 -->
        <div class="answer-button-container" v-if="showAnswerButton">
          <button class="answer-button" @click="handleAnswerButtonClick">
            开始面试
          </button>
        </div>
      </div>
      
      <!-- 用户摄像头视频显示区域 -->
      <div class="user-camera-container">
        <!-- 在小程序环境中使用camera组件 -->
        <camera v-if="useMiniProgramCameraComponent" 
                device-position="front" 
                flash="off" 
                class="user-camera-video"
                @error="handleCameraError">
        </camera>
        <!-- 在H5/App环境中使用video元素 -->
        <video v-else
          id="userCamera"
          ref="userCameraVideo"
          autoplay
          playsinline
          muted
          class="user-camera-video"
          :controls="false">
        </video>
      </div>
      
      <!-- 字幕/文本覆盖区域 -->
      <!-- <div class="subtitle-overlay" v-if="assistantResponse">
        {{ assistantResponse }}
      </div> -->
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">加载中...</div>
    
    <!-- 控制面板（可选，可以隐藏） -->
    
    <!-- 响应数据（可以设为隐藏，仅用于调试） -->
    <div v-if="showDebugInfo" class="response-container">
      <div v-if="assistantResponse" class="response-item">
        <div class="response-content">
          <span>助手回复: {{ assistantResponse }}</span>
        </div>
      </div>
      <div v-if="audioTranscript" class="response-item">
        <div class="response-content">
          <span>音频转写: {{ audioTranscript }}</span>
        </div>
      </div>
      <div v-for="(item, index) in processedResponses" :key="index" class="response-item">
        <div class="response-content">
          <span v-if="item.role">角色: {{ item.role }}</span>
          <span v-if="item.transcript">文本: {{ item.transcript }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'IdentityVerify',
  data() {
    return {
      loading: false,
      responses: [],
      processedResponses: [],
      assistantResponse: '',
      audioTranscript: '',
      videoPlaying: false,
      showDebugInfo: false, // 设置为true可以显示调试信息
      videoUrl: 'http://121.36.251.245:9000/minlong/0a0b3516-e0bb-4f6c-874c-8aaaca9d7f8f.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minioadmin%2F20250416%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250416T135206Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=4a79bc77f80ae7344f339717dbe505a3b152140251a6b2c76c1fd5c047b39c74', // 用于存储AI数字人视频URL
      showReplayButton: false,
      cameraStream: null, // 存储摄像头流
      cameraError: null, // 存储摄像头错误信息
      useMiniProgramCameraComponent: false, // 添加小程序相机组件标志
      cameraContext: null, // 添加相机上下文
      currentSubtitle: '',
      subtitles: [
        {
          startTime: 0, // 开始时间（秒）
          endTime: 5,   // 结束时间（秒）
          text: '你好，我是本次面试的面试官，欢迎参加本公司的线上面试!'
        },
        {
          startTime: 5,
          endTime: 13,
          text: '面试预计需要15分钟，请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试'
        },
        {
          startTime: 13,
          endTime: 20,
          text: '以免影响本次面试的结果。如果你在面试过程中遇到问题，请与我们的招聘人员联系。'
        }
      ],
      secondVideoSubtitles: [
        {
          startTime: 0,
          endTime: 10,
          text: '请结合您的基本信息与过往履历进行简单的自我介绍，并讲一讲您有哪些优势胜任本岗位：'
        }
      ],
      thirdVideoSubtitles: [
        {
          startTime: 0,
          endTime: 3,
          text: '在工作中，你如何确保个人防护装备的正确使用？'
        }
      ],
      fourthVideoSubtitles: [
        {
          startTime: 0,
          endTime: 3,
          text: '描述一次你与团队合作改善生产流程的经历。'
        }
      ],
      fifthVideoSubtitles: [
        {
          startTime: 0,
          endTime: 6,
          text: '你在团队合作中曾遇到过哪些挑战？如何解决团队内部的分歧？'
        }
      ],
      sixthVideoSubtitles: [
        {
          startTime: 0,
          endTime: 5,
          text: '您已完成本次面试全部题目，请问您对于这个岗位还有什么想要了解的吗？'
        }
      ],
      showAnswerButton: false, // 控制答题按钮显示
      currentVideoIndex: 0, // 当前播放的视频索引
      videoList: [
        'http://121.36.251.245:9000/minlong/0a0b3516-e0bb-4f6c-874c-8aaaca9d7f8f.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minioadmin%2F20250416%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250416T135206Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=4a79bc77f80ae7344f339717dbe505a3b152140251a6b2c76c1fd5c047b39c74', // 第一段视频
        'http://121.36.251.245:9000/minlong/9ab3fd68-a2e9-47a7-a05e-a6e2253ef22c.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minioadmin%2F20250416%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250416T143129Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=7a0ebf1058252b5f76895b31a5293d4781b33ede63d32dce148350846aa20621', // 第二段视频
        'http://121.36.251.245:9000/minlong/69406ce9-8d8e-48aa-ba2f-3b12ea5b6a6c.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minioadmin%2F20250416%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250416T144114Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=a43a06217a63f9bb6af975b1a7aa419b6f8e3d77d8c6c9c67d1070edfe60dc43', // 第三段视频
        'http://121.36.251.245:9000/minlong/1cd448b2-16ea-4565-be25-2cf71d1bf7b2.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minioadmin%2F20250416%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250416T144554Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=6ef5b0b160feab053e7d95952cdac62266d1a1eb48999efb17d7a3c4e0b495ed',
        'http://121.36.251.245:9000/minlong/5a9ad6b2-0de8-48e3-8eb7-141a9bee4a9b.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minioadmin%2F20250416%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250416T145623Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=8a2120a4c6b059d64f90620377fdda2536f9fff9c455d5140210ef35990758c6',
        'http://121.36.251.245:9000/minlong/7aafb07e-ab0d-477e-9124-3263d0b7bf6f.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minioadmin%2F20250416%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250416T145857Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=54ebe67d751c7e44a0f608b26175c9d076685a0e647e7e134cda22bbca2639eb'//结束
      ],
    }
  },
  mounted() {
    /* this.fetchData() */
    this.playDigitalHumanVideo();
    this.initCamera();
  },
  beforeDestroy() {
    // 组件销毁前停止摄像头
    this.stopUserCamera();
  },
  methods: {
    // 初始化相机
    initCamera() {
      // 检查平台
      const systemInfo = uni.getSystemInfoSync();
      
      // 判断是否在小程序环境中
      const isMiniProgram = systemInfo.uniPlatform === 'mp-weixin' || 
                            systemInfo.uniPlatform === 'mp-alipay' || 
                            systemInfo.uniPlatform === 'mp-baidu' ||
                            systemInfo.uniPlatform === 'mp-toutiao';
      
      // 设置标志，控制使用哪种相机组件
      this.useMiniProgramCameraComponent = isMiniProgram;
      
      if (isMiniProgram) {
        // 在小程序环境中使用camera组件
        this.$nextTick(() => {
          // 创建相机上下文
          this.cameraContext = uni.createCameraContext();
        });
      } else {
        // 只在非小程序环境(H5/App)中尝试使用getUserMedia
        this.startUserCamera();
      }
    },
    
    // 启动用户摄像头
    async startUserCamera() {
      try {
        // 首先检查是否在小程序环境中
        const systemInfo = uni.getSystemInfoSync();
        const isMiniProgram = systemInfo.uniPlatform && systemInfo.uniPlatform.startsWith('mp-');
        
        if (isMiniProgram) {
          // 小程序环境不应该调用这个方法，但如果调用了，直接返回
          console.log('小程序环境不支持 getUserMedia API');
          return;
        }
        
        // 检查是否支持getUserMedia (仅在H5/App环境)
        if (!navigator || !navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
          throw new Error('您的浏览器不支持摄像头访问');
        }
        
        // 请求摄像头权限并获取媒体流
        const stream = await navigator.mediaDevices.getUserMedia({
          video: {
            width: { ideal: 200 },
            height: { ideal: 150 },
            facingMode: 'user' // 使用前置摄像头
          },
          audio: true // 不需要音频
        });
        
        this.cameraStream = stream;
        
        // 将摄像头流设置到视频元素
        this.$nextTick(() => {
          if (this.$refs.userCameraVideo) {
            this.$refs.userCameraVideo.srcObject = stream;
          }
        });
      } catch (error) {
        console.error('无法访问摄像头:', error);
        this.cameraError = error.message;
        
        // 根据错误类型显示不同的错误提示
        let errorMessage = '无法访问摄像头，请检查权限设置';
        
        if (error.name === 'NotAllowedError' || error.name === 'PermissionDeniedError') {
          errorMessage = '摄像头访问被拒绝，请在浏览器设置中允许摄像头访问';
        } else if (error.name === 'NotFoundError' || error.name === 'DevicesNotFoundError') {
          errorMessage = '未检测到摄像头设备';
        } else if (error.name === 'NotReadableError' || error.name === 'TrackStartError') {
          errorMessage = '摄像头可能被其他应用占用';
        } else if (error.name === 'OverconstrainedError') {
          errorMessage = '摄像头不满足指定的要求';
        } else if (error.name === 'TypeError' || error.message.includes('SSL')) {
          errorMessage = '请确保在HTTPS环境下访问';
        }
        
        // 显示错误提示
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 3000
        });
        
        // 添加摄像头错误处理
        this.handleCameraError(errorMessage);
      }
    },
    
    // 停止用户摄像头
    stopUserCamera() {
      if (this.cameraStream) {
        // 停止所有轨道
        this.cameraStream.getTracks().forEach(track => {
          track.stop();
        });
        this.cameraStream = null;
      }
    },
    
    async fetchData() {
      this.loading = true
      this.assistantResponse = ''
      this.audioTranscript = ''
      this.processedResponses = []
      try {
        // 使用uni.request代替fetch
        const requestTask = uni.request({
          url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer sk-9e1ec73a7d97493b8613c63f06b6110c'
          },
          data: {
            "model": "qwen-omni-turbo",
            "messages":  [
              {
                "role": "user",
                "content": [
                  {
                    "type": "input_audio",
                    "input_audio": {
                      "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
                      "format": "wav"
                    }
                  },
                  {
                    "type": "text",
                    "text": "这段音频在说什么"
                  }
                ]
              }
            ],
            "stream":true,
            "stream_options":{
                "include_usage":true
            },
            "modalities":["text","audio"],
            "audio":{"voice":"Cherry","format":"wav"}
          },
          success: (res) => {
            console.log('请求成功，响应数据:', res.data);
            // 检查响应数据是否包含多个JSON对象
            if (typeof res.data === 'string' && res.data.includes('data: {')) {
              // 处理包含多个JSON对象的情况
              const chunks = res.data.split('data: ').filter(chunk => chunk.trim() !== '');
              chunks.forEach(chunk => {
                this.handleStreamResponse(chunk);
              });
            } else {
              // 处理单个响应对象的情况
              this.handleStreamResponse(res.data);
            }
            
            // 模拟获取到数字人视频并播放
            this.playDigitalHumanVideo();
          },
          fail: (err) => {
            console.error('请求失败:', err);
          },
          complete: () => {
            this.loading = false;
          }
        });
      } catch (error) {
        console.error('获取数据失败:', error);
        this.loading = false;
      }
    },
    
    handleStreamResponse(data) {
      // 处理流式响应数据
      if (typeof data === 'string') {
        // 处理字符串格式的响应
        if (data === '[DONE]') return;
        
        try {
          // 移除可能存在的换行符和多余空格
          const cleanData = data.trim();
          // 检查是否是有效的JSON字符串
          if (cleanData.startsWith('{') && cleanData.endsWith('}')) {
            const jsonData = JSON.parse(cleanData);
            this.processStreamChunk(jsonData);
          }
        } catch (e) {
          console.error('解析JSON失败:', e, '原始数据:', data);
        }
      } else {
        // 处理对象格式的响应
        this.processStreamChunk(data);
      }
    },
    
    processStreamChunk(chunk) {
      if (chunk.choices && chunk.choices.length > 0) {
        const choice = chunk.choices[0];
        
        // 处理助手回复内容
        if (choice.delta && choice.delta.content) {
          this.assistantResponse += choice.delta.content;
        }
        
        // 处理音频转写内容
        if (choice.delta && choice.delta.audio && choice.delta.audio.transcript) {
          this.audioTranscript += choice.delta.audio.transcript;
        }
        
        // 处理角色和音频转写
        if (choice.delta) {
          const result = {};
          
          if (choice.delta.role) {
            result.role = choice.delta.role;
          }
          
          if (choice.delta.audio && choice.delta.audio.transcript) {
            result.transcript = choice.delta.audio.transcript;
          }
          
          if (Object.keys(result).length > 0) {
            this.processedResponses.push(result);
          }
        }
      }
    },
    
    processResponseData() {
      // 处理返回的数据
      this.processedResponses = this.responses.map(item => {
        const result = {}
        
        // 处理角色信息
        if (item.delta && item.delta.role) {
          result.role = item.delta.role
        }
        
        // 处理音频转写文本
        if (item.delta && item.delta.audio && item.delta.audio.transcript) {
          result.transcript = item.delta.audio.transcript
        }
        
        return result
      }).filter(item => Object.keys(item).length > 0)
    },
    
    // 播放数字人视频
    playDigitalHumanVideo() {
      // 设置第一个视频
      this.videoUrl = this.videoList[this.currentVideoIndex];
      this.videoPlaying = true;
      
      // 使用 uni.createVideoContext 来控制视频
      this.$nextTick(() => {
        const videoContext = uni.createVideoContext('myVideo', this);
        if (videoContext) {
          videoContext.play();
          
          // 设置超时检查，确认视频是否真的在播放
          setTimeout(() => {
            if (this.videoPlaying && this.$refs.videoPlayer) {
              console.log('视频应该正在播放');
            } else {
              console.log('视频可能未成功播放，尝试替代方案');
              this.tryAlternativeVideoPath();
            }
          }, 1000);
        } else {
          console.error('无法创建视频上下文');
          this.tryAlternativeVideoPath();
        }
      });
    },
    
    // 修改 tryAlternativeVideoPath 方法
    tryAlternativeVideoPath() {
      console.log('尝试使用替代路径');
      
      // 尝试不同的路径格式
      const alternativePaths = [
        './static/demo.mp4',
        '../static/demo.mp4',
        'static/demo.mp4',
        '/static/demo.mp4',
        // 添加绝对路径
        `${window.location.origin}/static/demo.mp4`
      ];
      
      // 获取当前路径索引
      const currentPathIndex = alternativePaths.indexOf(this.videoUrl);
      const nextPathIndex = (currentPathIndex + 1) % alternativePaths.length;
      
      // 设置下一个路径
      this.videoUrl = alternativePaths[nextPathIndex];
      console.log('尝试新路径:', this.videoUrl);
      
      this.$nextTick(() => {
        const videoContext = uni.createVideoContext('myVideo', this);
        if (videoContext) {
          videoContext.stop();
          videoContext.play();
          
          // 检查是否成功播放
          setTimeout(() => {
            if (nextPathIndex === alternativePaths.length - 1 && !this.videoPlaying) {
              console.log('所有路径均失败，尝试使用uni.getVideoInfo检查视频');
              this.checkVideoWithAPI();
            }
          }, 1000);
        }
      });
    },
    
    // 添加新方法：使用uni API检查视频
    checkVideoWithAPI() {
      // 尝试使用uni.getVideoInfo API检查视频是否可用
      uni.getVideoInfo({
        src: '/static/demo.mp4',
        success: (res) => {
          console.log('视频信息获取成功:', res);
          // 如果能获取到视频信息，再次尝试播放
          this.videoUrl = '/static/demo.mp4';
          this.$nextTick(() => {
            const videoContext = uni.createVideoContext('myVideo', this);
            if (videoContext) {
              videoContext.play();
            }
          });
        },
        fail: (err) => {
          console.error('视频信息获取失败:', err);
          // 最后尝试使用uni.chooseVideo API
          this.fallbackToLocalVideo();
        }
      });
    },
    
    // 添加新方法：回退到本地视频
    fallbackToLocalVideo() {
      console.log('尝试使用本地视频资源');
      
      // 检查平台
      const platform = uni.getSystemInfoSync().platform;
      if (platform === 'android' || platform === 'ios') {
        // 移动端可以尝试使用本地资源
        this.videoUrl = platform === 'android' ? 'android.resource://package_name/raw/demo' : 'file:///assets/demo.mp4';
        this.$nextTick(() => {
          const videoContext = uni.createVideoContext('myVideo', this);
          if (videoContext) {
            videoContext.play();
          }
        });
      } else {
        // 最终回退到静态图片
        this.videoPlaying = false;
        uni.showToast({
          title: '视频加载失败，显示静态图片',
          icon: 'none'
        });
      }
    },
    
    // 修改 handleVideoError 方法
    handleVideoError(e) {
      console.error('视频加载错误:', e);
      
      // 记录更详细的错误信息
      if (e && e.detail) {
        console.error('详细错误信息:', e.detail);
      }
      
      // 检查视频文件是否存在
      uni.getFileInfo({
        filePath: this.videoUrl.startsWith('/') ? this.videoUrl.substring(1) : this.videoUrl,
        success: (res) => {
          console.log('文件存在，大小:', res.size);
          // 文件存在但播放失败，可能是格式问题
          this.tryDifferentFormat();
        },
        fail: (err) => {
          console.error('文件不存在或无法访问:', err);
          // 尝试不同路径
          this.tryAlternativeVideoPath();
        }
      });
      
      // 如果多次尝试后仍然失败，显示错误信息
      uni.showToast({
        title: '视频加载失败，请检查文件是否存在',
        icon: 'none',
        duration: 2000
      });
    },

    // 添加新方法：尝试不同格式
    tryDifferentFormat() {
      console.log('尝试不同的视频格式');
      
      // 尝试不同的视频格式
      const formats = [
        { ext: 'mp4', mime: 'video/mp4' },
        { ext: 'webm', mime: 'video/webm' },
        { ext: 'ogg', mime: 'video/ogg' },
        { ext: 'mov', mime: 'video/quicktime' }
      ];
      
      // 获取当前文件名（不含扩展名）
      const currentPath = this.videoUrl;
      const basePath = currentPath.substring(0, currentPath.lastIndexOf('.')) || '/static/demo';
      
      // 尝试下一个格式
      let nextFormat = formats.find(f => !currentPath.endsWith(f.ext));
      if (nextFormat) {
        this.videoUrl = `${basePath}.${nextFormat.ext}`;
        console.log('尝试新格式:', this.videoUrl);
        
        this.$nextTick(() => {
          const videoContext = uni.createVideoContext('myVideo', this);
          if (videoContext) {
            videoContext.stop();
            videoContext.play();
          }
        });
      } else {
        // 所有格式都尝试过了，使用内置资源
        this.useBuiltInResource();
      }
    },

    // 添加新方法：使用内置资源
    useBuiltInResource() {
      console.log('尝试使用内置资源');
      
      // 检查平台
      const platform = uni.getSystemInfoSync().platform;
      
      // 根据平台选择合适的视频源
      if (platform === 'windows') {
        // Windows平台特定处理
        // 尝试使用相对于应用根目录的路径
        const appRoot = process.env.UNI_INPUT_DIR || '';
        this.videoUrl = `./static/demo.mp4`;
        
        // 或者尝试使用file://协议
        // this.videoUrl = `file:///${appRoot.replace(/\\/g, '/')}/static/demo.mp4`;
        
        console.log('Windows平台尝试路径:', this.videoUrl);
      } else if (platform === 'android' || platform === 'ios') {
        // 移动端
        this.useNativeVideo();
      } else {
        // Web平台
        // 尝试使用完整URL
        const baseUrl = window.location.origin;
        this.videoUrl = `${baseUrl}/static/demo.mp4`;
        console.log('Web平台尝试URL:', this.videoUrl);
      }
      
      this.$nextTick(() => {
        const videoContext = uni.createVideoContext('myVideo', this);
        if (videoContext) {
          videoContext.play();
        }
      });
    },

    // 添加新方法：使用原生视频能力
    useNativeVideo() {
      console.log('尝试使用原生视频能力');
      
      // 在移动端，可以尝试使用原生视频播放器
      uni.chooseVideo({
        sourceType: ['album'],
        success: (res) => {
          this.videoUrl = res.tempFilePath;
          this.$nextTick(() => {
            const videoContext = uni.createVideoContext('myVideo', this);
            if (videoContext) {
              videoContext.play();
            }
          });
        },
        fail: () => {
          // 如果用户取消选择，回退到静态图片
          this.videoPlaying = false;
          uni.showToast({
            title: '无法加载视频，显示静态图片',
            icon: 'none'
          });
        }
      });
    },

    // 处理视频结束事件
    handleVideoEnded() {
      console.log('视频播放结束');
      this.videoPlaying = false;
      
      // 显示答题按钮
      this.showAnswerButton = true;
    },
    
    // 处理答题按钮点击
    handleAnswerButtonClick() {
      // 隐藏答题按钮
      this.showAnswerButton = false;
      
      // 切换到下一个视频
      this.currentVideoIndex++;
      if (this.currentVideoIndex < this.videoList.length) {
        // 还有下一段视频，播放它
        this.videoUrl = this.videoList[this.currentVideoIndex];
        this.videoPlaying = true;
        
        // 重置当前字幕
        this.currentSubtitle = '';
        
        // 使用 nextTick 确保 DOM 更新后再播放视频
        this.$nextTick(() => {
          const videoContext = uni.createVideoContext('myVideo', this);
          if (videoContext) {
            videoContext.play();
          }
        });
      } else {
        // 所有视频都播放完毕，可以进行下一步操作
        uni.showToast({
          title: '面试完成',
          icon: 'success',
          duration: 2000
        });
        
        // 可以在这里添加面试完成后的逻辑，比如跳转到下一个页面
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/interview-result/interview-result'
          });
        }, 2000);
      }
    },

    // 处理相机错误
    handleCameraError(e) {
      console.error('相机错误:', e);
      
      // 显示错误提示
      uni.showToast({
        title: '相机初始化失败，请检查权限设置',
        icon: 'none'
      });
      
      // 尝试备用选项
      this.tryFallbackOptions();
    },

    // 添加新方法：尝试备用选项
    tryFallbackOptions() {
      // 检查环境
      const systemInfo = uni.getSystemInfoSync();
      
      // 在小程序环境中使用小程序API
      if (systemInfo.uniPlatform === 'mp-weixin' || systemInfo.uniPlatform === 'mp-alipay') {
        this.useMiniProgramCamera();
      } 
      // 在H5环境中显示静态图像
      else {
        this.showStaticCameraPlaceholder();
      }
    },

    // 添加新方法：使用小程序相机API
    useMiniProgramCamera() {
      console.log('尝试使用小程序相机组件');
      // 这里需要在模板中添加小程序相机组件
      // 并设置一个标志来控制显示
      this.useMiniProgramCameraComponent = true;
    },

    // 添加新方法：显示静态图像
    showStaticCameraPlaceholder() {
      console.log('显示静态摄像头占位图');
      // 创建一个图像元素
      const img = document.createElement('img');
      img.src = '/static/images/camera-placeholder.png'; // 确保有这个图片资源
      img.className = 'static-camera-image';
      img.style.width = '100%';
      img.style.height = '100%';
      img.style.objectFit = 'cover';
      
      // 获取容器并添加图像
      const container = this.$refs.userCameraVideo.parentNode;
      container.appendChild(img);
    },

    // 处理视频时间更新事件
    handleTimeUpdate(e) {
      // 获取当前视频播放时间
      const currentTime = e.target.currentTime;
      
      // 根据当前播放的视频索引选择对应的字幕数组
      let currentSubtitles;
      if (this.currentVideoIndex === 0) {
        currentSubtitles = this.subtitles;
      } else if (this.currentVideoIndex === 1) {
        currentSubtitles = this.secondVideoSubtitles;
      }else if (this.currentVideoIndex === 2) {
        currentSubtitles = this.thirdVideoSubtitles;
      }else if (this.currentVideoIndex === 3) {
        currentSubtitles = this.fourthVideoSubtitles;
      }else if (this.currentVideoIndex === 4) {
        currentSubtitles = this.fifthVideoSubtitles;
      }else if (this.currentVideoIndex === 5) {
        currentSubtitles = this.sixthVideoSubtitles;
      }else {
        // 如果有更多视频，可以继续添加条件
        currentSubtitles = [];
      }
      
      // 查找当前时间应该显示的字幕
      const subtitle = currentSubtitles.find(
        sub => currentTime >= sub.startTime && currentTime < sub.endTime
      );
      
      // 更新当前字幕
      this.currentSubtitle = subtitle ? subtitle.text : '';
    },
  }
}
</script>

<style scoped>
.identity-verify-container {
  padding: 0;
  max-width: 100%;
  margin: 0 auto;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.digital-human-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background-color: #f0f0f0;
}

.digital-human-video {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 用户摄像头容器样式 */
.user-camera-container {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 100px;
  height: 150px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  z-index: 20;
  border: 1px solid #fff;
}

/* 用户摄像头视频样式 */
.user-camera-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background-color: #333;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
  outline: none; /* 移除视频获得焦点时的轮廓 */
  -webkit-tap-highlight-color: transparent; /* 移除移动设备上的点击高亮 */
}

/* 隐藏视频控制条 */
video::-webkit-media-controls {
  display: none !important;
}

video::-webkit-media-controls-enclosure {
  display: none !important;
}

video::-webkit-media-controls-panel {
  display: none !important;
}

video::-webkit-media-controls-play-button {
  display: none !important;
}

video::-webkit-media-controls-timeline {
  display: none !important;
}

video::-webkit-media-controls-current-time-display {
  display: none !important;
}

video::-webkit-media-controls-time-remaining-display {
  display: none !important;
}

video::-webkit-media-controls-mute-button {
  display: none !important;
}

video::-webkit-media-controls-volume-slider {
  display: none !important;
}

video::-webkit-media-controls-fullscreen-button {
  display: none !important;
}

.subtitle-overlay {
  position: absolute;
  bottom: 50px;
  left: 0;
  width: 100%;
  padding: 15px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  text-align: center;
  font-size: 16px;
  line-height: 1.5;
  z-index: 10;
  border-radius: 4px;
  max-width: 90%;
  margin: 0 auto;
  left: 5%;
  right: 5%;
}

.control-panel {
  padding: 15px;
  display: flex;
  justify-content: center;
}

.control-button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.loading {
  text-align: center;
  margin: 20px 0;
  font-size: 16px;
}

.response-container {
  margin-top: 20px;
  padding: 0 20px;
  display: none; /* 默认隐藏调试信息 */
}

/* 当showDebugInfo为true时显示 */
.showDebugInfo .response-container {
  display: block;
}

.response-item {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 10px;
  background-color: #f9f9f9;
}

.response-content {
  display: flex;
  flex-direction: column;
}

.answer-button-container {
  position: absolute;
  top: 75%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 20;
}

.answer-button {
  width: 120px;
  height: 120px;
  border-radius: 50%;
 background-color: #6c5ce7; /* 绿色背景，与图片中的颜色类似 */
  color: white;
  font-size: 18px;
  border: none;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  }
  50% {
    transform: scale(1.05);
    box-shadow: 0 8px 15px rgba(0, 0, 0, 0.4);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
  }
}
</style>
