<template>
  <div class="kf-video-item-box " @click="handleClick" ref="stream">
    <video ref="videoRef" controls v-if="!isFlv" autoplay class="kf-video-item" muted></video>
    <!--    <vue3-video-player v-if="!isFlv && initFlag " v-bind="options" autoplay :playsinline="true" ref="playerDom" :core="HLSCore" @waiting="handleVideoError"-->
    <!--      class="kf-video-item" style="width: 100%; height: 100%;display: flex" ></vue3-video-player>-->
    <div v-if="errorMessage"
         style="background:#333;width:100%; height: 100%;display: flex;position:absolute;align-items: center;justify-content: center;">
      <div>{{ errorMessage }}</div>
    </div>
    <div v-if="isFlv" class="kf-video-item-box1">
      <video id="idPlayer" autoplay class="kf-video-item" muted></video>
      <div class="kf-video-item-mask" v-loading="!initFlag" element-loading-text="加载中，请稍候..."
           element-loading-background="rgba(0, 0, 0, 0.5)" v-show="!initFlag">
      </div>
    </div>
  </div>
</template>

<script>
import {computed, nextTick, onMounted, onUnmounted, ref, watch} from 'vue';
import pageModel from '../model/page';
import dataModel from '@/components/ui/model/data';
import {runUntil} from '@/utils/tools.js';
import flvjs from 'flv-h265.js';
import deviceService from '@/service/device';
import {ElMessage} from 'element-plus'
import Hls from 'hls.js';
//import HLSCore from '@cloudgeek/playcore-hls'

export default {
  name: 'kfVideoItem',
  props: {
    props: {
      type: Object,
      default: () => {
      },
    },
  },
  setup(props) {
    onMounted(() => {
      init();
    });
    // 视频元素引用
    const videoRef = ref(null);
    // 初始化 HLS
    // HLS 实例
    let hls = null;
    const initHlsPlayer = (url) => {
      if (Hls.isSupported()) {
        hls = new Hls();
        hls.loadSource(url); // 加载 HLS 视频流
        hls.attachMedia(videoRef.value); // 绑定到 video 元素
        hls.on(Hls.Events.ERROR, (event, data) => {
          console.error('HLS Error:', data);
        });
        hls.on(Hls.Events.MANIFEST_PARSED, () => {
          console.log('HLS 视频加载完成，可以播放');
          videoRef.value.play(); // 自动播放
        });
      } else if (videoRef.value.canPlayType('application/vnd.apple.mpegurl')) {
        // 如果浏览器原生支持 HLS（如 Safari）
        videoRef.value.src = url;
        videoRef.value.addEventListener('loadedmetadata', () => {
          console.log('HLS 视频加载完成，可以播放');
          videoRef.value.play(); // 自动播放
        });
      } else {
        console.error('当前浏览器不支持 HLS 播放');
      }
    };

    let playerDom = ref(null);
    const options = ref({
      muted: true, //静音
      webFullScreen: true,
      speedRate: ["0.75", "1.0", "1.25", "1.5", "2.0"],
      autoPlay: true,
      loop: true,
      preload: 'auto',
      mirror: false,
      lightOff: false,
      control: false,
      controls: false,
      title: '',
      notSupportedMessage: '此视频暂无法播放，请稍后再试',
      src: props.props.src,
    });

    if (window.Kf.config.videoCore) {
      props.props.core = window.Kf.config.videoCore;
    }

    const initFlag = ref(false);
    const stream = ref();

    let player = null;

    const srcVersion = ref(0);

    if (props.props.deviceId) {
      srcVersion.value = 1;
    }

    const updateData = () => {
      srcVersion.value++;
    };

    const src = computed(() => {
      let result = null;
      if (props.props.deviceId && srcVersion.value) {
        console.log("Load video deviceId:", props.props.deviceId);
        let newData = dataModel.getData(props.props, true);
        console.log("Loaded video device:", newData);
        let url = getCameraUrl(newData);
        console.log("Loaded video url:", url);
        if (url.indexOf('/') !== -1) {
          result = url;
        } else {
          result = getImageUrl(url); // static resource
        }
      } else {
        if (props.props.src?.indexOf('/') !== -1) { // 视频网址
          result = props.props.src;
        } else if (props.props.outSrc?.indexOf('/') !== -1) { // 外部视频网址
          result = props.props.outSrc;
        } else {
          result = getImageUrl(props.props.src); // 静态资源
        }
      }
      return result;
    });

    const getImageUrl = function (pubUuid) {
      let url =
          window.Kf.config.server +
          '/api/repo/kf-pub-resource/load-file?uuid=' +
          pubUuid;
      return url;
    };

    const getCameraUrl = (newData) => {
      let url = '';
      if (newData && typeof newData === 'string') {
        url = newData;
      } else if (newData && Array.isArray(newData)) {
        url = newData[0];
      } else if (newData && typeof newData === 'object') {
        if (
            newData?.device &&
            newData.device?.data &&
            newData.device.data?.url
        ) {
          url = newData.device.data.url;
          newData.device.data.url = "";
        } else if (newData?.device) {
          let type = window.Kf?.config?.videoType;
          if (type == undefined) {
            type = "hls";
          }
          deviceService.getCameraUrl(newData.device.provider, newData.device.connId, newData.device.deviceId, type, window.location.protocol).then((res) => {
            if (res?.streamUrl) {
              newData.device.data.url = res.streamUrl;
              srcVersion.value += 1;
            } else {
              // 如果获取不到流媒体地址，则5秒后重试
              setTimeout(() => {
                srcVersion.value += 1;
              }, 5000);
            }
            //newData.device.data.url = "http://172.17.2.77:6666/live.flv";
          });
        }
      }
      return url;
    };

    const isFlv = computed(() => {
      let result = false;
      if (src.value && (src.value.startsWith('rtsp://') || src.value.startsWith('rtmp://') || src.value.endsWith('.flv'))) {
        result = true;
      }
      return result;
    })

    const isNative = computed(() => {
      let result = false;
      if (src.value && (src.value.startsWith('rtsp://') || src.value.startsWith('rtmp://'))) {
        result = true;
      }
      return result;
    })

    watch(src, (newValue, oldValue) => {
      init();
    });
    let isCanPlay = false;
    const init = function () {
      if (player) {
        try {
          player.pause();
          player.unload();
          player.detachMediaElement();
          player.destroy();
          player = null;
        } catch (e) {
        }
      }
      if (hls) {
        hls.destroy();
        hls = null;
      }

      function initFlv() {
        if (flvjs.isSupported()) {
          nextTick(() => {
            console.log('创建播放器');
            let id = new Date().getTime();
            let video =
                stream.value.querySelector('#idPlayer');
            if (video) {
              let url = isNative.value ? `${pageModel.currProject.value.settings.streamServer}/rtsp/${id}/?url=${encodeURIComponent(src.value)}` : src.value;
              player = flvjs.createPlayer({
                type: 'flv',
                isLive: true,
                enableStashBuffer: false,
                url: url
              });
              player.attachMediaElement(video);
              player.on(flvjs.Events.ERROR, (errorType, errorDetail, errorInfo) => {
                console.log("errorType:", errorType);
                console.log("errorDetail:", errorDetail);
                console.log("errorInfo:", errorInfo);
                ElMessage.error("视频播放失败");
                //视频出错后销毁重新创建
                if (player) {
                  player.pause();
                  player.unload();
                  player.detachMediaElement();
                  player.destroy();
                  player = null;
                  initFlv()
                }
              });

              try {
                player.load();
                let playPromise = player.play();
                if (playPromise !== undefined) {
                  playPromise.then(() => {
                    initFlag.value = true;
                    player.play();
                  }).catch(() => {
                  });
                }
              } catch (error) {
                console.log(error);
              }
            }
          });
        }
      }

      if (src.value) {
        if (isFlv.value) {
          runUntil(() => {
            return stream.value != null; // 组件初始化
          }, () => {
            if (isNative.value) { // 原生rtsp/rtmp
              runUntil(
                  () => {
                    return pageModel.currProject.value?.settings?.streamServer != null; // 流媒体服务器
                  },
                  () => {
                    initFlv();
                  },
              );
            } else {
              initFlv();
            }
          });
        } else {
          const extension = src.value.split('?')[0].split('.').pop().toLowerCase();

          switch (extension) {
            case 'm3u8':
              initHlsPlayer(src.value);
              break;
            case 'mp4':
              videoRef.value.src = src.value;
              break;
          }
          // initFlag.value = false;
          // options.value.src = src.value;
          //  nextTick(() => {
          //    initFlag.value = true;})
          //   nextTick(() => {
          //     if (src.value && !isFlv.value) {
          //       playerDom.value.play();
          //       // 获取 video 元素
          //       const videoElement = playerDom.value.$player.$video;
          //       videoElement.addEventListener('error', function(e) {
          //         console.log('视频出错了')
          //         console.log(e)
          //       })
          //       videoElement.addEventListener('loadeddata', function(e) {
          //         console.log('提示当前帧的数据是可用的')
          //         console.log(e)
          //       })
          //       videoElement.addEventListener('timeupdate', function(e) {
          //         console.log('提示当前帧的数据是可用的timeupdate')
          //         console.log(e)
          //         if(playerDom.value){
          //           const readyState = playerDom.value.$player.$video.readyState;
          //           switch (readyState) {
          //             case 0:
          //               errorMessage.value = '没有关于媒体资源的信息';
          //               break;
          //             case 1:
          //               errorMessage.value = '已获取元数据，但没有可用的数据';
          //               break;
          //             case 2:
          //               errorMessage.value = '有当前播放位置的数据，但不足以播放下一帧';
          //               break;
          //             case 3:
          //               errorMessage.value = '有足够的数据可以播放至少几帧';
          //               break;
          //             case 4:
          //               errorMessage.value = '';
          //               break;
          //             default:
          //               errorMessage.value = '未知状态';
          //           }
          //         }
          //       })
          //       const errorLayer =
          //         playerDom.value.$container.querySelector(
          //           '.error-layer',
          //         );
          //       if (errorLayer) {
          //         errorLayer.style.setProperty('display', 'none');
          //       }
          //     }
          //   });
          // });
        }
      }
    }

    const fullscreen = ref(false);

    const handleClick = () => {
      if (fullscreen.value) {
        fullscreen.value = false;
        exitFullscreen(stream.value);
      } else {
        fullscreen.value = true;
        requestFullscreen(stream.value);
      }
    }

    const requestFullscreen = (elem) => {
      try {
        if (elem.requestFullscreen) {
          elem.requestFullscreen();
        } else if (elem.mozRequestFullScreen) {
          elem.mozRequestFullScreen();
        } else if (elem.webkitRequestFullscreen) {
          elem.webkitRequestFullscreen();
        } else if (elem.msRequestFullscreen) {
          elem.msRequestFullscreen();
        }
      } catch (e) {
        console.log(e);
      }
    }

    const exitFullscreen = (elem) => {
      if (document.exitFullScreen) {
        document.exitFullScreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    }

    onUnmounted(() => {
      if (player) {
        try {
          player.destroy();
          player = null;
        } catch (e) {
        }
      }
      if (hls) {
        if (videoRef.value) {
          videoRef.value.pause();
        }
        hls.destroy();
        hls = null;
      }
    });
    const errorMessage = ref('');

    const handleVideoError = (event) => {
      errorMessage.value = '视频播放失败，请检查网络、跨域设置或视频源';
      console.error('Video error:', event);
    };

    return {
      options,
      initFlag,
      playerDom,
      videoRef,
      stream,
      updateData,
      isFlv,
      isNative,
      src,
      errorMessage,
      handleVideoError,
      handleClick,
      fullscreen,
      HLSCore: props.props.core
    };
  },
};
</script>

<style lang="scss">
::v-deep(.vue-core-video-player-layers) {
  z-index: 0;
}

.kf-video-item-box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}


.kf-video-item-box1 {
  width: 100%;
  height: 100%;
}

.kf-video-item {
  width: 100%;
  height: 100%;
}

.kf-video-item-mask {
  position: absolute;
  top: 25px;
  left: 0;
  width: 100%;
  height: calc(100% - 25px);
  background-color: rgba(0, 0, 0, 0.5);
}
</style>
