<template>
  <div class="camera-container">
    <el-card>
      <!-- 头部控制区 -->
      <div class="header-container">
        <div class="header-title">相机2、3模块</div>
        <div class="header-buttons">
          <el-button type="primary" @click="getVideoList" :disabled="dynamiCameraisInitialized">获取相机2列表</el-button>
          <el-button type="primary" @click="getStereoCameraList"
            :disabled="stereoCameraisInitialized">获取相机3列表</el-button>
        </div>
      </div>

      <!-- 相机参数设置区 -->
      <el-card class="camera-settings" v-if="dynamiCameras.length > 0 || stereoCameras.length > 0">

        <el-tabs v-model="activeTab">
          <!-- 动态相机参数 -->
          <el-tab-pane label="相机2" name="dynami" v-if="dynamiCameras.length > 0">
            <div class="settings-group">
              <el-form inline size="mini" class="compact-form">
                <el-form-item label="分辨率">
                  <el-select v-model="dynamiSettings.resolution" style="width: 140px">
                    <el-option label="2560×1440" value="2560×1440"></el-option>
                    <el-option label="1920×1080" value="1920×1080"></el-option>
                    <el-option label="1280×960" value="1280×960"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="帧率">
                  <el-select v-model="dynamiSettings.fps" style="width: 80px">
                    <el-option label="15" :value="15"></el-option>
                    <el-option label="30" :value="30"></el-option>
                    <el-option label="60" :value="60"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="保存路径">
                  <el-input v-model="dynamiSettings.savePath" placeholder="/images" style="width: 180px"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button-group>
                    <el-button type="primary" @click="initDynamiCameras" icon="el-icon-refresh"
                      :disabled="dynamiCameraisInitialized">初始化</el-button>
                    <el-button type="danger" @click="closeAllCameras" icon="el-icon-close">关闭</el-button>
                  </el-button-group>
                </el-form-item>
                <el-form-item>
                  <el-switch v-model="dynamiSettings.lowFpsMode" active-text="低帧率" inactive-text="原始帧"
                    @change="toggleLowFpsMode" :disabled="!dynamiCameraisInitialized" />
                </el-form-item>
                <el-form-item>
                  <el-tag :type="dynamiCameraisInitialized ? 'success' : 'info'">
                    {{ dynamiCameraisInitialized ? '已初始化' : '未初始化' }}
                  </el-tag>
                </el-form-item>

              </el-form>
            </div>
          </el-tab-pane>

          <!-- 双目相机参数 -->
          <el-tab-pane label="相机3" name="stereo" v-if="stereoCameras.length > 0">
            <div class="settings-group">
              <el-form label-width="120px" size="mini">
                <el-row :gutter="20">
                  <!-- 曝光和增益 -->
                  <el-col :span="12">
                    <el-form-item label="自动曝光/增益">
                      <el-switch v-model="stereoSettings.autoExposure" active-text="自动" inactive-text="手动"
                        @change="handleAutoExposureChange"></el-switch>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" v-if="!stereoSettings.autoExposure">
                    <el-form-item label="曝光">
                      <el-input-number v-model="stereoSettings.exposure" :min="0" :max="100" :step="1" size="mini"
                        style="width: 100px" @change="handleAutoExposureChange"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6" v-if="!stereoSettings.autoExposure">
                    <el-form-item label="增益">
                      <el-input-number v-model="stereoSettings.gain" :min="0" :max="100" :step="1" size="mini"
                        style="width: 100px" @change="handleAutoExposureChange"></el-input-number>
                    </el-form-item>
                  </el-col>

                  <!-- 基础参数 -->
                  <el-col :span="6">
                    <el-form-item label="亮度">
                      <el-input-number v-model="stereoSettings.brightness" :min="0" :max="8" :step="1" size="mini"
                        style="width: 100px" @change="handleBrightnessChange"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="对比度">
                      <el-input-number v-model="stereoSettings.contrast" :min="0" :max="8" :step="1" size="mini"
                        style="width: 100px" @change="handleContrastChange"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="色调">
                      <el-input-number v-model="stereoSettings.hue" :min="0" :max="11" :step="1" size="mini"
                        style="width: 100px" @change="handleHueChange"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="饱和度">
                      <el-input-number v-model="stereoSettings.saturation" :min="0" :max="8" :step="1" size="mini"
                        style="width: 100px" @change="handleSaturationChange"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="锐度">
                      <el-input-number v-model="stereoSettings.sharpness" :min="0" :max="8" :step="1" size="mini"
                        style="width: 100px" @change="handleSharpnessChange"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="伽马值">
                      <el-input-number v-model="stereoSettings.gamma" :min="1" :max="9" :step="1" size="mini"
                        style="width: 100px" @change="handleGammaChange"></el-input-number>
                    </el-form-item>
                  </el-col>

                  <!-- 白平衡 -->
                  <el-col :span="12">
                    <el-form-item label="白平衡">
                      <el-switch v-model="stereoSettings.whiteBalanceAuto" active-text="自动" inactive-text="手动"
                        @change="handleWhiteBalanceChange"></el-switch>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12" v-if="!stereoSettings.whiteBalanceAuto">
                    <el-form-item label="白平衡值">
                      <el-slider v-model="stereoSettings.whiteBalance" :min="28" :max="65" :step="1"
                        style="width: 200px" show-input @change="handleWhiteBalanceChange"></el-slider>
                    </el-form-item>
                  </el-col>

                  <!-- 分辨率和帧率 -->
                  <el-col :span="12">
                    <el-form-item label="分辨率">
                      <el-select v-model="stereoSettings.resolution" style="width: 200px"
                        @change="handleResolutionChange">
                        <el-option v-for="opt in resolutionOptions" :key="opt.value" :label="opt.label"
                          :value="opt.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="帧率">
                      <el-select v-model="stereoSettings.fps" style="width: 200px" @change="handleFpsChange">
                        <el-option v-for="fps in currentFpsOptions" :key="fps" :label="`${fps} FPS`"
                          :value="fps"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>

                  <!-- 深度计算 -->
                  <!-- <el-col :span="12">
                    <el-form-item label="深度计算">
                      <el-switch v-model="stereoSettings.depthEnabled" active-text="开" inactive-text="关"
                        @change="handleDepthEnabledChange"></el-switch>
                    </el-form-item>
                  </el-col> -->
                  <el-col :span="12" v-if="stereoSettings.depthEnabled">
                    <el-form-item label="深度模式">
                      <el-select v-model="stereoSettings.depthMode" style="width: 200px"
                        @change="handleDepthModeChange">
                        <el-option v-for="mode in depthModes" :key="mode" :label="mode" :value="mode"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item>
                  <el-button-group>
                    <el-button type="primary" @click="initStereoCameras"
                      :disabled="stereoCameraisInitialized">初始化</el-button>
                    <el-button type="danger" @click="closeStereoCameras">关闭</el-button>
                  </el-button-group>
                </el-form-item>
                <el-form-item>
                  <el-tag :type="stereoCameraisInitialized ? 'success' : 'info'">
                    {{ stereoCameraisInitialized ? '已初始化' : '未初始化' }}
                  </el-tag>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 视频帧显示区 -->
      <div class="frame-display-area" v-if="dynamiCameras.length > 0 || stereoCameras.length > 0">
        <!-- 相机显示区 -->
        <div class="camera-grid">
          <!-- 动态相机显示区 -->
          <div class="dynami-frames" v-if="dynamiCameras.length > 0">
            <h3 class="frame-section-title">相机2</h3>
            <el-row :gutter="10" class="frame-display-row">
              <el-col :span="8" v-for="camera in dynamiCameras" :key="camera.id" class="frame-display-wrapper">
                <el-card class="frame-display">
                  <div slot="header" class="clearfix" style="padding: 5px;">
                    <div class="frame-title">
                      <span class="camera-id">相机 {{ camera.id }}</span>
                      <span class="camera-spec">({{ camera.width }}×{{ camera.height }} @{{ camera.fps }}fps)</span>
                    </div>
                    <div class="frane-config">
                      <el-popover placement="right" width="400" trigger="click">
                        <div class="config-content">
                          <div class="config-item">
                            <div class="config-item-label">
                              <span class="demonstration">亮度</span>
                            </div>
                            <div class="config-item-slider">
                              <el-slider v-model="camera.brightness" :min="-100" :max="100"
                                @change="handleBrightnessChange(camera)"></el-slider>
                            </div>
                            <div class="config-item-value">
                              {{ camera.brightness }}
                            </div>
                          </div>
                          <div class="config-item">
                            <div class="config-item-label">
                              <span class="demonstration">对比度</span>
                            </div>
                            <div class="config-item-slider">
                              <el-slider v-model="camera.contrast" :min="-100" :max="100" @change="handleContrastChange(camera)"></el-slider>
                            </div>
                            <div class="config-item-value">
                              {{ camera.contrast }}
                            </div>
                          </div>
                          <div class="config-item">
                            <div class="config-item-label">
                              <span class="demonstration">饱和度</span>
                            </div>
                            <div class="config-item-slider">
                              <el-slider v-model="camera.saturation" :min="-100" :max="100"
                                @change="handleSaturationChange(camera)"></el-slider>
                            </div>
                            <div class="config-item-value">
                              {{ camera.saturation }}
                            </div>
                          </div>
                          <div class="config-item">
                            <div class="config-item-label">
                              <span class="demonstration">色调</span>
                            </div>
                            <div class="config-item-slider">
                              <el-slider v-model="camera.hue" :min="-100" :max="100" @change="handleHueChange(camera)"></el-slider>
                            </div>
                            <div class="config-item-value">
                              {{ camera.hue }}
                            </div>
                          </div>
                          <div class="config-item">
                            <div class="config-item-label">
                              <span class="demonstration">增益</span>
                            </div>
                            <div class="config-item-slider">
                              <el-slider v-model="camera.gain" :min="-100" :max="100" @change="handleGainChange(camera)"></el-slider>
                            </div>
                            <div class="config-item-value">
                              {{ camera.gain }}
                            </div>
                          </div>
                          <div class="config-item">
                            <div class="config-item-label">
                              <span class="demonstration">曝光</span>
                            </div>
                            <div class="config-item-slider">
                              <el-slider v-model="camera.exposure" :min="-100" :max="100" @change="handleExposureChange(camera)"></el-slider>
                            </div>
                            <div class="config-item-value">
                              {{ camera.exposure }}
                            </div>
                          </div>
                        </div>
                        <el-button slot="reference" circle icon="el-icon-more-outline" size="mini"></el-button>
                      </el-popover>
                    </div>
                  </div>
                  <div class="frame-header" style="padding: 5px; text-align: center;">
                    <el-select v-model="camera.cameraOrientation" size="mini" style="width: 80px; margin-right: 10px;"
                      @change="configCamera(camera)">
                      <el-option label="不指定" value="不指定"></el-option>
                      <el-option label="右中" value="右中"></el-option>
                      <el-option label="右下" value="右下"></el-option>
                      <el-option label="后中" value="后中"></el-option>
                      <el-option label="后下" value="后下"></el-option>
                      <el-option label="左中" value="左中"></el-option>
                      <el-option label="左下" value="左下"></el-option>
                    </el-select>
                    <!-- <el-button size="mini" type="primary" plain @click="configCamera(camera)">配置</el-button> -->
                    <el-button size="mini" type="primary" plain @click="startStream(camera)">链接</el-button>
                    <el-button size="mini" type="warning" plain @click="stopStream(camera)">断链</el-button>
                  </div>
                  <div v-if="!camera.imageData" style="width: 100%; height: 180px; background: #000;">
                  </div>
                  <canvas v-else :ref="`canvas_${camera.id}`" style="width: 100%; background: #000;"></canvas>
                  <div style="padding: 5px; font-size: 12px; color: #666; min-height: 40px;">
                    <div v-if="camera.statusInfo">{{ camera.statusInfo }}</div>
                    <div v-if="camera.captureLog">{{ camera.captureLog }}</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- 双目相机显示区 -->
          <div class="stereo-frames" v-if="stereoCameras.length > 0">
            <h3 class="frame-section-title">相机3</h3>
            <el-card class="frame-display">
              <div slot="header" class="clearfix" style="padding: 5px;">
                <div class="frame-title">
                  <span class="camera-id">相机3</span>
                </div>
              </div>
              <div class="stereo-layout">
                <div class="stereo-video-area">
                  <div class="stereo-video-grid">
                    <div class="video-panel">
                      <div class="video-label">左目画面</div>
                      <div class="video-frame" v-if="!stereoCamerasImage.leftImage"></div>
                      <canvas v-else ref="canvas-leftImage" class="video-canvas"></canvas>
                    </div>
                    <div class="video-panel">
                      <div class="video-label">右目画面</div>
                      <div class="video-frame" v-if="!stereoCamerasImage.rightImage"></div>
                      <canvas v-else ref="canvas-rightImage" class="video-canvas"></canvas>
                    </div>
                    <div class="video-panel">
                      <div class="video-label">深度画面</div>
                      <div class="video-frame" v-if="!stereoCamerasImage.depthImage"></div>
                      <canvas v-else ref="canvas-depthImage" class="video-canvas"></canvas>
                    </div>
                  </div>
                </div>
                <div class="stereo-control-panel">
                  <div class="control-group">
                    <el-button size="mini" type="primary" @click="getStereoFrame">获取帧</el-button>
                    <el-button size="mini" type="primary" :type="autoRefresh ? 'success' : 'primary'"
                      @click="toggleAutoRefresh">
                      {{ autoRefresh ? '停止自动获取' : '自动获取' }}
                    </el-button>
                    <div class="interval-control">
                      <span class="control-text">刷新间隔:</span>
                      <el-input-number v-model="refreshInterval" size="mini" :min="1" :max="5" :step="1"
                        :disabled="autoRefresh"></el-input-number>
                      <span class="control-text">次/秒</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>

      <!-- 总控制台区域 -->
      <div class="global-controls" v-if="dynamiCameras.length > 0 && stereoCameras.length > 0">
        <el-button-group>
          <el-button type="danger" @click="startAllRecordings">开始录制</el-button>
          <el-button type="info" @click="stopAllRecordings">停止录制</el-button>
        </el-button-group>
        <div class="recording-time" v-if="isRecording">
          <i class="el-icon-video-camera"></i>
          <span>{{ formatRecordingTime() }}</span>
        </div>
      </div>

      <!-- <div class="global-controls" v-if="stereoCameras.length > 0">
        <el-button-group>
          <el-button type="danger" @click="startStereoRecord">开始录制</el-button>
          <el-button type="info" @click="stopStereoRecord">停止录制</el-button>
        </el-button-group>
        <div class="recording-time" v-if="isRecording">
          <i class="el-icon-video-camera"></i>
          <span>{{ formatRecordingTime() }}</span>
        </div>
      </div> -->


      <div v-if="dynamiCameras.length <= 0 && stereoCameras.length <= 0" class="empty-tip">
        <el-empty description="暂无相机，请点击右上角按钮获取相机列表"></el-empty>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  baseURLConsole1
} from '@/utils/url'
import {
  getDynamiCameraList,
  initDynamiCamera,
  getWebSocketLink,
  configDynamiCamera,
  lowDynamiCamera,
  closeDynamiCamera,
  disconnectDynamiCamera,
  startMultiCameraRecode,
  stopMultiCameraRecode,
  setDynamiCameraBrightness,//设置动态相机亮度
  setDynamiCameraContrast,//设置动态相机对比度
  setDynamiCameraSaturation,//设置动态相机饱和度
  setDynamiCameraHue,//设置动态相机色相
  setDynamiCameraGain,//设置动态相机增益
  setDynamiCameraExposure,//设置动态相机曝光
} from '@/api/dynamiCamera.js'
import { binocularCameraMixins } from '@/components/binocularCamera'
import Worker from '@/components/workers/dynamiCamera.worker.js'
export default {
  name: 'DynamiCamera',
  mixins: [binocularCameraMixins],
  data() {
    return {
      activeTab: 'dynami',
      dynamiCameras: [],
      frameCanvas: null,
      dynamiCameraisInitialized: false,
      // 动态相机设置
      dynamiSettings: {
        resolution: '1920x1080',
        fps: 60,
        savePath: 'images/captures',
        lowFpsMode: false
      },
      // 录制相关状态
      isRecording: false,
      recordingStartTime: null,
      recordingTimer: null,
      workers: {} // 存储每个相机对应的worker
    }
  },
  methods: {
    // 获取动态相机列表
    getVideoList() {
      getDynamiCameraList().then(res => {
        console.log(res)
        if (res.data.length > 0) {
          let list = []
          res.data.forEach(item => {
            const worker = new Worker();
            worker.onmessage = (e) => this.handleWorkerMessage(item.camera_id, e.data);
            list.push({
              id: item.camera_id,
              name: item.name,
              width: 0,
              height: 0,
              fps: 0,
              cameraOrientation: '不指定',//方位
              websocket: null,
              reconnectAttempts: 0,//重连次数限制
              imageData: null,
              objectURL: null,
              statusInfo: null,
              captureLog: '等待连接',
              worker, // 存储worker引用
              brightness: 0,//亮度
              contrast: 0,//对比度
              saturation: 0,//饱和度
              hue: 0,//色相
              gain: 0,//增益
              exposure: 0,//曝光
            })
            this.workers[item.camera_id] = worker;
          })
          this.dynamiCameras = list
          this.$message.success(`获取到 ${this.dynamiCameras.length} 个相机2`)
          this.activeTab = 'dynami'
        } else {
          this.$message.error('当前无相机2')
        }
        //查询相机是否已webStock连接。有就关闭
        getWebSocketLink().then(res => {
          if (res.data.connected_cameras.length > 0) {
            res.data.connected_cameras.forEach(item => {
              disconnectDynamiCamera(item)
            })
          }
        })
      })
    },
    //初始化动态相机
    initDynamiCameras() {

      let cameraIds = [];
      const [width, height] = this.dynamiSettings.resolution.split('x')
      //
      //设置相机
      this.dynamiCameras.forEach(camera => {
        cameraIds.push(camera.id)
      })
      console.log(this.dynamiCameras)
      console.log(cameraIds)
      //设置参数
      let param = {
        camera_ids: cameraIds.join(","),
        init_params: {
          resolution_width: parseInt(width),
          resolution_height: parseInt(height),
          fps: this.dynamiSettings.fps
        }
      }
      initDynamiCamera(param).then(res => {
        console.log(res)
        this.dynamiCameras.forEach(camera => {
          let cameraConfig = res.data.initialized_cameras.find(item => item.camera_id == camera.id)
          if (cameraConfig) {
            camera.brightness = cameraConfig.brightness
            camera.contrast = cameraConfig.contrast
            camera.saturation = cameraConfig.saturation
            camera.hue = cameraConfig.hue
            camera.gain = cameraConfig.gain
            camera.exposure = cameraConfig.exposure
          }
          camera.width = parseInt(width)
          camera.height = parseInt(height)
          camera.fps = this.dynamiSettings.fps
        })
        this.dynamiCameraisInitialized = true
        this.$message.success(`初始化所有相机成功`)
      })
    },
    // 关闭所有相机
    closeAllCameras() {

      let cameraIds = [];
      this.dynamiCameras.forEach(camera => {
        cameraIds.push(camera.id);
        if (camera.websocket) {
          camera.websocket.close();
          camera.websocket = null;
        }
      });
      let param = {
        camera_ids: cameraIds.join(',')
      };
      closeDynamiCamera(param).then(res => {
        Object.values(this.workers).forEach(worker => worker.terminate());
        this.workers = {};
        this.dynamiCameras = []
        this.dynamiSettings = {
          resolution: '1920x1080',
          fps: 60,
          savePath: 'images/captures',
          lowFpsMode: false
        },
          this.dynamiCameraisInitialized = false
        this.$message.success(`关闭所有相机成功`)
      })
    },
    // 切换低帧率模式
    toggleLowFpsMode(isLowFps) {

      // 调用接口设置帧率模式
      let cameraIds = [];
      this.dynamiCameras.forEach(camera => {
        cameraIds.push(camera.id)
      });

      let param = {
        camera_ids: cameraIds.join(','),
        fps: isLowFps ? 5 : 25
      };
      lowDynamiCamera(param).then(res => {
        this.$message.success(isLowFps ? '已启用低帧率模式' : '已恢复原始帧率');
      })
    },
    //配置相机
    configCamera(camera) {

      let param = {
        camera_id: camera.id,
        orientation: camera.cameraOrientation
      };
      configDynamiCamera(param).then(res => {
        this.$message.success(`配置相机成功`)
      })
    },
    //处理亮度变化
    handleBrightnessChange(camera) {
      let param = {
        camera_id: camera.id,
        brightness: camera.brightness
      }
      setDynamiCameraBrightness(param).then(res => {
        console.log(res)
        this.$message.success(`设置亮度成功`)
      })
    },
    //处理对比度变化
    handleContrastChange(camera) {
      let param = {
        camera_id: camera.id,
        contrast: camera.contrast
      }
      setDynamiCameraContrast(param).then(res => {
        console.log(res)
        this.$message.success(`设置对比度成功`)
      })
    },
    //处理饱和度变化
    handleSaturationChange(camera) {
      let param = {
        camera_id: camera.id,
        saturation: camera.saturation
      }
      setDynamiCameraSaturation(param).then(res => {
        console.log(res)
        this.$message.success(`设置饱和度成功`)
      })
    },
    //处理色调变化
    handleHueChange(camera) {
      let param = {
        camera_id: camera.id,
        hue: camera.hue
      }
      setDynamiCameraHue(param).then(res => {
        console.log(res)
        this.$message.success(`设置色相成功`)
      })
    },
    //处理增益变化
    handleGainChange(camera) {
      let param = {
        camera_id: camera.id,
        gain: camera.gain
      }
      setDynamiCameraGain(param).then(res => {
        console.log(res)
        this.$message.success(`设置增益成功`)
      })
    },
    //处理曝光变化
    handleExposureChange(camera) {
      let param = {
        camera_id: camera.id,
        exposure: camera.exposure
      }
      setDynamiCameraExposure(param).then(res => {
        console.log(res)
        this.$message.success(`设置曝光成功`)
      })
    },


    //开启WebStock连接
    startStream(camera) {
      camera.worker.postMessage({
        action: 'connect',
        id: camera.id,
        baseURL: baseURLConsole1
      });
    },
    // 渲染图像到canvas
    renderImageToCanvas(camera) {
      if (!camera.imageData) return;
      const canvas = this.$refs[`canvas_${camera.id}`];
      if (!canvas || !canvas[0]) return;

      // 计算保持比例的尺寸
      const containerWidth = canvas[0].parentElement.clientWidth;
      const ratio = camera.imageData.width / camera.imageData.height;
      const height = containerWidth / ratio;

      // 设置canvas尺寸
      canvas[0].width = containerWidth;
      canvas[0].height = height;

      // 绘制图像
      const ctx = canvas[0].getContext('2d');
      ctx.clearRect(0, 0, canvas[0].width, canvas[0].height);
      ctx.drawImage(camera.imageData, 0, 0, canvas[0].width, canvas[0].height);
    },
    stopStream(camera) {
      disconnectDynamiCamera(camera.id).then(res => {
        this.$message.success(`断开链接成功`);
        camera.worker.postMessage({
          action: 'disconnect'
        });

        this.$nextTick(() => {
          camera.imageData = null;
          camera.statusInfo = null;
          camera.captureLog = '等待链接';
        });
      });
    },
    //开始录制
    async startAllRecordings() {
      if (!this.autoRefresh) {
        let hdCameras = [];
        this.dynamiCameras.forEach(camera => {
          hdCameras.push(camera.id);
        });
        let param = {
          hd_cameras: hdCameras.join(','),
          rgbd_cameras: this.stereoCameras[0].camera_id + '',
          user_name: this.$store.getters.username,
          save_dir: this.dynamiSettings.savePath
        }
        console.log(param)

        //低帧率
        if (!this.dynamiSettings.lowFpsMode) {
          this.dynamiSettings.lowFpsMode = true
          await this.toggleLowFpsMode(this.dynamiSettings.lowFpsMode)
        }

        startMultiCameraRecode(param).then(res => {
          this.isRecording = true;
          this.recordingStartTime = new Date();
          this.startRecordingTimer();
          this.$message.success(`开始录制`);
        })
      } else {
        this.$message.warning("请先停止双目相机的获取")
      }

    },
    // 处理worker消息
    handleWorkerMessage(cameraId, data) {
      const camera = this.dynamiCameras.find(c => c.id === cameraId);
      if (!camera) return;

      const { type, message, blob, width, height, performance, encode_time_ms, data_size_kb } = data;

      switch (type) {
        case 'status':
          camera.captureLog = message;
          break;

        case 'error':
          camera.captureLog = message;
          break;

        case 'frame':
          // 使用 createImageBitmap 处理 Blob 数据
          createImageBitmap(blob).then(bitmap => {
            camera.imageData = bitmap;
            this.$nextTick(() => {
              this.renderImageToCanvas(camera);
            });

            // 更新状态信息
            let statusInfo = `分辨率: ${width}x${height}`;
            if (performance) {
              statusInfo += ` | 实际FPS: ${performance.actual_fps} | 目标FPS: ${performance.target_fps}`;
            }
            if (encode_time_ms) {
              statusInfo += ` | 编码耗时: ${encode_time_ms}ms`;
            }
            if (data_size_kb) {
              statusInfo += ` | 数据大小: ${data_size_kb}KB`;
            }
            camera.statusInfo = statusInfo;
          });
          break;
      }
    },
    // 启动录制计时器
    startRecordingTimer() {
      this.recordingTimer = setInterval(() => {
        this.$forceUpdate(); // 强制更新视图以刷新时间显示
      }, 1000);
    },

    // 停止录制计时器
    stopRecordingTimer() {
      if (this.recordingTimer) {
        clearInterval(this.recordingTimer);
        this.recordingTimer = null;
      }
    },

    // 格式化录制时间
    formatRecordingTime() {
      if (!this.recordingStartTime) return '00:00:00';
      const now = new Date();
      const diff = Math.floor((now - this.recordingStartTime) / 1000); // 秒数

      const hours = Math.floor(diff / 3600).toString().padStart(2, '0');
      const minutes = Math.floor((diff % 3600) / 60).toString().padStart(2, '0');
      const seconds = (diff % 60).toString().padStart(2, '0');

      return `${hours}:${minutes}:${seconds}`;
    },
    //停止录制
    stopAllRecordings() {
      let hdCameras = [];
      this.dynamiCameras.forEach(camera => {
        hdCameras.push(camera.id);
      });
      let param = {
        hd_cameras: hdCameras.join(','),//高清相机列表
        rgbd_cameras: this.stereoCameras[0].camera_id + '',//双目相机列表
        user_name: this.$store.getters.username,
        save_dir: this.dynamiSettings.savePath,
      }
      stopMultiCameraRecode(param).then(res => {
        this.isRecording = false;
        this.stopRecordingTimer();
        this.recordingStartTime = null;
        this.$message.success(`停止录制`);
      })
    },
    // 组件销毁前清理
    beforeDestroy() {
      // 关闭所有相机连接
      this.dynamiCameras.forEach(camera => {
        this.stopStream(camera);
      });

      // 终止所有worker
      Object.values(this.workers).forEach(worker => worker.terminate());
      this.workers = {};
    }
  }
}
</script>

<style scoped>
.camera-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  padding-left: 10px;
  border-left: 4px solid #409eff;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.patient-info {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
}

.info-item label {
  width: 80px;
  color: #666;
  font-weight: 500;
}

.camera-control {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.camera-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.camera-item {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  background-color: #fff;
  transition: all 0.3s;
  margin-bottom: 10px;
}

.camera-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.selected-camera {
  border: 2px solid #409eff;
  background-color: #f0f7ff;
}

.clearfix {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  flex-wrap: nowrap;
}

.frame-title {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding: 2px 0;
}

.frane-config {
  text-align: right;
  flex: 1;
}

.config-content {
  width: 400px;
}

.config-item {
  display: flex;
  width: 100%;
  justify-content: column-reverse;
  align-items: center;
}

.config-item-label {
  margin: 5px;
  flex: 3;
}

.config-item-slider {
  margin: 5px;
  flex: 10;
}

.config-item-value {
  margin: 5px;
  flex: 1;
}

.camera-id {
  font-weight: bold;
  margin-right: 8px;
}

.camera-spec {
  font-size: 12px;
  color: #909399;
}

.frame-header {
  padding: 8px 15px;
  display: flex;
  justify-content: center;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.camera-info {
  flex: 1;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-row label {
  width: 70px;
  font-size: 12px;
  color: #666;
  text-align: right;
  padding-right: 8px;
  flex-shrink: 0;
}

.camera-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 5px;
}

.frame-display-row {
  margin-bottom: 20px;
}

.frame-display {
  height: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.frame-display>>>.el-card__header {
  padding: 8px 10px !important;
}

/* 紧凑表单样式 */
.compact-form>>>.el-form-item {
  margin-bottom: 8px;
}

.compact-form>>>.el-form-item__label {
  padding: 0;
  line-height: 28px;
}

.compact-form>>>.el-form-item__content {
  line-height: 28px;
}

.compact-form .el-row {
  margin-bottom: 8px;
}

/* 双目相机显示区样式 */
.stereo-layout {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.stereo-video-area {
  width: 100%;
  margin-bottom: 10px;
}

.stereo-video-grid {
  display: flex;
  gap: 10px;
}

.video-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #111;
  border-radius: 4px;
  overflow: hidden;
}

.video-label {
  color: #fff;
  padding: 8px;
  font-size: 12px;
  text-align: center;
  background: #333;
}

.video-frame {
  height: 180px;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-canvas {
  width: 100%;
  height: 100%;
  background: #000;
}

.stereo-control-panel {
  padding: 10px;
  background: #f5f7fa;
  border-top: 1px solid #ebeef5;
  margin-top: auto;
}

.control-group {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
}

.interval-control {
  display: flex;
  align-items: center;
  gap: 5px;
}

.control-text {
  font-size: 12px;
  color: #666;
}

.control-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
}

.refresh-control {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-left: 15px;
}

.control-label {
  font-size: 12px;
  color: #666;
}

.global-controls {
  margin-top: 20px;
  text-align: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

/* .capture-controls {
  margin-top: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 6px;
} */

.button-group {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-bottom: 15px;
}
</style>
