<template>
  <!-- 竖屏 playStyle: 1-竖屏 2-横屏-->
  <SScreen
    v-if="
      videoDetail.playStyle === 1 &&
      isPlay &&
      ![5, 6].includes(videoDetail.status)
    "
    :detail="videoDetail"
  ></SScreen>
  <HScreen
    :detail="videoDetail"
    v-else-if="isPlay && ![5, 6].includes(videoDetail.status)"
    @updateVideoDetail="updateVideoDetail"
  />
  <NoLookTip v-if="[5, 6].includes(videoDetail.status)" text="该视频已下架" />
  <NoLookTip
    v-else-if="noAuth"
    :text="`${store.state.userInfo.userId}账号暂无服务权限，请联系小助理开通`"
  />
  <van-dialog
    v-model:show="showCodeDialog"
    title="观看权限提示"
    show-cancel-button
    @confirm="getLiveLimit"
    @cancel="toBack"
  >
    <div class="code-content">
      <p class="tip-text">当前直播需输入邀请码才可观看</p>
      <van-field v-model.trim="code" placeholder="请输入邀请码" />
    </div>
  </van-dialog>
</template>

<script setup>
import { ref, computed, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showConfirmDialog, showToast, showDialog } from "vant";
import { queryVideoDetail } from "@/api/video";
import { queryLiveLimit } from "@/api/video";
import { useStore } from "vuex";
import emitter from "@/utils/emitter";
import HScreen from "./HScreen.vue";
import SScreen from "./SScreen.vue";
import NoLookTip from "@/components/NoLookTip.vue";
import { userLogin } from "@/utils/login";
// import { checkAuthIds } from "@/hooks/useHasAuth";

const route = useRoute();
const store = useStore();
const router = useRouter();
// 之前是否已经进行邀请码校验且通过校验
const codeVerify = localStorage.getItem(
  `${store.state.userInfo.userId}-${route.query.id}-code`
);

const showCodeDialog = computed(() => {
  if (videoDetail.value.limitType === 3 && !isPlay.value && !codeVerify) {
    // 邀请码
    return true;
  } else {
    return false;
  }
});

const videoDetail = ref({});
const isPlay = ref(false); // 当直播限制需要验证码登录的时候，验证码校验通过才能播放
const noAuth = ref(false);

const getVideoDetail = async () => {
  // await sendBrowseInfo({ id: route.query.id });

  let ret = await queryVideoDetail({
    videoId: route.query.id,
    saleUserId: route.query.saleUserId ? route.query.saleUserId : "",
  });
  if (ret.code === 6013) {
    noAuth.value = true;
  } else if (ret.code === 0) {
    document.title = ret.data.title;
    // limitType	直播限制 1不限制 2手机号 3邀请码 4微信授权 5产品专属直播 6 权限号
    if (
      [1].includes(ret.data.limitType) ||
      (ret.data.limitType === 3 && codeVerify) ||
      (ret.data.limitType === 2 && store.state.token)
    ) {
      isPlay.value = true;
    } else if (ret.data.limitType === 6) {
      const authResultVo = ret.data.authResultVo || {};
      isPlay.value = !!authResultVo.auth;
      noAuth.value = !authResultVo.auth;
      // if (checkAuthIds(ret.data.authIds, store.getters.authorityIdList)) {

      // } else {
      //   noAuth.value = true;
      // }
      if (authResultVo.auth) {
        if (authResultVo.riskUrl) {
          showDialog({
            title: "提示",
            message: `您当前订单尚未完成风险测评，无法查看产品服务内容，请点击完成风险测评`,
            confirmButtonText: "去测评",
          })
            .then(() => {
              location.href =
                authResultVo.riskUrl +
                `&callbackUrl=${encodeURIComponent(location.href)}`;
            })
            .catch(() => {
              router.go(-1);
            });
        } else if (authResultVo.contractUrl) {
          showDialog({
            title: "提示",
            message: `您当前订单尚未完成合同签署，无法查看产品服务内容，请点击完成合同签署`,
            confirmButtonText: "去签署",
          })
            .then(() => {
              location.href =
                authResultVo.contractUrl +
                `&contractCallbackUrl=${encodeURIComponent(location.href)}`;
            })
            .catch(() => {
              router.go(-1);
            });
        }
      }
    } else if (ret.data.limitType === 5) {
      getLiveLimit();
    } else if (ret.data.limitType === 2 && !store.state.token) {
      userLogin();
    }
    videoDetail.value = ret.data;

    // let extRet = await queryVideoExt({
    //   videoId: route.query.id,
    //   saleUserId: route.query.saleUserId ? route.query.saleUserId : "",
    // }).catch((error) => {
    //   console.log("queryVideoExt", error);
    // });
    // if (extRet.code === 0) {
    //   Object.assign(videoDetail.value, ret.data);
    // }
    // liveCustomerSave({
    //   channel: route.query.saleUserId ? 2 : 1,
    //   comId: "",
    //   deptId: "",
    //   riskLevel: videoDetail.value.riskLevel,
    //   saleUserId: route.query.saleUserId ? route.query.saleUserId : "",
    //   userId: store.state.userInfo.userId,
    //   userName: store.state.userInfo.userName,
    //   zjzh: store.state.userInfo.userId,
    //   imgUrl: store.state.userInfo.imgUrl,
    //   videoId: videoDetail.value.id,
    // });
  }
};
getVideoDetail();

const code = ref("");
const getLiveLimit = async () => {
  let ret = await queryLiveLimit({
    videoId: route.query.id,
    code: code.value,
  });
  if (ret.code === 0) {
    if (ret.data.res) {
      // 检验通过
      if (ret.data.limitType === 3) {
        localStorage.setItem(
          `${store.state.userInfo.userId}-${route.query.id}-code`,
          true
        );
      }
      isPlay.value = true;
    } else {
      if (ret.data.limitType === 5) {
        showConfirmDialog({
          title: "提示",
          message: `该直播为【${videoDetail.value.infoVO?.productName}】专属直播服务，订阅产品后即可观看。`,
        })
          .then(() => {
            location.href = `${location.origin}/tgh5/viewpackageDetail/${videoDetail.value.infoVO?.productId}`;
          })
          .catch(() => {
            router.go(-1);
          });
      } else if (ret.data.limitType === 3) {
        showToast("邀请码输入错误！");
      }
    }
  }
};

// 更新视频详情对象
const updateVideoDetail = (obj = {}) => {
  Object.assign(videoDetail.value, obj);
};
emitter.on("updateVideoDetail", updateVideoDetail);

onBeforeUnmount(() => {
  emitter.off("updateVideoDetail");
  store.commit("resetInteractMsgObj");
});

const toBack = () => {
  if (route.query.sdk) {
    console.log("sdk返回");
  } else if (route.query.source === "c") {
    router.go(-1);
  } else {
    if (window.history.state.back) {
      router.go(-1);
    } else {
      if (
        typeof window.WeixinJSBridge == "object" &&
        typeof window.WeixinJSBridge.invoke == "function"
      ) {
        window.WeixinJSBridge.invoke("closeWindow", {}, function (res) {
          console.log(res);
        });
      } else {
        window.close();
      }
    }
  }
};
</script>
<style scoped lang="scss">
.code-content {
  padding: 30px 50px 30px;

  p {
    margin-bottom: 20px;
  }
}
::v-deep .tcp-skin .vjs-big-play-button {
  z-index: 3;
}
</style>
