import { onBeforeUnmount, ref, nextTick } from "vue";
import { getPlaySign } from "@/api/video";
import { videoRecord } from "@/api/shortVideo";
import TCPlayer from "tcplayer.js";
import "tcplayer.js/dist/tcplayer.min.css";
import dayjs from "dayjs";

export default function useVideoPlay() {
  let playCtx = ref();
  // let readDuration = 0;
  let videoId = "";

  let time = null;
  let currentTime = new Date();
  const uploadVideoRecord = () => {
    clearInterval(time);
    time = setInterval(() => {
      videoRecord({
        list: [
          {
            seconds: dayjs(new Date()).diff(currentTime, "second"),
            videoId,
          },
        ],
      });
      currentTime = new Date();
    }, 10000);
  };

  const stopUploadVideoRecord = () => {
    clearInterval(time);
    videoRecord({
      list: [
        {
          seconds: dayjs(new Date()).diff(currentTime, "second"),
          videoId,
        },
      ],
    });
    currentTime = new Date();
  };

  const playVideo = async ({ detail, videoEl }) => {
    videoId = detail.id;
    if (playCtx.value) {
      playCtx.value.dispose();
    }
    console.log(detail.playType);
    const id = `player-container-id-${new Date().getTime()}`;
    videoEl.innerHTML = `<video width="100%" height="100%" id="${id}"  webkit-playsinline="true" playsinline="true" renderer="standard" raw-controls=""></video>`;

    const baseConfig = {
      autoplay: true,
    };
    let ret = await getPlaySign({
      fileId: detail.fileId,
      audioVideoType: "RawAdaptive",
    });

    if (ret.code === 0) {
      baseConfig.appID = ret.data.appId;
      baseConfig.fileID = ret.data.fileId;
      baseConfig.psign = ret.data.psign;
    }

    playCtx.value = TCPlayer(id, baseConfig);
    if (playCtx.value) {
      playCtx.value.on("error", function (error) {
        // 做一些处理
        console.log("playError", error);
      });
      playCtx.value.on("timeupdate", function () {
        // 做一些处理
        // readDuration = playCtx.value.currentTime();
      });

      playCtx.value.on("webrtcevent", (res) => {
        console.log("webrtcevent", res);
        if (res.data.code === 2005) {
          nextTick(() => {
            console.log("WeixinJSBridge", window.WeixinJSBridge);
            if (
              typeof window.WeixinJSBridge == "object" &&
              typeof window.WeixinJSBridge.invoke == "function"
            ) {
              window.WeixinJSBridge.invoke("getNetworkType", {}, () => {
                //video.player.play();//这里使用的是基于video.js的vue-player插件
                playCtx.value.play();
              });
            }
          });
        } else if (res.data.code === 1010) {
          console.log("卡顿结束", playCtx.value);
          if (
            typeof window.WeixinJSBridge == "object" &&
            typeof window.WeixinJSBridge.invoke == "function"
          ) {
            window.WeixinJSBridge.invoke("getNetworkType", {}, () => {
              //video.player.play();//这里使用的是基于video.js的vue-player插件
              playCtx.value.play();
            });
          }
        }
      });
      playCtx.value.on("blocked", () => {
        nextTick(() => {
          console.log("WeixinJSBridge-blocked", window.WeixinJSBridge);
          if (
            typeof window.WeixinJSBridge == "object" &&
            typeof window.WeixinJSBridge.invoke == "function"
          ) {
            window.WeixinJSBridge.invoke("getNetworkType", {}, () => {
              //video.player.play();//这里使用的是基于video.js的vue-player插件
              playCtx.value.play();
            });
          }
        });
      });

      playCtx.value.on("play", uploadVideoRecord);

      playCtx.value.on("pause", stopUploadVideoRecord);
      // console.log(playCtx.value);
      // playCtx.value.eventBusEl_.addEventListener("click", function () {
      //   // 当点击发生时，暂停视频播放
      //   playCtx.value.pause();
      // });
    }
  };

  onBeforeUnmount(() => {
    if (playCtx.value) {
      console.log(playCtx.value.duration());
      console.log(playCtx.value.currentTime());
      videoRecord({
        list: [
          {
            seconds: dayjs(new Date()).diff(currentTime, "second"),
            videoId,
          },
        ],
      });
      playCtx.value.dispose();
    }
  });

  window.addEventListener("unload", function () {
    if (playCtx.value) {
      videoRecord({
        list: [
          {
            seconds: dayjs(new Date()).diff(currentTime, "second"),
            videoId,
          },
        ],
      });
      playCtx.value.dispose();
    }
  });
  return {
    playVideo,
    playCtx,
  };
}
