<template>
  <!-- 视频 -->
  <div
    class="videocon"
    v-if="(isVideoMode || isMixinMode) && !isToApp"
    v-show="videoShow"
    :style="{
      zIndex: videoIndex,
    }"
  >
    <div
      class="video-background"
      v-if="coverData.videoMoLoc !== 'full'"
      :style="{
        backgroundImage:
          coverData.coverVideoBac === 'imgTile'
            ? `url(${coverData.videoBacImg})`
            : 'none',
        backgroundColor:
          coverData.coverVideoBac === 'imgTile'
            ? `rgba(0,0,0,1)`
            : `${coverData.videoColorSelec}`,
      }"
    ></div>
    <video
      v-if="coverData.videoMo"
      x5-playsinline="true"
      playsinline="true"
      webkit-playsinline="true"
      x5-video-orientation="portraint"
      x5-video-player-fullscreen="true"
      class="video"
      ref="openvideo$"
      preload
      autoplay
      :poster="coverData.videoMoIcon"
      :class="coverData.videoMoLoc == 'center' ? 'contain' : 'cover'"
      :src="coverData.videoMo"
      :controls="Boolean(coverData.coverVideoControl)"
      muted
    ></video>
    <img
      v-show="videoNeedPlay"
      @click.stop="handleVideoPlay"
      class="videoPlay"
      :src="require('@/assets/images/default/bofang.png')"
      alt=""
    />

    <div @click.stop="jumpVideo" class="jump" v-if="countdownVideo == 0">
      {{ $t("common.jump") }}
    </div>
  </div>

  <!-- 图片 -->

  <div
    class="imgcon"
    v-if="(isImageMode || isMixinMode) && !isToApp"
    v-show="imgShow"
    :style="{
      zIndex: imgIndex,
    }"
  >
    <div
      @click="jumpImage(0)"
      class="image-front"
      :style="{
        backgroundImage: `url(${coverData.coverMo})`,
        backgroundSize: coverData.coverMoLoc == 'center' ? 'contain' : 'cover',
      }"
    ></div>
    <div
      class="img-background"
      v-if="coverData.coverMoLoc !== 'full'"
      :style="{
        backgroundImage:
          coverData.coverImgBac == 'imgTile'
            ? `url(${coverData.coverBac})`
            : `none`,
        backgroundColor:
          coverData.coverImgBac == 'imgTile'
            ? `none`
            : `${coverData.imgColorSelec}`,
      }"
    ></div>
    <div @click.stop="jumpImage(1)" class="jump">
      {{
        countdownImg > 0
          ? $t("common.jumpTips", { second: countdownImg })
          : $t("common.jump")
      }}
    </div>
  </div>
</template>
<script setup>
import {
  ref,
  watch,
  computed,
  onMounted,
  defineProps,
  unref,
  watchEffect,
  onUnmounted,
} from "vue";
import { useStore } from "vuex";
import { useApp } from "@/app";
import { useI18n, getLocale } from "@/i18n";

const { t } = useI18n({ useScope: "global" });
const zIndex = ref(1000);
const useZIndex = () => {
  zIndex.value++;
  return unref(zIndex);
};
const props = defineProps({
  coverData: {
    type: [Boolean, Object],
    default: () => {
      return {};
    },
  },
});
const store = useStore();
const openvideo$ = ref(null);
const videoNeedPlay = ref(true);
const isToApp = ref(false);
const isMixinMode = computed(
  () => props.coverData.coverSelect.toLowerCase().indexOf("and") > -1
);
const isImageMode = computed(
  () => props.coverData.coverSelect.toLowerCase() === "img"
);
const isVideoMode = computed(
  () => props.coverData.coverSelect.toLowerCase() === "video"
);
// 字段意思有误
const showImageFirst = computed(
  () => props.coverData.coverImageOrder === "before"
);

const show = ref(true);
const countdownImg = ref(3);
const countdownVideo = ref(3);
const imgTimer = ref(null);
const videotimer = ref(null);

const isImageCountDone = ref(false);
const isVideoCountDone = ref(false);

const isImageAutoNext = computed(() => props.coverData.coverImageInWay === 1);
const isVideoAutoNext = computed(() => props.coverData.coverVideoInWay === 1);

const imgShow = ref(false);
const videoShow = ref(false);

const imgIndex = ref(1);
const videoIndex = ref(1);

const handleVideoPlay = () => {
  // window.alert("play");
  let video = unref(openvideo$);
  video && video.play();
};

//手动跳转
/**
 *  跳转逻辑PM设定非奇怪，要注意
 *  @TODO 图片模式 button 3秒倒只作装饰显示，不参与逻辑
 *
 *  */

const jumpImage = (from = 0) => {
  // 0 来自元素click, 1.来自跳转按钮
  if (unref(isMixinMode)) {
    if (unref(showImageFirst)) {
      imgShow.value = false;
      videoShow.value = true;
      startVideoCount();
    } else {
      // 强制跳转
      // 非自动模式强制跳转
      if (from === 0 && !unref(isImageAutoNext)) {
        toApp();
      }
      if (from === 1) {
        toApp();
      }
      if (unref(isImageAutoNext) && unref(isImageCountDone)) {
        toApp();
      }
    }
  } else {
    // 非自动模式强制跳转
    if (from === 0 && !unref(isImageAutoNext)) {
      toApp();
    }
    // 非自动模式强制跳转
    if (from === 1) {
      toApp();
    }
    if (unref(isImageAutoNext) && unref(isImageCountDone)) {
      toApp();
    }
  }
};

//手动跳转
const jumpVideo = () => {
  if (unref(isMixinMode)) {
    if (!unref(showImageFirst)) {
      imgShow.value = true;
      videoShow.value = false;
      startImageCount();
    } else {
      toApp();
    }
  } else {
    if (unref(isVideoCountDone)) {
      toApp();
    }
  }
};

const startImageCount = () => {
  imgTimer.value = setInterval(() => {
    countdownImg.value--;
    if (countdownImg.value <= 0) {
      clearInterval(imgTimer.value);
      countdownImg.value = 0;
      isImageCountDone.value = true;
      imgTimer.value = null;
      return;
    }
  }, 1000);
};
const startVideoCount = () => {
  const nextIndex = useZIndex();
  videoIndex.value = nextIndex;
  videotimer.value = setInterval(() => {
    countdownVideo.value--;
    if (countdownVideo.value <= 0) {
      clearInterval(videotimer.value);
      countdownVideo.value = 0;
      isVideoCountDone.value = true;
      videotimer.value = null;
      return;
    }
  }, 1000);
};

//开始全监听
watch(
  [isMixinMode, isImageMode, isVideoMode, showImageFirst],
  ([val1, val2, val3, val4]) => {
    //混合模式

    if (unref(val1)) {
      //图片优先
      if (unref(val4)) {
        imgShow.value = true;
        startImageCount();
      } else {
        videoShow.value = true;
        startVideoCount();
      }
    } else {
      //非混合模式
      if (unref(val2)) {
        imgShow.value = true;
        startImageCount();
      }
      if (unref(val3)) {
        videoShow.value = true;
        startVideoCount();
      }
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
//倒数完全监听
watch(
  [isMixinMode, isImageCountDone, isVideoCountDone, showImageFirst],
  ([val1, val2, val3, val4]) => {
    //混合模式
    if (unref(val1)) {
      //图片优先
      if (unref(val4)) {
        //图片倒数完
        if (unref(val2)) {
          if (unref(isImageAutoNext)) {
            imgShow.value = false;
            videoShow.value = true;
            startVideoCount();
          }
        }
      } else {
        //图片非优先
        if (unref(val2)) {
          if (unref(isImageAutoNext)) {
            toApp();
          }
        }
      }
    } else {
      //非混合模式
      if (unref(val2)) {
        if (unref(isImageAutoNext)) {
          toApp();
        }
      }
    }
  },
  {
    deep: true,
  }
);

//跳转到app
const toApp = () => {
  if (!unref(isToApp)) {
    console.log("跳转到app", unref(isToApp));
    imgShow.value = false;
    videoShow.value = false;
    isToApp.value = true;
    store.commit("scene/setDoneforCover", true);
    useApp().then((app) => {
      setTimeout(() => {
        app.render();
      }, 1000);
    });
  }
};
const handleVideoEnded = () => {
  if (isVideoAutoNext.value) {
    //混合模式
    if (unref(isMixinMode)) {
      //视频优先 直达图片
      if (!unref(showImageFirst)) {
        videoShow.value = false;
        imgShow.value = true;
        startImageCount();
      } else {
        toApp();
      }
    } else {
      toApp();
    }
  }
};
onUnmounted(() => {
  if (openvideo$.value) {
    openvideo$.value.addEventListener("ended", handleVideoEnded, false);
  }
});
onMounted(() => {
  console.log("coverData", unref(props.coverData));

  if (openvideo$.value) {
    openvideo$.value.addEventListener("ended", handleVideoEnded, false);

    openvideo$.value.addEventListener("playing", () => {
      if (videoNeedPlay.value) {
        videoNeedPlay.value = false;
      }
    });

    openvideo$.value.addEventListener("pause", () => {
      if (!videoNeedPlay.value) {
        videoNeedPlay.value = true;
      }
    });

    // document.addEventListener(
    //   "WeixinJSBridgeReady",
    //   () => {
    //     openvideo$.value.play();
    //   },
    //   false
    // );
  }
}),
  useApp().then((app) => {
    app.Scene.on("ready", () => {
      if (show.value) {
        show.value = false;
      }
    });
  });
</script>
<style lang="scss" scoped>
.imgcon,
.videocon {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
.video-background {
  background-repeat: repeat;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.imgcon {
  // z-index: 10;
  .image-front,
  .img-background {
    background-position: center;
    width: 100%;
    height: 100%;
    position: absolute;

    top: 0;
    z-index: 1;
    bottom: 0;
    left: 0;
  }
  .img-background {
    background-repeat: repeat;
  }
  .image-front {
    z-index: 10;
  }
}

.videocon {
  text-align: center;

  > video {
    max-width: inherit;
    height: auto;
    min-height: 100%;
    top: 50%;
    left: 50%;
    z-index: 99;
    display: inline-block;
    transform: translate(-50%, -50%);
    position: absolute;
  }

  .contain {
    width: 100%;
    height: auto;
    object-fit: scale-down;
  }

  .cover {
    height: 100%;
    width: 100%;
    object-fit: cover;
  }

  .videoPlay {
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
    left: 50%;
    width: 80px;
    height: 80px;
    z-index: 99999;
  }
}

.videoPlayFirst {
  z-index: 99;
}

.jump {
  position: absolute;
  right: 15px;
  top: 20px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 17px;
  text-align: center;
  line-height: 28px;
  font-size: 16px;
  z-index: 999;
  color: #fff;
  padding: 4px 12px;
  cursor: pointer;
}

@keyframes loading {
  100% {
    left: -900px;
  }
}
</style>
