<template>
  <div class="app-container">
    <el-card>
        <el-row :gutter="1" type="flex" align="middle">
          <el-col :span="4">
            <el-text class="mx-1" type="primary">设备IP：{{ tableData.ip }}</el-text>
          </el-col>
          <el-col :span="3">
            <div style="display: flex;">
              <el-text class="mx-1" type="primary">设备类型：</el-text>
              <dict-tag :options="device_type" :value="tableData.type"/>
            </div>
          </el-col>
          <el-col :span="10">
            <div style="display: flex;">
              <el-text class="mx-1" type="primary">播放地址：</el-text>
              <el-input v-model="playUrl" placeholder="播放地址" disabled style="width: 85%"></el-input>
            </div>
          </el-col>
          <el-col :span="4">
            <el-button @click="handlePlay" type="primary">刷新</el-button>
            <el-button @click="handleCopy" type="primary">复制</el-button>
            <el-button @click="handleCatch" type="primary">捕捉</el-button>
          </el-col>
        </el-row>
    </el-card>
    <div style="height: 20px;"></div>
    <el-card>
        <div style="width: 800px; height: 600px;" v-if="selected == 0">
          <el-row :gutter="10" >
            <el-col :span="24">
              <div @click="clickVideo(0)" class="selectVideo">
                <CusPlayer @clickPlayer="clickPlayer" ref="video"></CusPlayer>
              </div>
            </el-col>
          </el-row>
        </div>
      <div style="height: 20px;"></div>
    </el-card>
  </div>
</template>

<script setup name="Flv">
import {useRoute} from 'vue-router'
import {ref, onMounted} from 'vue';
import 'xgplayer';
import FlvJsPlayer from 'xgplayer-flv.js';
import CusPlayer from './cusPlayer.vue';
import {getDevice} from "@/api/video/device";

const {proxy} = getCurrentInstance();
const {device_type} = proxy.useDict('device_type');

const route = useRoute();

const selected = ref(0);
const videoIndex = ref(0);
const tableData = ref([]);
const selectValue = ref('');
const playUrl = ref('');
const useffmpeg = ref(false);
const video = ref(null);

onMounted(() => {
  getDetails(route.query.deviceId);
})

const getDetails = async (deviceId) => {
  const res = await getDevice(deviceId);
  tableData.value = res.data;
  // 直接访问后端视频流服务器（10083端口），绕过Nginx反代，避免缓冲问题
  // 注意：RTSP URL需要原样传递，不要编码，&&&作为特殊分隔符
  // 使用 ffmpeg=true，系统 FFmpeg 包含完整的编码器支持（包括 libx264）
  const videoServerUrl = 'http://49.232.154.205:10083';
  playUrl.value = `${videoServerUrl}/live?url=${tableData.value.url}&&&ffmpeg=true`;
  console.log('📺 播放地址（直连后端）:', playUrl.value);
  handlePlay();
}

const handleCatch = () => {
  console.log("捕捉事件开始")
}

const handleCopy = async () => {
  try {
    if (!navigator.clipboard) {
      throw new Error('浏览器不支持复制功能');
    }
    await navigator.clipboard.writeText(playUrl.value);
    proxy.$modal.msgSuccess('复制成功');
  } catch (error) {
    console.error('复制失败:', error);
    try {
      const textArea = document.createElement('textarea');
      textArea.value = playUrl.value;
      document.body.appendChild(textArea);
      textArea.select();
      const success = document.execCommand('copy');
      document.body.removeChild(textArea);
      if (success) {
        proxy.$modal.msgSuccess('复制成功');
      } else {
        throw new Error('复制失败');
      }
    } catch (fallbackError) {
      console.error('备用复制方法失败:', fallbackError);
      proxy.$modal.msgError('复制失败，请手动复制');
    }
  }
};


const handlePlay = () => {
  if (playUrl.value) {
    video.value.createPlayer(playUrl.value, 0)
  } else {
    alert('请填写播放地址');
  }
};

const clickVideo = (index) => {
  videoIndex.value = index;
}

const clickPlayer = (index) => {
  videoIndex.value = index;
}
</script>

<style>
.selectVideo {
  height: 600px;
  width: 800px;
}
</style>