EasyPlayer.vue 30 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 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
<template>
  <div
    class="player-wrapper"
    :class="[playerClassOptions, { 'force-hide-controls': !showControls }]"
    @click="onPlayerClick"
    @mousemove="onMouseMove"
    @mouseleave="onMouseLeave"
    @contextmenu="onContextMenuWrapper"
  >
    <div class="custom-top-bar" :class="{ 'hide-bar': !showControls }">
      <div class="top-bar-left">
        <span class="video-title">{{ videoTitle || '实时监控' }}</span>
      </div>
      <div class="top-bar-right">
        <span class="net-speed">
           <i class="el-icon-odometer"></i> {{ netSpeed }}
        </span>
      </div>
    </div>

    <div :id="uniqueId" ref="container" class="player-box"></div>

    <!-- 自定义右键菜单 - 全屏时附加到 body -->
    <div
      v-if="showContextMenu"
      ref="contextMenu"
      class="custom-contextmenu"
      :class="{ 'menu-fixed': isFullscreen }"
      :style="{ top: contextMenuY + 'px', left: contextMenuX + 'px' }"
      @click.stop
    >
      <div class="contextmenu-item" @click.stop="onShowVideoInfo">视频信息</div>
      <div class="contextmenu-divider"></div>
      <div class="contextmenu-item" @click.stop="onSwitchMainStream">主码流</div>
      <div class="contextmenu-item" @click.stop="onSwitchSubStream">子码流</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'VideoPlayer',
  props: {
    initialPlayUrl: { type: String, default: '' },
    isResize: { type: Boolean, default: true },
    videoTitle: { type: String, default: '' },
    hasAudio: { type: Boolean, default: false },
    // 码流切换所需参数
    sim: { type: String, default: '' },
    channel: { type: [String, Number], default: '' }
  },
  data() {
    return {
      uniqueId: `player-box-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
      playerInstance: null,
      netSpeed: '0KB/s',
      hasStarted: false,
      showControls: false,
      controlTimer: null,
      isFullscreen: false, // 全屏状态

      // 自定义右键菜单
      showContextMenu: false,
      contextMenuX: 0,
      contextMenuY: 0,
      contextMenuHandler: null, // 保存右键菜单监听器函数
      docContextMenuHandler: null, // 保存文档级右键菜单监听器函数
      containerContextMenuHandler: null, // 保存容器级右键菜单监听器函数

      // 【配置控制表】
      controlsConfig: {
        showBottomBar: true,   // 是否显示底栏
        showSpeed: false,      // 是否显示底部原生的网速 (建议 false,因为顶部已经有了)
        showCodeSelect: false, // 是否显示解码器/分辨率切换

        showPlay: true,        // 播放暂停
        showAudio: true,       // 音量
        showStretch: true,     // 拉伸
        showScreenshot: true,  // 截图
        showRecord: true,      // 录制
        showZoom: true,        // 电子放大
        showFullscreen: true,  // 全屏
      }
    };
  },
  computed: {
    // 根据配置生成 CSS 类名
    playerClassOptions() {
      const c = this.controlsConfig;
      return {
        'hide-bottom-bar': !c.showBottomBar,
        'hide-speed': !c.showSpeed,            // 对应下方 CSS
        'hide-code-select': !c.showCodeSelect, // 对应下方 CSS

        'hide-btn-play': !c.showPlay,
        'hide-btn-audio': !c.showAudio,
        'hide-btn-stretch': !c.showStretch,
        'hide-btn-screenshot': !c.showScreenshot,
        'hide-btn-record': !c.showRecord,
        'hide-btn-zoom': !c.showZoom,
        'hide-btn-fullscreen': !c.showFullscreen,
      };
    }
  },
  watch: {
    initialPlayUrl(newUrl, oldUrl) {
      if (newUrl && newUrl !== oldUrl) {
        this.destroyAndReplay(newUrl);
      } else if (!newUrl) {
        this.destroy();
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        if (this.$refs.container) {
          this.create();
          if (this.initialPlayUrl) {
            this.play(this.initialPlayUrl);
          }
        }
      }, 500);
    });
    // 添加全局点击事件监听,用于隐藏右键菜单
    document.addEventListener('click', this.hideContextMenu);
    // 添加全屏变化监听
    document.addEventListener('fullscreenchange', this.onFullscreenChange);
    document.addEventListener('webkitfullscreenchange', this.onFullscreenChange);
    // 在 document 级别使用 capture 模式拦截 contextmenu 事件
    this.docContextMenuHandler = (e) => {
      // 检查播放器是否在播放
      if (!this.hasStarted) {
        return;
      }

      // 优先使用 this.isFullscreen(通过 onFullscreenChange 更新的),因为 EasyPlayerPro 可能不会更新 document.fullscreenElement
      const isFullscreen = !!(document.fullscreenElement || document.webkitFullscreenElement || this.isFullscreen);
      console.log('Contextmenu event - isFullscreen:', isFullscreen, 'docFullscreen:', !!(document.fullscreenElement || document.webkitFullscreenElement), 'this.isFullscreen:', this.isFullscreen, 'target:', e.target);

      // 全屏模式下,使用 DOM 遍历方式检测
      if (isFullscreen) {
        console.log('Entering fullscreen branch');
        let target = e.target;

        // 简化检测:直接检查点击目标是否在当前播放器元素内
        const isInPlayer = this.$el.contains(target);
        console.log('isInPlayer (this.$el.contains):', isInPlayer, 'target:', target, 'this.$el:', this.$el);

        if (isInPlayer) {
          e.preventDefault();
          setTimeout(() => {
            this.hideNativeContextMenu();
            this.onContextMenu(e);
          }, 10);
        }
        return;
      }

      // 非全屏模式下,使用坐标检测
      const rect = this.$el.getBoundingClientRect();
      const isClickInPlayer = (
        e.clientX >= rect.left &&
        e.clientX <= rect.right &&
        e.clientY >= rect.top &&
        e.clientY <= rect.bottom
      );

      // 如果点击不在当前播放器内,不处理
      if (!isClickInPlayer) {
        return;
      }

      // 点击在当前播放器内,阻止原生菜单并显示自定义菜单
      e.preventDefault();
      // 延迟一点执行,确保我们的菜单能显示
      setTimeout(() => {
        this.hideNativeContextMenu();
        this.onContextMenu(e);
      }, 10);
    };
    document.addEventListener('contextmenu', this.docContextMenuHandler, true);
  },
  beforeDestroy() {
    this.destroy();
    if (this.controlTimer) clearTimeout(this.controlTimer);
    // 移除全局点击事件监听
    document.removeEventListener('click', this.hideContextMenu);
    // 移除全屏变化监听
    document.removeEventListener('fullscreenchange', this.onFullscreenChange);
    document.removeEventListener('webkitfullscreenchange', this.onFullscreenChange);
    // 移除 document 级别的 contextmenu 监听
    if (this.docContextMenuHandler) {
      document.removeEventListener('contextmenu', this.docContextMenuHandler, true);
    }
  },
  methods: {
    onMouseMove() {
      if (!this.hasStarted) return;
      this.showControls = true;
      if (this.controlTimer) clearTimeout(this.controlTimer);
      this.controlTimer = setTimeout(() => {
        this.showControls = false;
      }, 3000);
    },
    onMouseLeave() {
      this.showControls = false;
    },

    create() {
      if (this.playerInstance) return;
      const container = this.$refs.container;
      if (!container || !window.EasyPlayerPro) return;
      if (container.clientWidth === 0) return;

      try {
        // 保持原有的创建逻辑不变
        this.playerInstance = new window.EasyPlayerPro(container, {
          bufferTime: 0.2,
          stretch: !this.isResize,
          MSE: true,
          WCS: true,
          hasAudio: this.hasAudio,
          isLive: true,
          loading: true,
          isBand: true, // 必须为 true 才能获取网速回调
          // js配置全开,实际显隐由 CSS 控制
          btns: {
            fullscreen: true,
            screenshot: true,
            play: true,
            audio: true,
            record: true,
            stretch: true,
            zoom: true,
          }
        });

        this.playerInstance.on('kBps', (speed) => {
          this.netSpeed = speed + '/S';
        });

        this.playerInstance.on('play', () => {
          this.hasStarted = true;
          this.showControls = true;
          if (this.controlTimer) clearTimeout(this.controlTimer);
          this.controlTimer = setTimeout(() => {
            this.showControls = false;
          }, 3000);
        });

        this.playerInstance.on('error', (err) => {
          console.warn('Player Error:', err);
        });

        // 监听播放器的 contextmenu 事件,防止显示原生菜单
        this.playerInstance.on('contextmenu', (e) => {
          e.preventDefault();
        });

        // 添加原生 contextmenu 监听器到容器元素和 wrapper 元素,作为 document 级监听器的备份
        // 在 fullscreen 模式下,事件可能不会冒泡到 document
        this.containerContextMenuHandler = (e) => {
          console.log('Container contextmenu fired (native listener), hasStarted:', this.hasStarted);
          if (!this.hasStarted) {
            console.log('hasStarted check failed');
            return;
          }
          e.preventDefault();
          console.log('About to call onContextMenu');
          this.hideNativeContextMenu();
          this.onContextMenu(e);
          console.log('onContextMenu called, showContextMenu should be:', this.showContextMenu);
        };
        container.addEventListener('contextmenu', this.containerContextMenuHandler, true);
        // 也在 wrapper (this.$el) 上添加监听,fullscreen 时 this.$el 可能是全屏元素
        this.$el.addEventListener('contextmenu', this.containerContextMenuHandler, true);

        // 注意:document 级别的 contextmenu 监听器已在 mounted 中添加,这里不需要重复添加


      } catch (e) {
        console.error("Create Error:", e);
      }
    },

    play(url) {
      const playUrl = url || this.initialPlayUrl;
      if (!playUrl) return;
      if (!this.playerInstance) {
        this.create();
        setTimeout(() => this.play(playUrl), 200);
        return;
      }
      this.playerInstance.play(playUrl).catch(e => {
        console.warn('Play Error:', e);
      });
    },

    destroy() {
      this.hasStarted = false;
      this.showControls = false;
      // 移除 document 级别的 contextmenu 监听
      if (this.docContextMenuHandler) {
        document.removeEventListener('contextmenu', this.docContextMenuHandler, true);
        this.docContextMenuHandler = null;
      }
      // 移除容器级别的 contextmenu 监听
      if (this.containerContextMenuHandler && this.$refs.container) {
        this.$refs.container.removeEventListener('contextmenu', this.containerContextMenuHandler, true);
        this.$el.removeEventListener('contextmenu', this.containerContextMenuHandler, true);
        this.containerContextMenuHandler = null;
      }
      if (this.playerInstance) {
        this.playerInstance.destroy();
        this.playerInstance = null;
      }
    },

    destroyAndReplay(url) {
      this.destroy();
      this.$nextTick(() => {
        this.create();
        if (url) this.play(url);
      });
    },

    onPlayerClick() {
      this.$emit('click');
    },

    // 右键菜单处理 - 直接在 wrapper 上拦截
    onContextMenuWrapper(e) {
      // 阻止事件冒泡到 EasyPlayerPro
      e.stopPropagation();
      // document 级别的监听器会处理阻止默认行为
    },

    // 右键菜单 - 用于 capture 模式拦截
    onContextMenuCapture(e) {
      // 阻止原生右键菜单
      e.preventDefault();
      e.stopPropagation();

      // 调用正常的右键菜单处理
      this.onContextMenu(e);
    },

    // 右键菜单
    onContextMenu(e) {
      console.log('onContextMenu called, hasStarted:', this.hasStarted);
      // 只有在播放器已启动后才显示菜单
      if (!this.hasStarted) return;

      // 计算菜单位置,确保不超出播放器边界
      const menuWidth = 150;
      const menuHeight = 140;

      // 检查是否是全屏模式
      const isFs = !!(document.fullscreenElement || document.webkitFullscreenElement || this.isFullscreen);

      // 全屏模式:使用 viewport 坐标
      // 非全屏模式:使用播放器容器坐标
      let x, y;
      if (isFs) {
        // 全屏时使用绝对坐标
        x = e.clientX;
        y = e.clientY;
        console.log('Fullscreen mode - using viewport coords:', x, y);
      } else {
        // 非全屏时使用相对于 player-wrapper 的坐标
        const containerRect = this.$el.getBoundingClientRect();
        x = e.clientX - containerRect.left;
        y = e.clientY - containerRect.top;
        console.log('Normal mode - using relative coords:', x, y, 'containerRect:', containerRect);
      }

      // 边界检测
      const maxX = isFs ? window.innerWidth : (isFs ? window.innerWidth : this.$el.getBoundingClientRect().width);
      const maxY = isFs ? window.innerHeight : (isFs ? window.innerHeight : this.$el.getBoundingClientRect().height);

      if (x + menuWidth > maxX) {
        x = maxX - menuWidth;
      }
      if (y + menuHeight > maxY) {
        y = maxY - menuHeight;
      }

      // 确保最小值
      x = Math.max(0, x);
      y = Math.max(0, y);

      this.contextMenuX = x;
      this.contextMenuY = y;
      console.log('Setting showContextMenu=true, x:', x, 'y:', y);

      // 阻止事件冒泡
      e.stopPropagation();

      // 先隐藏原生菜单(多次调用确保隐藏)
      this.hideNativeContextMenu();

      this.showContextMenu = true;
      this.$forceUpdate();
      console.log('showContextMenu is now:', this.showContextMenu);

      // 全屏时将菜单附加到 body
      if (isFs && this.$refs.contextMenu) {
        console.log('Appending menu to body for fullscreen');
        document.body.appendChild(this.$refs.contextMenu);
        // 强制设置 position: fixed 和 top/left
        this.$refs.contextMenu.style.position = 'fixed';
        this.$refs.contextMenu.style.top = y + 'px';
        this.$refs.contextMenu.style.left = x + 'px';
      }

      // 检查 DOM
      this.$nextTick(() => {
        const menu = this.$refs.contextMenu || this.$el.querySelector('.custom-contextmenu');
        console.log('DOM check - menu exists:', !!menu, 'parent:', menu ? menu.parentElement : 'N/A');
        console.log('isFullscreen data property:', this.isFullscreen);
        console.log('menu-fixed class applied:', menu ? menu.classList.contains('menu-fixed') : 'N/A');
        if (menu) {
          console.log('Menu computed position:', getComputedStyle(menu).position);
          console.log('Menu rect:', menu.getBoundingClientRect(), 'viewport:', window.innerWidth, window.innerHeight);
          // 检查原生菜单状态
          const nativeMenus = document.querySelectorAll('[class*="easyplayer-contextmenu"]');
          console.log('Native menus count:', nativeMenus.length);

          // 检查是否有其他元素覆盖在菜单上面
          const elemBelow = document.elementFromPoint(x, y);
          console.log('Element at menu position (x,y):', x, y, 'is:', elemBelow);

          // 使用 requestAnimationFrame 确保菜单在原生菜单之后渲染
          requestAnimationFrame(() => {
            requestAnimationFrame(() => {
              this.hideNativeContextMenu();
              // 强制确保菜单可见
              menu.style.setProperty('display', 'block', 'important');
              menu.style.setProperty('visibility', 'visible', 'important');
              menu.style.setProperty('opacity', '1', 'important');
              console.log('After rAF forcing styles - display:', getComputedStyle(menu).display, 'visibility:', getComputedStyle(menu).visibility, 'opacity:', getComputedStyle(menu).opacity, 'position:', getComputedStyle(menu).position);
              // 再次检查覆盖元素
              const elemBelowAfter = document.elementFromPoint(x, y);
              console.log('Element at menu position AFTER forcing:', x, y, 'is:', elemBelowAfter);
            });
          });
        }
      });
    },

    // 隐藏右键菜单
    hideContextMenu() {
      // 如果菜单被附加到 body,将其移回 player-wrapper
      if (this.$refs.contextMenu && this.$refs.contextMenu.parentElement !== this.$el) {
        this.$el.appendChild(this.$refs.contextMenu);
      }
      this.showContextMenu = false;
      // 同时隐藏原生菜单
      this.hideNativeContextMenu();
    },

    // 隐藏原生右键菜单
    hideNativeContextMenu() {
      const menus = document.querySelectorAll('[class*="easyplayer-contextmenu"]');
      menus.forEach(menu => {
        if (!menu.classList.contains('custom-contextmenu')) {
          menu.style.display = 'none';
        }
      });
    },

    // 全屏状态变化处理
    onFullscreenChange() {
      this.isFullscreen = !!(document.fullscreenElement || document.webkitFullscreenElement);
      // 全屏时隐藏右键菜单
      if (!this.isFullscreen) {
        this.hideContextMenu();
      }
    },

    // 视频信息
    onShowVideoInfo() {
      const instance = this.playerInstance;

      // 方法1: 直接调用
      if (instance && typeof instance.showVideoInfo === 'function') {
        instance.showVideoInfo();
        this.hideContextMenu();
        return;
      }

      // 方法2: 通过 player 调用
      if (instance && instance.player && typeof instance.player.showVideoInfo === 'function') {
        instance.player.showVideoInfo();
        this.hideContextMenu();
        return;
      }

      // 方法3: 调用 _videoinfo 方法
      if (instance && typeof instance._videoinfo === 'function') {
        instance._videoinfo();
        this.hideContextMenu();
        return;
      }

      // 方法4: 尝试通过 events 触发
      if (instance && instance.events && instance.events.emit) {
        instance.events.emit('showVideoInfo');
        this.hideContextMenu();
        return;
      }

      // 方法5: 触发原生菜单中的视频信息按钮
      // 先隐藏我们的自定义菜单,然后让原生菜单显示,再点击其视频信息按钮
      const customMenu = this.$el.querySelector('.custom-contextmenu');
      if (customMenu) {
        customMenu.style.display = 'none';
      }

      // 强制显示原生菜单(移除我们的隐藏样式)
      const allMenus = document.querySelectorAll('.easyplayer-contextmenu-btn');
      allMenus.forEach(menu => {
        menu.style.display = '';
        menu.style.opacity = '';
        menu.style.visibility = '';
      });

      // 延迟一点让原生菜单显示
      setTimeout(() => {
        // 在当前播放器容器内查找原生菜单
        const container = this.$refs.container;
        let infoBtn = null;

        if (container) {
          const nativeMenu = container.querySelector('.easyplayer-contextmenu-btn');
          if (nativeMenu) {
            infoBtn = nativeMenu.querySelector('.easyplayer-contextmenu-info');
          }
        }

        // 如果没找到,尝试基于位置匹配
        if (!infoBtn) {
          const playerRect = this.$el.getBoundingClientRect();
          for (let i = 0; i < allMenus.length; i++) {
            const menu = allMenus[i];
            const menuRect = menu.getBoundingClientRect();
            const isOverlapping =
              Math.abs(menuRect.left - playerRect.left) < 100 &&
              Math.abs(menuRect.top - playerRect.top) < 100;
            if (isOverlapping) {
              infoBtn = menu.querySelector('.easyplayer-contextmenu-info');
              break;
            }
          }
        }

        if (infoBtn) {
          infoBtn.click();
        }

        // 隐藏原生菜单
        allMenus.forEach(menu => {
          menu.style.display = 'none';
        });
      }, 50);
    },

    // 切换主码流
    onSwitchMainStream() {
      this.hideContextMenu();
      this.switchStream(0);
    },

    // 切换子码流
    onSwitchSubStream() {
      this.hideContextMenu();
      this.switchStream(1);
    },

    setControls(config) {
      this.controlsConfig = { ...this.controlsConfig, ...config };
    },

    // 切换码流
    switchStream(type) {
      // 如果没有sim和channel参数,则不发送请求
      if (!this.sim || !this.channel) {
        console.log('码流切换跳过: 缺少sim或channel参数');
        return;
      }

      const params = {
        sim: this.sim,
        channel: parseInt(this.channel),
        type: type
      };

      console.log(`码流切换: sim=${params.sim}, channel=${params.channel}, type=${type} (0=主码流, 1=子码流)`);

      // 使用箭头函数保存this引用
      const doSwitch = (axiosInstance) => {
        axiosInstance.post('/api/jt1078/query/switch/stream', params)
          .then(res => {
            if (res.data.code === 200 || res.data.code === 0) {
              console.log('码流切换成功,等待设备切换...');
            } else {
              console.warn('码流切换失败:', res.data.msg || res.data);
            }
          })
          .catch(err => {
            console.error('码流切换请求失败:', err);
          });
      };

      if (this.$axios) {
        doSwitch(this.$axios);
      } else if (window.axios) {
        doSwitch(window.axios);
      }
    },

    // 刷新播放地址并重新播放
    refreshPlayUrl() {
      if (!this.sim || !this.channel) return;

      const axiosInstance = this.$axios || window.axios;
      if (!axiosInstance) return;

      axiosInstance.get(`/api/jt1078/query/send/request/io/${this.sim}/${this.channel}`)
        .then(res => {
          if (res.data.code === 200 || res.data.code === 0) {
            const newUrl = res.data.data.ws_flv || res.data.data.wss_flv;
            console.log('获取新播放地址:', newUrl);

            if (newUrl) {
              // 重新创建播放器并播放新地址
              // 分步执行:先销毁,等待,再重建,确保播放器完全重置
              this.destroy();

              // 等待一段时间后重新创建播放器
              setTimeout(() => {
                this.create();
                this.play(newUrl);
              }, 500); // 等待500ms确保完全销毁后再重建
            }
          } else {
            console.warn('获取播放地址失败:', res.data.msg || res.data);
          }
        })
        .catch(err => {
          console.error('获取播放地址失败:', err);
        });
    }
  },
};
</script>

<style scoped>
/* 组件自身的 Scoped 样式 */
.player-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  background: #000;
  overflow: hidden;
}

.player-box {
  flex: 1;
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 1;
}

.custom-top-bar {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 40px;
  background: linear-gradient(to bottom, rgba(0,0,0,0.8), rgba(0,0,0,0));
  z-index: 200;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  box-sizing: border-box;
  pointer-events: none;
  transition: opacity 0.3s ease;
}
.custom-top-bar.hide-bar { opacity: 0; }
.top-bar-left .video-title { color: #fff; font-size: 14px; font-weight: bold; }
.top-bar-right .net-speed { color: #00ff00; font-size: 12px; font-family: monospace; }
</style>

<style>
/* =========================================
   1. 基础显隐控制 (映射 controlsConfig)
   ========================================= */

/* 网速显示 */
.player-wrapper.hide-speed .easyplayer-speed {
  display: none !important;
}

/* 解码器/清晰度选择面板 */
.player-wrapper.hide-code-select .easyplayer-controls-code-wrap {
  display: none !important;
}

/* 整个底部栏 */
.player-wrapper.hide-bottom-bar .easyplayer-controls {
  display: none !important;
}

/* 播放/暂停按钮 */
.player-wrapper.hide-btn-play .easyplayer-play,
.player-wrapper.hide-btn-play .easyplayer-pause {
  display: none !important;
}

/* 音量按钮 */
.player-wrapper.hide-btn-audio .easyplayer-volume {
  display: none !important;
}

/* 截图按钮 */
.player-wrapper.hide-btn-screenshot .easyplayer-screenshot {
  display: none !important;
}

/* 全屏按钮 */
.player-wrapper.hide-btn-fullscreen .easyplayer-fullscreen,
.player-wrapper.hide-btn-fullscreen .easyplayer-fullscreen-exit {
  display: none !important;
}

/* 录制按钮 (原生图标) */
.player-wrapper.hide-btn-record .easyplayer-record,
.player-wrapper.hide-btn-record .easyplayer-record-stop {
  display: none !important;
}

/* 拉伸按钮 (原生图标) */
.player-wrapper.hide-btn-stretch .easyplayer-stretch {
  display: none !important;
}

/* 电子放大按钮 */
.player-wrapper.hide-btn-zoom .easyplayer-zoom,
.player-wrapper.hide-btn-zoom .easyplayer-zoom-stop {
  display: none !important;
}

/* =========================================
   2. 样式修正与美化
   ========================================= */

/* 强制隐藏整个控制栏 (当鼠标移出且 force-hide-controls 为 true 时) */
.player-wrapper.force-hide-controls .easyplayer-controls {
  opacity: 0 !important;
  visibility: hidden !important;
  transition: opacity 0.3s ease;
}

/* --- 录制状态栏位置修正 --- */

/* 默认隐藏,防止初始闪烁 */
.player-wrapper .easyplayer-recording {
  display: none;
  position: absolute !important;
  top: 50px !important;
  left: 50% !important;
  transform: translateX(-50%) !important;
  z-index: 200 !important;
  background: rgba(255, 0, 0, 0.6);
  border-radius: 4px;
  padding: 4px 12px;
}

/* 当播放器将其设为 block 时,强制改为 flex 布局 */
.player-wrapper .easyplayer-recording[style*="block"] {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

.player-wrapper .easyplayer-recording-time {
  margin: 0 8px;
  font-size: 14px;
  color: #fff;
  line-height: 1;
}

.player-wrapper .easyplayer-recording-stop {
  height: auto !important;
  display: flex !important;
  align-items: center !important;
  cursor: pointer;
}

/* --- 拉伸按钮图标修正 (使用 SVG) --- */
.player-wrapper .easyplayer-stretch {
  font-size: 0 !important;
  width: 34px !important;
  height: 100% !important;
  display: flex !important;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.player-wrapper .easyplayer-stretch::after {
  content: '';
  display: block;
  width: 20px;
  height: 20px;
  background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg' width='200' height='200'%3E%3Cpath d='M128 128h298.667v85.333H195.2l201.6 201.6-60.373 60.374-201.6-201.6v231.466H49.067V49.067h78.933V128zM896 896H597.333v-85.333H828.8l-201.6-201.6 60.373-60.374 201.6 201.6V518.933h85.334v377.067h-78.934V896z' fill='%23ffffff'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  opacity: 0.8;
}

.player-wrapper .easyplayer-stretch:hover::after {
  opacity: 1;
}

/* --- 电子放大控制栏位置修正 --- */
.player-wrapper .easyplayer-zoom-controls {
  position: absolute !important;
  top: 50px !important;
  left: 50% !important;
  transform: translateX(-50%);
  z-index: 199 !important;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 20px;
  padding: 0 10px;
}

/* 加载动画层样式 - 双环渐变旋转(柔和蓝色版) */
.player-wrapper .easyplayer-loading-img {
  background-color: #000 !important; /* 黑色背景 */
  background-image: none !important; /* 清除外部GIF */
  width: 100%;
  height: 100%;
  display: block;
  position: relative;
  animation: none !important; /* 取消原生动画 */
}

/* 外层圆环(带渐变光效)- 核心修改:柔和科技蓝 */
.player-wrapper .easyplayer-loading-img::before {
  content: "";
  width: 70px;
  height: 70px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 4px solid transparent;
  border-top-color: #1e90ff; /* 柔和科技蓝(不刺眼的天蓝色) */
  border-right-color: #1e90ff;
  border-radius: 50%;
  animation: spin 1.2s linear infinite;
  z-index: 1;
  box-shadow: 0 0 15px rgba(30, 144, 255, 0.3); /* 匹配蓝色的柔和光晕 */
}

/* 内层圆环(白色半透明)- 保留不变,保证层次感 */
.player-wrapper .easyplayer-loading-img::after {
  content: "";
  width: 50px;
  height: 50px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 3px solid rgba(255, 255, 255, 0.3); /* 白色半透明 */
  border-bottom-color: rgba(255, 255, 255, 0.8); /* 底部高亮 */
  border-radius: 50%;
  animation: spin-reverse 0.8s linear infinite;
  z-index: 2;
}

/* 旋转动画(顺时针) */
@keyframes spin {
  0% { transform: translate(-50%, -50%) rotate(0deg); }
  100% { transform: translate(-50%, -50%) rotate(360deg); }
}

/* 旋转动画(逆时针) */
@keyframes spin-reverse {
  0% { transform: translate(-50%, -50%) rotate(0deg); }
  100% { transform: translate(-50%, -50%) rotate(-360deg); }
}

/* 隐藏加载文字 */
.player-wrapper .easyplayer-loading-text {
  display: none !important;
}

/* =========================================
   3. 自定义右键菜单
   ========================================= */

/* 隐藏原生右键菜单 - 使用更高优先级 */
[class*="easyplayer-contextmenu"] {
  display: none !important;
  visibility: hidden !important;
}

/* 自定义右键菜单样式 */
.custom-contextmenu {
  position: absolute;
  z-index: 2147483647 !important;
  background: rgba(30, 30, 30, 0.95);
  border: 1px solid rgba(80, 80, 80, 0.8);
  border-radius: 6px;
  padding: 6px 0;
  min-width: 140px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
}

/* 全屏模式下使用 fixed 定位,并强制使用视口作为定位上下文 */
.custom-contextmenu.menu-fixed {
  position: fixed !important;
  top: var(--menu-top, 0) !important;
  left: var(--menu-left, 0) !important;
  transform: none !important;
}

.custom-contextmenu .contextmenu-divider {
  height: 1px;
  background: rgba(80, 80, 80, 0.6);
  margin: 4px 0;
}

.custom-contextmenu .contextmenu-item {
  padding: 8px 16px;
  color: #fff;
  font-size: 13px;
  cursor: pointer;
  transition: background 0.2s;
}

.custom-contextmenu .contextmenu-item:hover {
  background: rgba(30, 144, 255, 0.6);
}
</style>