import { onBeforeUnmount, ref, nextTick } from "vue";
import { queryPlayInfo, getPlaySign } from "@/api/video";
import TCPlayer from "tcplayer.js";
import "tcplayer.js/dist/tcplayer.min.css";
import store from "@/store/index";
import { isMobi } from "@/utils/index";

export default function useVideoPlay(
  $liveStatusObj,
  detail,
  stompClient,
  setPlayCtx
) {
  let playCtx = ref();
  let showPlayBtn = ref(false);
  let sessionId = localStorage.getItem(
    `sessionId-${store.state.userInfo.userId}-${detail.id}`
  );
  console.log("sessionId", sessionId);
  const playVideo = async (videoEl) => {
    showPlayBtn.value = false;
    if (playCtx.value) {
      playCtx.value.dispose();
    }

    const id = `player-container-id-${new Date().getTime()}`;
    if (
      (detail.playType === 2 ||
        detail.liveStatus === $liveStatusObj.FinishPlay) &&
      detail.libraryList &&
      detail.libraryList.length
    ) {
      videoEl.innerHTML = `<video width="100%" height="100%" id="${id}" webkit-playsinline="true" playsinline="true" autoplay></video>`;
      let promiseAll = [];
      detail.libraryList.forEach((item) => {
        promiseAll.push(
          getPlaySign({
            fileId: item.fileId,
            audioVideoType: item.transStatus === 2 ? "RawAdaptive" : "Original",
          })
        );
      });
      let retPromiseAll = await Promise.all(promiseAll);

      if (retPromiseAll.length) {
        const baseConfig = {
          autoplay: true,
          poster: detail.imgUrl,
          appID: retPromiseAll[0].data.appId,
          fileID: retPromiseAll[0].data.fileId,
          psign: retPromiseAll[0].data.psign,
          controlBar: {
            fullscreenToggle: true,
            volumePanel: false,
          },
        };
        if (detail.libraryList.length > 1) {
          baseConfig.PlayList = {
            data: [],
            title: "视频回放列表", // 列表标题
            loop: true, // 是否循环播放
          };
          retPromiseAll.forEach((ret, index) => {
            if (ret.code === 0) {
              baseConfig.PlayList.data.push({
                fileID: ret.data.fileId,
                appID: ret.data.appId,
                duration: detail.libraryList[index].duration, // 视频时长
                text: detail.libraryList[index].name, // 视频名称
                psign: ret.data.psign, // 播放器签名
                img: detail.imgUrl, // 封面图
              });
            }
          });
        }
        playCtx.value = TCPlayer(id, baseConfig);
        if (playCtx.value) {
          setPlayCtx({ playCtx: playCtx.value });
          playCtx.value.on("loadedmetadata", () => {
            const currentTime = localStorage.getItem(
              `${store.state.userInfo.userId}-${detail.id}-videoPlayTime`,
              playCtx.value.currentTime()
            );
            if (playCtx.value && currentTime) {
              playCtx.value.currentTime(Number(currentTime));
            }
          });

          playCtx.value.on("error", function (error) {
            // 做一些处理
            console.log("playError", error);
          });
          playCtx.value.on("play", () => {
            // 做一些处理
            console.log("play", {
              reportVideoTopic: `/app/chat/report/video/${detail.id}`,
              userId: store.state.userInfo.userId,
              reportType: 2,
              GroupId: detail.id,
            });
            setTimeout(() => {
              const updateUserLookTime = new Date().getTime();
              stompClient.value &&
                stompClient.value.publish({
                  destination: `/app/chat/report/video/${detail.id}`,
                  headers: {
                    userId: store.state.userInfo.userId,
                    reportType: 2,
                    GroupId: detail.id,
                    sessionId,
                    requestId: updateUserLookTime,
                  },
                });
            }, Math.floor(Math.random() * 10000));
          });
          playCtx.value.on("pause", () => {
            // 做一些处理
            console.log("pause", {
              reportVideoTopic: `/app/chat/report/video/${detail.id}`,
              userId: store.state.userInfo.userId,
              reportType: 1,
              GroupId: detail.id,
            });
            setTimeout(() => {
              const updateUserLookTime = new Date().getTime();
              stompClient.value &&
                stompClient.value.publish({
                  destination: `/app/chat/report/video/${detail.id}`,
                  headers: {
                    userId: store.state.userInfo.userId,
                    reportType: 1,
                    GroupId: detail.id,
                    sessionId,
                    requestId: updateUserLookTime,
                  },
                });
            }, Math.floor(Math.random() * 10000));
          });
          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" &&
                  isMobi
                ) {
                  window.WeixinJSBridge.invoke("getNetworkType", {}, () => {
                    //video.player.play();//这里使用的是基于video.js的vue-player插件
                    playCtx.value.play();
                  });
                }
              });
            } else if (res.data.code === 1010) {
              console.log("录播卡顿结束");
              // 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" &&
                isMobi
              ) {
                window.WeixinJSBridge.invoke("getNetworkType", {}, () => {
                  //video.player.play();//这里使用的是基于video.js的vue-player插件
                  playCtx.value.play();
                });
              }
            });
          });
          playCtx.value.on("timeupdate", () => {
            localStorage.setItem(
              `${store.state.userInfo.userId}-${detail.id}-videoPlayTime`,
              playCtx.value.currentTime()
            );
          });
        }
      }
    } else if (
      [$liveStatusObj.InLive, $liveStatusObj.PausePlay].includes(
        detail.liveStatus
      )
    ) {
      videoEl.innerHTML = `<video width="100%" height="100%"  id="${id}" webkit-playsinline="true" playsinline="true" autoplay></video>`;
      // liveStatus	直播状态: 1直播中; 2未开始; 3已暂停; 4已结束
      let ret = await queryPlayInfo({ id: detail.id });
      if (ret.code === 0) {
        if (detail.liveStatus === $liveStatusObj.InLive) {
          const baseConfig = {
            autoplay: true,
            poster: detail.imgUrl,
            controls: true,
          };
          playCtx.value = TCPlayer(id, {
            ...baseConfig,
            webrtcConfig: { connectRetryDelay: 20 },
            controlBar: {
              playToggle: false,
              fullscreenToggle: true,
              volumePanel: false,
            },
          });
          ret.data && ret.data.playUrl && playCtx.value.src(ret.data.playUrl);
          if (playCtx.value) {
            setPlayCtx({ playCtx: playCtx.value });
            playCtx.value.on("error", (error) => {
              // 做一些处理
              showPlayBtn.value = true;
              console.log("playError", error);
            });
            playCtx.value.on("play", (error) => {
              // 做一些处理
              console.log("play", error);
              setTimeout(() => {
                const updateUserLookTime = new Date().getTime();
                stompClient.value &&
                  stompClient.value.publish({
                    destination: `/app/chat/report/video/${detail.id}`,
                    headers: {
                      userId: store.state.userInfo.userId,
                      reportType: 2,
                      GroupId: detail.id,
                      sessionId,
                      requestId: updateUserLookTime,
                    },
                  });
              }, Math.floor(Math.random() * 10000));
            });
            playCtx.value.on("pause", (error) => {
              // 做一些处理
              console.log("pause", error);
              setTimeout(() => {
                const updateUserLookTime = new Date().getTime();
                stompClient.value &&
                  stompClient.value.publish({
                    destination: `/app/chat/report/video/${detail.id}`,
                    headers: {
                      userId: store.state.userInfo.userId,
                      reportType: 1,
                      GroupId: detail.id,
                      sessionId,
                      requestId: updateUserLookTime,
                    },
                  });
              }, Math.floor(Math.random() * 10000));
            });
            playCtx.value.on("webrtcevent", (res) => {
              console.log("webrtcevent-res", res);
              if (res.data.code === 2005) {
                console.log(
                  "自动播放被劫持了，监听的是webrtcevent方法，code是2005"
                );
                nextTick(() => {
                  console.log("WeixinJSBridge", window.WeixinJSBridge);
                  if (
                    typeof window.WeixinJSBridge == "object" &&
                    typeof window.WeixinJSBridge.invoke == "function" &&
                    isMobi
                  ) {
                    window.WeixinJSBridge.invoke("getNetworkType", {}, () => {
                      //video.player.play();//这里使用的是基于video.js的vue-player插件
                      playCtx.value && playCtx.value.play();
                    });
                  }
                });
              } else if (res.data.code === 1010) {
                console.log("卡顿结束1010");
                // 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", () => {
              console.log("自动播放被劫持了，监听的是blocked方法");
              nextTick(() => {
                console.log("WeixinJSBridge-blocked", window.WeixinJSBridge);
                if (
                  typeof window.WeixinJSBridge == "object" &&
                  typeof window.WeixinJSBridge.invoke == "function" &&
                  isMobi
                ) {
                  window.WeixinJSBridge.invoke("getNetworkType", {}, () => {
                    //video.player.play();//这里使用的是基于video.js的vue-player插件
                    playCtx.value.play();
                  });
                }
              });
            });
            playCtx.value.on("fullscreenchange", () => {
              playCtx.value && playCtx.value.play();
            });
          }
        }
      }
    }
  };

  // const manualPlay = () => {
  //   playCtx.value && playCtx.value.play();
  //   showPlayBtn.value = false;
  // };

  onBeforeUnmount(() => {
    if (playCtx.value) {
      playCtx.value.dispose();
    }
  });

  window.addEventListener("unload", function (event) {
    if (playCtx.value) {
      playCtx.value.dispose();
    }
    event.returnValue = "你确定要离开这个页面吗？";
  });
  return {
    playVideo,
    playCtx,
    showPlayBtn,
  };
}
