<template>
  <view class="camera-container">
    <!-- camera组件，全屏显示 -->
    <camera class="camera" device-position="back" flash="off" @error="error" style="width: 200px;height: 200px"></camera>
    
    <!-- 自定义底部操作栏 -->
    <view class="controls">
      <button @tap="switchCamera">切换摄像头</button>
      <!-- 长按录制视频，点击拍照 -->
      <button @touchstart="startRecord" @touchend="stopRecord">按住录制</button>
      <button @tap="takePhoto">拍照</button>
    </view>
    
    <!-- 用于显示拍下的照片 -->
    <image v-if="photoPath" :src="photoPath" mode="widthFix"></image>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cameraContext: null,
      photoPath: '', // 拍照得到的图片路径
      isRecording: false
    };
  },
  onReady() {
    // 页面渲染完成后，创建相机上下文
    this.cameraContext = uni.createCameraContext();
  },
  methods: {
    // 拍照
    takePhoto() {
      this.cameraContext.takePhoto({
        quality: 'high',
        success: (res) => {
          this.photoPath = res.tempImagePath;
          console.log('拍照成功，照片路径:', this.photoPath);
        },
        fail: (err) => {
          console.error('拍照失败:', err);
        }
      });
    },
    
    // 开始录制视频
    startRecord() {
      this.isRecording = true;
      this.cameraContext.startRecord({
        success: () => {
          console.log('开始录制');
        }
      });
    },
    
    // 结束录制视频
    stopRecord() {
      if (!this.isRecording) return;
      this.isRecording = false;
      this.cameraContext.stopRecord({
        success: (res) => {
          console.log('录制完成，视频路径:', res.tempThumbPath); // 封面
          console.log('视频文件路径:', res.tempVideoPath);
          // res.tempVideoPath 是视频的临时文件路径
        }
      });
    },
    
    // 切换前后摄像头
    switchCamera() {
      // 需要通过变量动态改变camera组件的device-position属性
      // 这部分逻辑需要你在data中定义变量并切换'front'和'back'
    }
  }
};
</script>

<style>
.camera {
  width: 100%;
  height: 100vh; /* 全屏 */
}
.controls {
  position: fixed;
  bottom: 50px;
  width: 100%;
  display: flex;
  justify-content: space-around;
}
</style>