DeviceList1078.vue 25.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
<template>
  <el-container>
    <!-- 侧边栏:设备树 -->
    <el-aside v-show="sidebarState">
      <vehicleList
        @tree-loaded="handleTreeLoaded"
        @node-click="nodeClick"
        @node-contextmenu="nodeContextmenu"
        @mouseover.native="showTooltip"
        @mouseout.native="hideTooltip"
        @click.native="hideTooltip"
        @contextmenu.native="hideTooltip"
      />

      <!-- 右键菜单 -->
      <el-dropdown ref="contextMenu" @command="handleCommand">
        <span class="el-dropdown-link"></span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="playback">一键播放</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </el-aside>

    <el-container>
      <el-header style="height: 5%;">
        <!-- 左侧折叠按钮 -->
        <i :class="sidebarState ? 'el-icon-s-fold' : 'el-icon-s-unfold'"
           @click="updateSidebarState"
           style="font-size: 20px;margin-right: 10px; cursor: pointer;"
        />

        <!-- 分屏选择与通用控制 -->
        <window-num-select v-model="windowNum"></window-num-select>
        <el-button type="danger" size="mini" @click="closeAllVideo">全部关闭</el-button>
        <el-button type="warning" size="mini" @click="closeVideo"> 关 闭</el-button>
        <el-button type="primary" size="mini" icon="el-icon-full-screen" @click="toggleFullscreen"></el-button>

        <!-- 轮播控制按钮 -->
        <el-button type="success" size="mini" icon="el-icon-timer" @click="openCarouselConfig">
          {{ isCarouselRunning ? '停止轮播' : '轮播设置' }}
        </el-button>

        <!-- 轮播状态提示区 -->
        <div v-if="isCarouselRunning" style="margin-left: 10px; font-size: 12px; display: flex; align-items: center;">
          <span v-if="isWithinSchedule" style="color: #67C23A;">
            <i class="el-icon-loading"></i>
            轮播运行中 <span style="font-size: 10px; opacity: 0.8;">(预加载模式)</span>
          </span>
          <span v-else style="color: #E6A23C;">
            <i class="el-icon-time"></i>
            轮播待机中 (等待生效时段)
          </span>
        </div>

        <!-- 右侧信息 -->
        <span class="header-right-info">{{ `下一个播放窗口 : ${windowClickIndex}` }}</span>
      </el-header>

      <!-- 轮播配置弹窗 -->
      <carousel-config
        ref="carouselConfig"
        :device-tree-data="deviceTreeData"
        @save="startCarousel"
      ></carousel-config>

      <!-- 视频播放主区域 -->
      <el-main ref="videoMain">
        <playerListComponent
          ref="playListComponent"
          @playerClick="handleClick"
          :video-url="videoUrl"
          :videoDataList="videoDataList"
          v-model="windowNum"
          style="width: 100%; height: 100%;"
        ></playerListComponent>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import tree from "vue-giant-tree";
import uiHeader from "../layout/UiHeader.vue";
import playerListComponent from './common/PlayerListComponent.vue';
import player from './common/JessVideoPlayer.vue';
import DeviceTree from './common/DeviceTree.vue'
import treeTransfer from "el-tree-transfer";
import Device1078Tree from "./JT1078Components/deviceList/Device1078Tree.vue";
import VehicleList from "./JT1078Components/deviceList/VehicleList.vue";
import WindowNumSelect from "./WindowNumSelect.vue";
import CarouselConfig from "./CarouselConfig.vue";

export default {
  name: "live",
  components: {
    WindowNumSelect,
    playerListComponent,
    Device1078Tree,
    VehicleList,
    CarouselConfig,
    uiHeader, player, DeviceTree, tree, treeTransfer
  },
  data() {
    return {
      // --- UI 状态 ---
      isFullscreen: false,
      sidebarState: true,
      windowNum: '4',
      windowClickIndex: 1,
      windowClickData: null,
      rightClickNode: null,
      tooltipVisible: false,

      // --- 播放数据 ---
      videoUrl: [],
      videoDataList: [],
      deviceTreeData: [],
      deviceList: [
        "600201", "600202", "600203", "600204", "600205",
        "601101", "601102", "601103", "601104", "CS-010",
      ],

      // --- 轮播核心状态 ---
      isCarouselRunning: false,
      isWithinSchedule: true,
      carouselConfig: null,
      carouselTimer: null,

      // 流式缓冲相关变量
      carouselDeviceList: [],
      channelBuffer: [],
      deviceCursor: 0,
    };
  },
  mounted() {
    document.addEventListener('fullscreenchange', this.handleFullscreenChange);
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  },
  beforeDestroy() {
    document.removeEventListener('fullscreenchange', this.handleFullscreenChange);
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
    this.stopCarousel();
  },
  // 路由离开守卫
  beforeRouteLeave(to, from, next) {
    if (this.isCarouselRunning) {
      this.$confirm('当前视频轮播正在进行中,离开页面将停止轮播,是否确认离开?', '提示', {
        confirmButtonText: '确定离开',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.stopCarousel();
        next();
      }).catch(() => next(false));
    } else {
      next();
    }
  },
  methods: {
    // ==========================================
    // 1. 拦截与权限控制
    // ==========================================
    handleBeforeUnload(e) {
      if (this.isCarouselRunning) {
        e.preventDefault();
        e.returnValue = '轮播正在运行,确定要离开吗?';
      }
    },

    async checkCarouselPermission(actionName) {
      if (!this.isCarouselRunning) return true;
      try {
        await this.$confirm(
          `当前【视频轮播】正在运行中。\n进行"${actionName}"操作将停止轮播,是否继续?`,
          '轮播运行提示',
          { confirmButtonText: '停止轮播并继续', cancelButtonText: '取消', type: 'warning' }
        );
        this.stopCarousel();
        return true;
      } catch (e) {
        this.$message.info("已取消操作,轮播继续运行");
        return false;
      }
    },

    // ==========================================
    // 2. 轮播核心逻辑 (预加载 + 无限循环)
    // ==========================================

    getChannels(data) {
      // (保持原有逻辑不变)
      let nvrLabels, rmLabels;
      if (data.sim2) {
        if (this.deviceList.includes(data.name)) {
          nvrLabels = ['中门', '', '车前', '驾驶舱', '', '前车厢', '', '360'];
        } else {
          nvrLabels = ['中门', '', '车前', '驾驶舱', '前门', '前车厢', '后车厢', '360'];
        }
        rmLabels = [];
      } else {
        nvrLabels = ['ADAS', 'DSM', '路况', '司机', '整车前', '中门', '倒车', '前门客流', '后面客流'];
        rmLabels = [];
      }
      return [
        ...nvrLabels.map((label, index) => label ? `${data.id}_${data.sim}_${index + 1}` : null).filter(Boolean),
        ...rmLabels.map((label, index) => label ? `${data.id}_${data.sim2}_${index + 1}` : null).filter(Boolean)
      ];
    },

    openCarouselConfig() {
      if (this.isCarouselRunning) {
        this.stopCarousel();
      } else {
        this.$refs.carouselConfig.open(this.carouselConfig);
      }
    },

    /**
     * 启动轮播
     */
    async startCarousel(config) {
      this.carouselConfig = config;
      // 1. 收集设备
      let deviceNodes = [];
      if (config.sourceType === 'all_online') {
        const findOnlineDevices = (nodes) => {
          if (!Array.isArray(nodes)) return;
          nodes.forEach(node => {
            if (node.abnormalStatus !== undefined && node.children && node.abnormalStatus === 1) {
              deviceNodes.push(node);
            }
            if (node.children) findOnlineDevices(node.children);
          });
        };
        findOnlineDevices(this.deviceTreeData);
      } else if (config.sourceType === 'custom') {
        const selected = config.selectedNodes || [];
        deviceNodes = selected.filter(n => n.abnormalStatus !== undefined && n.children);
      }

      if (deviceNodes.length === 0) {
        this.$message.warning("没有可轮播的在线设备");
        return;
      }

      // 2. 初始化状态
      this.carouselDeviceList = deviceNodes;
      this.channelBuffer = [];
      this.deviceCursor = 0;
      this.isCarouselRunning = true;
      this.isWithinSchedule = true;

      this.$message.success(`轮播启动,覆盖 ${deviceNodes.length} 台设备`);

      // 3. 立即执行第一轮播放
      await this.executeFirstRound();
    },

    /**
     * 执行第一轮 (不等待,立即播放)
     */
    async executeFirstRound() {
      // 切换到配置的布局
      if (this.windowNum !== this.carouselConfig.layout) {
        this.windowNum = this.carouselConfig.layout;
      }

      // 获取第一批数据
      const batchData = await this.fetchNextBatchData();
      if (batchData && batchData.urls) {
        this.videoUrl = batchData.urls;
        this.videoDataList = batchData.infos;
        // 启动后续的循环
        this.runCarouselLoop();
      } else {
        this.$message.warning("获取首轮播放数据失败,尝试继续运行...");
        this.runCarouselLoop(); // 即使失败也尝试进入循环
      }
    },

    /**
     * 轮播循环调度器 (预加载核心)
     */
    runCarouselLoop() {
      if (!this.isCarouselRunning) return;

      const config = this.carouselConfig;
      // 检查时间段
      if (config.runMode === 'schedule') {
        const isInTime = this.checkTimeRange(config.timeRange[0], config.timeRange[1]);
        this.isWithinSchedule = isInTime;
        if (!isInTime) {
          // 不在时间段,清屏并等待 10秒再检查
          if (this.videoUrl.some(u => u)) this.closeAllVideoNoConfirm();
          this.carouselTimer = setTimeout(() => this.runCarouselLoop(), 10000);
          return;
        }
      } else {
        this.isWithinSchedule = true;
      }

      // 计算时间: 间隔时间,提前 15s 请求(优化预加载时间)
      const intervalSeconds = Math.max(config.interval, 30); // 最小间隔30秒,给足够时间
      const preLoadSeconds = 15; // 提前15秒开始请求,确保流有足够时间推上来
      const waitTimeForFetch = (intervalSeconds - preLoadSeconds) * 1000;
      const waitTimeForSwitch = preLoadSeconds * 1000;

      // 步骤 1: 等待到预加载时间点
      this.carouselTimer = setTimeout(async () => {
        if (!this.isCarouselRunning) return;

        console.log(`[轮播] 预加载下一批数据...`);
        
        // 显示加载提示
        const loadingMsg = this.$message({
          type: 'info',
          message: '正在预加载下一批视频...',
          duration: preLoadSeconds * 1000,
          showClose: false
        });
        
        // 步骤 2: 向后端请求下一批地址 (后端秒回,但流还没好)
        const nextBatch = await this.fetchNextBatchData();
        
        loadingMsg.close();

        // 步骤 3: 拿到地址后,等待流推上来 (补足剩下的时间)
        this.carouselTimer = setTimeout(() => {
          if (!this.isCarouselRunning) return;

          if (nextBatch && nextBatch.urls) {
            console.log('[轮播] 切换画面');
            // 更新布局 (防止用户中途改了)
            if (this.windowNum !== this.carouselConfig.layout) {
              this.windowNum = this.carouselConfig.layout;
            }
            // 切换数据 -> 触发播放器复用逻辑
            this.videoUrl = nextBatch.urls;
            this.videoDataList = nextBatch.infos;
            
            this.$message.success('已切换到下一批视频');
          } else {
            this.$message.warning('预加载失败,将在下一轮重试');
          }

          // 递归进入下一轮
          this.runCarouselLoop();

        }, waitTimeForSwitch);

      }, waitTimeForFetch);
    },

    /**
     * 核心:获取下一批数据 (分批加载优化)
     */
    async fetchNextBatchData() {
      // 1. 确定当前需要的通道数
      let pageSize = parseInt(this.carouselConfig.layout);
      const layoutMap = { '1+5': 6, '1+7': 8, '1+9': 10, '1+11': 12 };
      if (layoutMap[this.carouselConfig.layout]) pageSize = layoutMap[this.carouselConfig.layout];

      // 2. 补货逻辑:填充 channelBuffer
      let loopSafety = 0;
      const maxLoops = 50;

      while (this.channelBuffer.length < pageSize && loopSafety < maxLoops) {
        loopSafety++;

        // 游标归零重置逻辑
        if (this.deviceCursor >= this.carouselDeviceList.length) {
          console.log('[轮播缓冲] 列表循环,重置游标...');
          this.deviceCursor = 0;
          this.rebuildOnlineList(); // 刷新在线列表

          if (this.carouselDeviceList.length === 0) {
            console.warn('[轮播] 无在线设备,无法补货');
            break;
          }
        }

        const BATCH_SIZE = 10; // 增加批次大小以提高效率
        let batchCodes = [];

        // 提取一批设备
        for (let i = 0; i < BATCH_SIZE; i++) {
          if (this.deviceCursor >= this.carouselDeviceList.length) break;
          const device = this.carouselDeviceList[this.deviceCursor];
          if (device && device.abnormalStatus === 1) {
            batchCodes.push(device);
          }
          this.deviceCursor++;
        }

        // 解析通道放入 Buffer
        if (batchCodes.length > 0) {
          batchCodes.forEach(device => {
            try {
              const codes = this.getChannels(device);
              if (codes && codes.length > 0) this.channelBuffer.push(...codes);
            } catch (e) {}
          });
        }

        if (this.channelBuffer.length >= pageSize) break;
      }

      // 3. 如果 Buffer 还是空的
      if (this.channelBuffer.length === 0) return null;

      // 4. 从 Buffer 取出数据
      const currentBatch = this.channelBuffer.splice(0, pageSize);

      // 提取 ID
      const streamList = currentBatch
        .map(c => c.replaceAll('_', '-'))
        .map(code => code.substring(code.indexOf('-') + 1));

      // 5. 分批请求后端以减轻压力
      const BATCH_REQUEST_SIZE = 12; // 每批最多12路
      let allResults = [];
      
      // 如果总数超过BATCH_REQUEST_SIZE,则分批请求
      if (streamList.length > BATCH_REQUEST_SIZE) {
        console.log(`[轮播] 总共 ${streamList.length} 路视频,将分批请求`);
        
        for (let i = 0; i < streamList.length; i += BATCH_REQUEST_SIZE) {
          const batch = streamList.slice(i, i + BATCH_REQUEST_SIZE);
          console.log(`[轮播] 请求第 ${Math.floor(i/BATCH_REQUEST_SIZE)+1} 批,共 ${batch.length} 路`);
          
          try {
            const res = await this.fetchBatchData(batch);
            if (res && res.data && res.data.data) {
              allResults.push(...res.data.data);
            }
            // 每批之间短暂休息以避免服务器压力过大
            await new Promise(resolve => setTimeout(resolve, 200));
          } catch (e) {
            console.error(`[轮播] 第 ${Math.floor(i/BATCH_REQUEST_SIZE)+1} 批请求失败:`, e);
          }
        }
      } else {
        // 少量数据直接请求
        try {
          const res = await this.fetchBatchData(streamList);
          if (res && res.data && res.data.data) {
            allResults = res.data.data;
          }
        } catch (e) {
          console.error('[轮播] 批量请求失败:', e);
        }
      }

      // 6. 整合结果
      const urls = new Array(pageSize).fill('');
      const infos = new Array(pageSize).fill(null);

      if (allResults.length > 0) {
        allResults.forEach((item, i) => {
          if (i < currentBatch.length && item) {
            urls[i] = item.ws_flv;
            infos[i] = {
              code: currentBatch[i],
              name: `通道 ${i+1}`,
              videoUrl: item.ws_flv
            };
          }
        });
      }
      
      console.log(`[轮播] 成功获取 ${allResults.length}/${pageSize} 路视频地址`);
      return { urls, infos };
    },

    /**
     * 分批请求数据
     */
    async fetchBatchData(streamList) {
      // 请求后端 (优化点:增加重试机制和超时时间)
      let retryCount = 0;
      const maxRetries = 2;
      
      while (retryCount <= maxRetries) {
        try {
          const res = await this.$axios({
            method: 'post',
            url: '/api/jt1078/query/beachSend/request/io',
            data: streamList,
            timeout: 30000 // 增加超时时间到30秒,支持大批量请求
          });
          return res;
        } catch (e) {
          retryCount++;
          if (retryCount > maxRetries) {
            console.error(`预加载请求失败,已重试${maxRetries}次`, e);
            this.$message.error('批量加载失败,请检查网络或设备状态');
            return null;
          }
          console.warn(`请求失败,${retryCount * 2}秒后重试... (第${retryCount}/${maxRetries}次)`);
          await new Promise(resolve => setTimeout(resolve, retryCount * 2000)); // 递增延迟重试:2秒、4秒
        }
      }
    },

    /**
     * 重建在线列表
     */
    rebuildOnlineList() {
      let newDeviceNodes = [];
      if (this.carouselConfig.sourceType === 'all_online') {
        const findOnlineDevices = (nodes) => {
          if (!Array.isArray(nodes)) return;
          nodes.forEach(node => {
            if (node.abnormalStatus !== undefined && node.children && node.abnormalStatus === 1) {
              newDeviceNodes.push(node);
            }
            if (node.children) findOnlineDevices(node.children);
          });
        };
        findOnlineDevices(this.deviceTreeData);
      } else {
        const selected = this.carouselConfig.selectedNodes || [];
        newDeviceNodes = selected.filter(n => n.abnormalStatus !== undefined && n.abnormalStatus === 1);
      }
      this.carouselDeviceList = newDeviceNodes;
    },

    stopCarousel() {
      this.isCarouselRunning = false;
      if (this.carouselTimer) {
        clearTimeout(this.carouselTimer);
        this.carouselTimer = null;
      }
      this.$message.info("轮播已停止");
    },

    closeAllVideoNoConfirm() {
      this.videoUrl = [];
      this.videoDataList = [];
    },

    checkTimeRange(startStr, endStr) {
      const now = new Date();
      const current = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds();
      const parse = (str) => {
        const [h, m, s] = str.split(':').map(Number);
        return h * 3600 + m * 60 + s;
      };
      return current >= parse(startStr) && current <= parse(endStr);
    },

    // ==========================================
    // 3. 常规操作
    // ==========================================
    handleTreeLoaded(data) {
      this.deviceTreeData = data;
    },

    async nodeClick(data, node) {
      if (!(await this.checkCarouselPermission('播放视频'))) return;
      if (data.abnormalStatus === undefined && data.children === undefined) {
        if (!(await this.checkCarouselPermission('切换播放'))) return;
        this.getPlayStream(data);
      }
    },

    getPlayStream(data) {
      let stream = data.code.replace('-', '_');
      let currentIdx = this.windowClickIndex;
      let arr = stream.split("_");
      // 单路播放默认主码流(0)
      this.$axios({
        method: 'get',
        url: `/api/jt1078/query/send/request/io/${arr[1]}/${arr[2]}`
      }).then(res => {
        if (res.data.code === 0) {
          const url = res.data.data.ws_flv;
          const idx = currentIdx - 1;
          this.$set(this.videoUrl, idx, url);
          data['videoUrl'] = url;
          this.$set(this.videoDataList, idx, data);

          let nextIndex = currentIdx + 1;
          const max = parseInt(this.windowNum) || 4;
          if (nextIndex > max) nextIndex = 1;
          this.windowClickIndex = nextIndex;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },

    // 优化后的右键播放
    async handleCommand(command) {
      if (command === 'playback') {
        if (!(await this.checkCarouselPermission('切换设备播放'))) return;
        if (!this.rightClickNode) {
          this.$message.warning("请选择播放设备");
          return;
        }

        const nodeData = this.rightClickNode.data;
        // 清空当前画面
        this.videoUrl = [];
        this.videoDataList = [];

        const doPlay = (channels) => {
          if (!channels || channels.length === 0) {
            this.$message.warning("该设备下没有可用通道");
            return;
          }

          // 自动适配布局
          const count = channels.length;
          if (count <= 1) this.windowNum = '1';
          else if (count <= 4) this.windowNum = '4';
          else if (count <= 9) this.windowNum = '9';
          else if (count <= 16) this.windowNum = '16';
          else if (count <= 25) this.windowNum = '25';
          else this.windowNum = '36'; // 最大支持36

          this.$nextTick(() => {
            const streamList = channels
              .map(c => c.code.replaceAll('_', '-'))
              .map(code => code.substring(code.indexOf('-') + 1));

            this.$axios({
              method: 'post',
              url: '/api/jt1078/query/beachSend/request/io',
              data: streamList,
              headers: { 'Content-Type': 'application/json' }
            }).then(res => {
              const streamData = res.data.data;
              if (streamData && streamData.length > 0) {
                let urls = streamData.map(item => item.ws_flv);
                // 填充数据
                urls.forEach((url, i) => {
                  this.$set(this.videoUrl, i, url);
                  const channelInfo = { ...channels[i], videoUrl: url };
                  this.$set(this.videoDataList, i, channelInfo);
                });
                this.$message.success(`成功播放 ${streamData.length} 路视频`);
              } else {
                this.$message.warning("服务器未返回流地址");
              }
            }).catch(err => {
              console.error("播放失败", err);
              this.$message.error("播放请求失败");
            });
          });
        };

        if (nodeData.children && nodeData.children.length > 0) {
          doPlay(nodeData.children);
        } else {
          // 假设这里需要异步加载子节点,如果是同步的可以直接忽略 else
          const channels = nodeData.children || [];
          doPlay(channels);
        }
      }
    },

    async closeAllVideo() {
      if (!(await this.checkCarouselPermission('关闭所有视频'))) return;
      if (this.videoUrl.some(u => u)) {
        this.$confirm('确认全部关闭直播 ?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.videoUrl = [];
            this.videoDataList = [];
          }).catch(() => {
        });
      } else {
        this.$message.error('没有可以关闭的视频');
      }
    },

    async closeVideo() {
      if (!(await this.checkCarouselPermission('关闭当前窗口'))) return;
      const idx = Number(this.windowClickIndex) - 1;
      if (this.videoUrl && this.videoUrl[idx]) {
        // 设置为null而不是空字符串,确保播放器完全销毁
        this.$set(this.videoUrl, idx, null);
        this.$set(this.videoDataList, idx, null);
      } else {
        this.$message.warning(`当前窗口 [${this.windowClickIndex}] 没有正在播放的视频`);
      }
    },

    toggleFullscreen() {
      const element = this.$refs.videoMain.$el;
      if (!this.isFullscreen) {
        if (element.requestFullscreen) element.requestFullscreen();
        else if (element.webkitRequestFullscreen) element.webkitRequestFullscreen();
      } else {
        if (document.exitFullscreen) document.exitFullscreen();
        else if (document.webkitExitFullscreen) document.webkitExitFullscreen();
      }
    },
    handleFullscreenChange() {
      this.isFullscreen = !!document.fullscreenElement;
    },
    updateSidebarState() {
      this.sidebarState = !this.sidebarState;
      this.$refs.playListComponent.updateGridTemplate(this.windowNum);
    },
    handleClick(data, index) {
      this.windowClickIndex = index + 1;
      this.windowClickData = data;
    },
    showTooltip() {
      this.tooltipVisible = true;
    },
    hideTooltip() {
      this.tooltipVisible = false;
    },
    nodeContextmenu(event, data, node) {
      if (data.abnormalStatus !== undefined && data.children) {
        this.rightClickNode = node;
        event.preventDefault();
        const menu = this.$refs.contextMenu;
        menu.show();
        menu.$el.style.position = 'fixed';
        menu.$el.style.left = `${event.clientX}px`;
        menu.$el.style.top = `${event.clientY}px`;
      }
    },
  }
};
</script>

<style scoped>
.el-header {
  background-color: #B3C0D1;
  color: #333;
  text-align: center;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 0 20px;
}

.header-right-info {
  margin-left: auto;
  font-weight: bold;
  font-size: 14px;
}

.el-aside {
  background-color: white;
  color: #333;
  text-align: center;
  height: 100%;
  width: 20%;
  padding: 10px;
  margin-right: 1px;
}

.el-main {
  background-color: rgba(0, 0, 0, 0.95);
  color: #333;
  text-align: center;
  line-height: 160px;
  padding: 0;
  margin-left: 1px;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container {
  height: 90vh;
}

.el-container:nth-child(5) .el-aside, .el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-dropdown-link {
  display: none;
}

.el-container:nth-child(7) .el-aside {
  width: 100%;
  line-height: 320px;
}

.el-main:fullscreen, .el-main:-webkit-full-screen {
  background-color: black;
  width: 100vw;
  height: 100vh;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
</style>