<template>
  <div class="camera-item">
    <div class="camera-name">
      {{ props.name }}
    </div>
    <video ref="previewVideoRef" class="camera-player"></video>
    <div class="overlay" @click="openPlayModal">
      <!-- <img src="../assets/stLine-play-l@3x.png" alt="" width="40" height="40" /> -->
      <span class="iconfont icon-bofang_o" style="font-size: 60px"></span>
    </div>
    <div v-if="showModal" class="modal-overlay" @click="closePlayModal">
      <span
        v-if="isFullscreen"
        class="quit-fullscreen iconfont icon-quxiaoquanping_o"
        @click.stop="exitFullscreen"
      ></span>
      <div ref="rotateElementRef" :class="`modal`">
        <video
          ref="videoElementRef"
          :class="`camera-player ${isFullscreen ? 'fullscreen-video' : ''}`"
        ></video>

        <div
          :class="`video-overlay  ${isFullscreen ? 'fullscreen-video' : ''}`"
          @click.stop="switchPlayStatus"
        >
          <div v-if="isFullscreen" class="arrow-control">
            <div
              :class="`up iconfont icon-up ${pressed.up ? 'pressed' : ''}`"
              @touchend="moveCamera('stop')"
              @touchstart="moveCamera('up')"
              @contextmenu.prevent
            ></div>
            <div
              :class="`down  iconfont icon-down ${
                pressed.down ? 'pressed' : ''
              }`"
              @touchend="moveCamera('stop')"
              @touchstart="moveCamera('down')"
              @contextmenu.prevent
            ></div>
            <div
              :class="`left iconfont icon-left ${
                pressed.left ? 'pressed' : ''
              }`"
              @touchend="moveCamera('stop')"
              @touchstart="moveCamera('left')"
              @contextmenu.prevent
            ></div>
            <div
              :class="`right iconfont icon-right ${
                pressed.right ? 'pressed' : ''
              }`"
              @touchend="moveCamera('stop')"
              @touchstart="moveCamera('right')"
              @contextmenu.prevent
            ></div>
          </div>
          <div
            v-if="!isFullscreen"
            class="iconfont icon-quanping_o fullscreen"
            @click.stop="videoFullscreen"
          ></div>
        </div>
      </div>
    </div>
  </div>
</template>
<script name="camera" setup>
import { nextTick, onUnmounted, reactive, ref, toRefs } from "vue";
import flvjs from "flv.js";
import axios from "axios";
// import { useRoute } from "vue-router";
const props = defineProps({
  name: {
    type: String,
  },
  source: {
    type: String,
    default:
      "https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/flv/xgplayer-demo-360p.flv",
  },
});
const { source } = toRefs(props);
// const route = useRoute();
// document.title = route.query.proname;
const showModal = ref(false);
let flvPlayer;
// const previewVideoRef = ref();
// onMounted(() => {
//   const flvPlayer = flvjs.createPlayer({
//     type: "flv",
//     url: props.source,
//     isLive: true,
//   });
//   flvPlayer.attachMediaElement(previewVideoRef.value);
//   flvPlayer.load();
//   console.log();
//   // loadVideo(props.source);
// });

const openPlayModal = () => {
  showModal.value = true;
  nextTick(() => {
    flvPlayer = flvjs.createPlayer({
      type: "flv",
      url: props.source,
    });
    if (flvjs.isSupported()) {
      flvPlayer.attachMediaElement(videoElementRef.value);
      // flvPlayer.attachMediaElement();
      flvPlayer.load();
      flvPlayer.on("ERROR", flvPlayerEventHandler);
      flvPlayer.play();
    }
  });
};

// file为视频的文件对象，可使用 input[file] 进行获取
const loadVideo = async (url) => {
  const resp = await axios.get(url);
  const file = new File([resp.data], "monitor.flv");
  console.log(file);
  return new Promise(function (resolve, reject) {
    const videoElem = document.createElement("video");
    const dataUrl = URL.createObjectURL(file);
    // 当前帧的数据是可用的
    videoElem.onloadeddata = function () {
      resolve(videoElem);
    };
    videoElem.onerror = function (e) {
      console.log(e);
      reject("video 后台加载失败");
    };
    // 设置 auto 预加载数据， 否则会出现截图为黑色图片的情况
    videoElem.setAttribute("preload", "auto");
    videoElem.src = dataUrl;
  });
};

const closePlayModal = () => {
  flvPlayer.on("ERROR", flvPlayerEventHandler);
  flvPlayer.pause();
  flvPlayer.unload();
  flvPlayer.detachMediaElement();
  flvPlayer.destroy();
  flvPlayer = null;
  showModal.value = false;
};
const videoElementRef = ref();
// const playBtnRef = ref();
// let flvPlayer = flvjs.createPlayer({
//   type: "flv",
//   url: "https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/flv/xgplayer-demo-360p.flv",
// });

const flvPlayerEventHandler = (e) => {
  console.log(e);
};
// 切换播放状态
const switchPlayStatus = () => {
  if (!videoElementRef.value) return;
  if (videoElementRef.value.paused) {
    console.log(flvPlayer);
    flvPlayer.play();
  } else {
    flvPlayer.pause();
  }
};
const isFullscreen = ref(false);
const rotateElementRef = ref();
const videoFullscreen = () => {
  const scale = screen.availWidth / videoElementRef.value.offsetHeight;
  videoElementRef.value.style.setProperty("--scale", scale);
  videoElementRef.value.parentNode.style.setProperty("--scale", scale);
  isFullscreen.value = true;
};

const token = ref("");
const loadToken = async () => {
  const url = new URL(source.value);
  const resp = await axios.get(
    `${url.protocol}//${url.host}/api/v1/login?username=admin&password=de240967f3dff8b62df33e719d646e3e`
  );
  return resp.data.URLToken;
};

const pressed = reactive({
  left: false,
  right: false,
  up: false,
  down: false,
});
const moveCamera = async (arrow) => {
  if (!token.value) {
    token.value = await loadToken();
  }

  const serial = source.value.split("/flv/hls/")[1].split("_")[0];
  const url = new URL(source.value);
  await axios.get(
    `${url.protocol}//${url.host}/api/v1/control/ptz?serial=${serial}&code=${serial}&command=${arrow}&token=${token.value}`
  );
  if (arrow === "stop") {
    pressed.left = false;
    pressed.right = false;
    pressed.up = false;
    pressed.down = false;
  } else {
    pressed[arrow] = true;
  }
};

const exitFullscreen = () => {
  isFullscreen.value = false;
};
onUnmounted(() => {
  console.log("destroy player here");

  function flvDestroy() {
    flvPlayer.off("ERROR", flvPlayerEventHandler);
    flvPlayer.pause();
    flvPlayer.unload();
    flvPlayer.detachMediaElement();
    flvPlayer.destroy();
    flvPlayer = null;
  }

  if (flvPlayer) {
    flvDestroy();
  }
});
</script>
<style lang="scss" scoped>
@import "../assets/fonts/iconfont.css";

.camera-item {
  // height: 300px;
  background-color: white;
  border-radius: 10px;
  margin-bottom: 20px;
  position: relative;

  .camera-name {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    background-color: #c6c6c6;
    border-radius: 10px 10px 0 0;
    color: white;
    top: 0;
    left: 0;
    font-size: 20px;
    height: 50px;
    width: 100%;
    z-index: 99;
  }

  .camera-player {
    width: 100%;
    height: 400px;
    border-radius: 10px;
  }

  .overlay {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 99;
  }

  .modal-overlay {
    width: 100vw;
    height: 100vh;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 999;
    // position: relative;
    background-color: rgba(153, 153, 153, 0.363);

    .quit-fullscreen {
      position: fixed;
      font-size: 60px;
      left: 25px;
      bottom: 25px;
      z-index: 100;
    }

    .modal {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 90vw;
      // height: 60vw;
      background-color: #fff;
      border-radius: 2vw;

      .fullscreen-video {
        transform-origin: center;
        transform: scale(var(--scale)) rotate(90deg);
      }

      .video-overlay {
        width: 100%;
        height: 100%;
        position: absolute;
        //background-color: #eee;
        left: 0;
        top: 0;
        // display: flex;
        // align-items: center;
        // justify-content: center;
        // z-index: 99;
        // position: relative;
        .fullscreen {
          position: absolute;
          z-index: 99;
          right: 10px;
          bottom: 10px;
          font-size: 60px;
          width: 60px;
          height: 60px;
          background-color: #eee;
          color: #777;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 12px;
        }

        .exit-fullscreen {
          position: absolute;
          font-size: 40px;
          color: white;
          z-index: 99999;
          right: 5px;
          bottom: 5px;
        }

        .arrow-control {
          width: 100px;
          height: 100px;
          border-radius: 50%;
          background-color: rgba(255, 255, 255, 0.56);
          position: absolute;
          right: 25px;
          bottom: 25px;
          z-index: 9999;

          .iconfont {
            width: 32px;
            height: 32px;
            font-size: 32px;
            position: absolute;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
          }

          .iconfont.pressed {
            background-color: gray;
          }

          .up {
            left: 50%;
            transform: translateX(-50%);
            top: 4px;
          }

          .down {
            left: 50%;
            transform: translateX(-50%);
            bottom: 4px;
          }

          .left {
            top: 50%;
            transform: translateY(-50%);
            left: 4px;
          }

          .right {
            top: 50%;
            transform: translateY(-50%);
            right: 4px;
          }
        }
      }
    }
  }
}
</style>
