import { onMounted, onBeforeUnmount, ref, nextTick } from "vue";
import { useRoute } from "vue-router";
import { useStore } from "vuex";
import { liveMsgSend, sendLiveShare } from "@/api/video";
import emitter from "@/utils/emitter";
import useWebSocket from "@/hooks/useWebSocket";
import useVideoPlay from "@/hooks/useVideoPlay";
import useGetLiveStatusObj from "@/hooks/useGetLiveStatusObj";
import useDisableScroll from "@/hooks/useDisableScroll";

export default function ({ detail, videoClass }) {
  const $liveStatusObj = useGetLiveStatusObj();
  const { addScrollEvent } = useDisableScroll();

  const liveStatus = ref(detail.liveStatus); // 直播状态
  const isSpeak = ref(detail.isSpeak === 2); // 是否允许互动

  const online = ref(detail.online); // 在线人数
  const questionnaireTipRef = ref();
  const questionId = ref(); // 问卷id
  const questionTitle = ref();

  const activityObj = ref({}); // 活动内容
  const carPushObj = ref({}); // 推送购物车内容

  const discountCouponRef = ref();

  const couponDetail = ref({});

  const store = useStore();
  const route = useRoute();

  const { stompClient, setPlayCtx } = useWebSocket({
    id: detail.id,
    chatMessage,
    subMessage,
    saleUserId: route.query.saleUserId ? route.query.saleUserId : "",
  });
  const { playVideo, playCtx, showPlayBtn } = useVideoPlay(
    $liveStatusObj,
    detail,
    stompClient,
    setPlayCtx
  );

  onMounted(async () => {
    if (
      [$liveStatusObj.InLive, $liveStatusObj.PausePlay].includes(
        liveStatus.value
      ) ||
      ((liveStatus.value === $liveStatusObj.FinishPlay ||
        detail.playType === 2) &&
        detail.libraryList &&
        detail.libraryList.length)
    ) {
      startPlay();
    }
  });

  async function startPlay() {
    nextTick(async () => {
      console.log(document.querySelector(videoClass));
      await playVideo(document.querySelector(videoClass));
      nextTick(() => {
        addScrollEvent(".tcp-playlist-box");
      });
    });
  }

  onBeforeUnmount(() => {
    emitter.off("showDiscountCoupon");
    emitter.off("informMsgListPush");
    emitter.off("emSendMsg");
    emitter.off("onShareInform");
  });

  function processingData(data) {
    if (data && data.type === 3) {
      online.value = data.online;
      if (store.state.userInfo.userId !== data.userId) {
        // 判断是否是本人进入直播间
        // informMsgList.value.push(data);
        store.commit("setInteractMsg", {
          type: 1,
          data,
        });
        // informMsgObj.value[data.id] = data
        // informMsgListIds.value.push(data.id)
        if (data.replyBasic) {
          store.commit("setReplyMsgObj", data);
          // replyBasicInformMsgObj[data.replyBasic.id] = data
        }
      }
    } else {
      if (data.type !== 1) {
        if (data.type === 9) {
          // 购物车产品数据有变化
          emitter.emit("updateCar");
        }
        store.commit("setInteractMsg", {
          type: 1,
          data,
        });
        if (data.replyBasic) {
          store.commit("setReplyMsgObj", data);
        }
      } else {
        // 获取其他用户发送的互动消息，需要去重下
        if (!store.state.interactMsgObj.msgListIds.includes(data.id)) {
          store.commit("setInteractMsg", {
            type: 1,
            data,
          });
          if (data.replyBasic) {
            store.commit("setReplyMsgObj", data);
          }
        }
      }
    }
  }

  function chatMessage(msg) {
    // 接收群聊接收消息路径
    // 消息类型：1普通消息；2推荐产品消息；3进入直播间消息；4用户关注投顾消息；5分享直播间消息；6开启互动消息；7关闭互动消息; 8下单产品； 9购物车产品数据量修改; 10购物车产品上架; 11问卷
    console.log("msgList", msg);
    let bodyObj = JSON.parse(msg.body);
    if (Array.isArray(bodyObj.data)) {
      bodyObj.data.forEach((data) => {
        processingData(data);
      });
    } else {
      processingData(bodyObj.data);
    }
  }

  function subMessage(msg) {
    // 订阅通知路径
    console.log("subMessage", msg);
    let msgBody = JSON.parse(msg.body);
    if (msgBody.code !== 0) return;
    let Obj = {};
    switch (msgBody.data.type) {
      case 1:
        emitter.emit("informUserInRoom", msgBody.data.data);
        break;
      case 2:
        if (liveStatus.value === Number(msgBody.data.data)) return;
        // 直播状态
        liveStatus.value = Number(msgBody.data.data);
        emitter.emit(
          "updateVideoDetail",
          msgBody.data.realEndTime
            ? {
                liveStatus: liveStatus.value,
                endTime: msgBody.data.realEndTime,
              }
            : { liveStatus: liveStatus.value }
        );
        if (
          liveStatus.value === $liveStatusObj.InLive ||
          (liveStatus.value === $liveStatusObj.FinishPlay &&
            detail.libraryList &&
            detail.libraryList.length)
        ) {
          startPlay();
        } else if (
          [$liveStatusObj.PausePlay, $liveStatusObj.FinishPlay].includes(
            liveStatus.value
          )
        ) {
          if (playCtx.value) {
            playCtx.value.dispose();
            playCtx.value = "";
          }
        }
        break;
      case 3:
        // 产品状态
        break;
      case 4:
        // 活动通知
        Obj = msgBody.data.data ? JSON.parse(msgBody.data.data) : "";
        if (
          Obj &&
          (Obj.activityRang === "2" ||
            (Obj.activityRang === "1" &&
              !Object.keys(activityObj.value).length))
        ) {
          activityObj.value = Obj;
        }
        break;
      case 5:
        // console.log("msgBody.data", informMsgList.value, msgBody.data);
        // for(let i=0; i<informMsgList.value.length; i++) {
        //   if(informMsgList.value[i].id === Number(msgBody.data.data)) {
        //     informMsgList.value.splice(i,1)
        //     informMsgListIds.value.splice(i,1)
        //     break
        //   }
        // }
        // informMsgObj.value[msgBody.data.data].show = false
        var item = store.state.interactMsgObj.msgListIdObj[msgBody.data.data];
        if (item) {
          item.show = false;
        }
        // emitter.emit("uploadMsg", { key: "status", item: msgBody.data });
        // 删除互动消息
        break;
      case 6:
        // 购物车产品状态
        break;
      case 7:
        isSpeak.value = msgBody.data.data === "2";
        // 互动通知
        break;
      case 8:
        // 优惠券
        console.log(
          "msgBody.data.couponVO",
          typeof msgBody.data.couponVO,
          msgBody.data.couponVO
        );
        couponDetail.value = msgBody.data.couponVO;
        discountCouponRef.value.showPopup = true;
        // 将最新的活动对象传递给其他组件
        emitter.emit("getCouponDetail", couponDetail.value);
        break;
      case 9:
        // 优惠券数量有变化通知
        couponDetail.value = msgBody.data.couponVO;
        // 将最新的活动对象传递给其他组件
        emitter.emit("getCouponDetail", couponDetail.value);
        break;
      case 10:
        var msgObj =
          store.state.interactMsgObj.msgListIdObj[msgBody.data.messageId];
        if (msgObj) {
          msgObj.isOpen = msgBody.data.isOpen;
          msgObj.show =
            (!msgObj.replyBasic && msgObj.isOpen !== 2) ||
            store.state.userInfo.userId === msgObj.phone ||
            (msgObj.replyBasic &&
              (msgObj.replyBasic.isOpen === 1 ||
                store.state.userInfo.userId === msgObj.replyBasic.userId));
        }

        var replyMsgObj =
          store.state.interactMsgObj.replyBasicInformMsgObj[
            msgBody.data.messageId
          ];
        if (replyMsgObj) {
          replyMsgObj.replyBasic.isOpen = msgBody.data.isOpen;
          replyMsgObj.show =
            (!replyMsgObj.replyBasic && replyMsgObj.isOpen !== 2) ||
            store.state.userInfo.userId === replyMsgObj.phone ||
            (replyMsgObj.replyBasic &&
              (replyMsgObj.replyBasic.isOpen === 1 ||
                store.state.userInfo.userId === replyMsgObj.replyBasic.userId));
        }
        break;
      case 11:
        // 发起问券
        if (
          !questionnaireTipRef.value.showPopup &&
          !questionnaireTipRef.value.questionnairePopupRef.showPopup &&
          !msgBody.data.questionVO.userIdList.includes(
            store.state.userInfo.userId
          )
        ) {
          questionId.value = msgBody.data.questionVO?.id;
          questionTitle.value = msgBody.data.questionVO?.title;
          questionnaireTipRef.value.showPopup = true;
        }
        break;
      case 13:
        emitter.emit("updateVideoDetail", { openQw: msgBody.data.openQW });
        break;
      case 14:
        // 推送产品
        Obj = msgBody.data.videoCart ? msgBody.data.videoCart : "";
        if (Obj) {
          carPushObj.value = Obj;
        }
        break;
      case 15:
        // 取消推送产品
        carPushObj.value = {};
        break;
      case 16:
        // 隐藏用户昵称
        emitter.emit("updateVideoDetail", {
          showNickname: msgBody.data.openQW,
        });
        break;
      default:
        break;
    }
  }

  // 发送普通文字消息
  async function sendMsg(type, { text, callBack, errorBack } = {}) {
    console.log("store.state.userInfo", store.state.userInfo);
    let ret = {};
    switch (type) {
      case 1:
        // 文本详细
        ret = await liveMsgSend({
          from: store.state.userInfo.userId,
          groupId: detail.id,
          text,
          type,
        }).catch(() => {
          errorBack && errorBack();
        });
        if (ret && ret.code === 0) {
          callBack && callBack();
          if (!store.state.interactMsgObj.msgListIds.includes(ret.data.id)) {
            store.commit("setInteractMsg", {
              type: 1,
              data: ret.data,
            });
          }
        } else if (ret) {
          errorBack && errorBack();
        }
        break;
      case 2:
        // 推荐产品信息
        break;
      case 3:
        // 进入直播消息
        break;
      case 4:
        // 用户点赞视频
        break;
      case 5:
        // 视频分享

        break;
      default:
        break;
    }
  }

  // let shareInformTime = ""; // 上一次消息分享通知时间，半小时内只通知一次

  emitter.on("onShareInform", () => {
    // 视频分享成功通知
    // if (
    //   !shareInformTime ||
    //   new Date().getTime() - shareInformTime.getTime() > 30 * 60 * 1000
    // ) {
    //   shareInformTime = new Date();
    sendLiveShare(
      detail.id,
      route.query.saleUserId ? route.query.saleUserId : ""
    );
    // }
  });

  emitter.on("emSendMsg", ({ type, params }) => {
    sendMsg(type, params);
  });

  // 关闭活动弹窗
  const closeActivity = () => {
    activityObj.value = {};
  };

  // 关闭活动弹窗
  const closeCarPush = () => {
    carPushObj.value = {};
  };

  // 重新弹出优惠券弹窗
  emitter.on("showDiscountCoupon", (detail) => {
    couponDetail.value = detail;
    console.log("discountCouponRef.value", discountCouponRef.value);
    discountCouponRef.value.showPopup = true;
  });

  emitter.on("informMsgListPush", (list) => {
    list.forEach((item) => {
      if (!store.state.interactMsgObj.msgListIds.includes(item.id)) {
        // informMsgList.value.push(item);
        // informMsgListIds.value.push(item.id)
        store.commit("setInteractMsg", {
          type: 1,
          data: item,
        });
        if (item.replyBasic) {
          store.commit("setReplyMsgObj", item);
        }
      }
    });
  });

  return {
    liveStatus,
    isSpeak,
    activityObj,
    carPushObj,
    discountCouponRef,
    questionnaireTipRef,
    questionId,
    questionTitle,
    couponDetail,
    showPlayBtn,
    online,
    closeActivity,
    sendMsg,
    closeCarPush,
  };
}
