<template>
  <van-nav-bar :title="item.title" left-text="返回" left-arrow @click-left="onClickLeft" />
  <!-- <video controls id="video" :poster="item.poster" /> -->
  <div id="dplayer" :style="{ backgroundImage: `url(${item.poster})` }"></div>

  <template v-if="false === item.bought">
    <van-notice-bar left-icon="volume-o" text="未购买的视频、音频默认播放时长为1分钟左右。" />
    <van-button square type="warning" @click="buy()" size="large" block>
      花费 {{ (item.price * item.discount) / 100 }} 点 立即购买
    </van-button>
  </template>

  <div id="container">
    <van-space direction="vertical" fill size="2rem">
      <van-row gutter="20" v-if="!pageLoading">
        <van-col span="12">
          <van-button type="primary" plain round @click="play(item.hash, 'video')" size="large" block>看视频</van-button>
        </van-col>
        <van-col span="12">
          <van-button type="warning" plain round="" @click="play(item.hash, 'audio')" size="large"
            block>听音频</van-button>
        </van-col>
      </van-row>
    </van-space>
  </div>
</template>

<script setup>
import request from "@/utils/request";
import DPlayer from "dplayer";
import Hls from "hls.js";
import { onBeforeUnmount, onMounted } from "vue";


const router = useRouter();
const route = useRoute();
const pageLoading = ref(true)

let player = null;

const item = ref({
  title: "加载中...",
});

onBeforeUnmount(() => {
  player?.destroy();
});

onMounted(() => {
  loadMedia(route.params.hash);
});

const onClickLeft = () => {
  if (route.meta.from?.name) {
    router.back();
    return;
  }
  router.replace({
    name: "tab.home",
    params: {
      tenant: route.params.tenant,
    },
  });
};

const loadMedia = (hash) => {
  request
    .get(`/medias/${hash}`)
    .then((res) => {
      console.log(res);
      item.value = res.data;
    })
    .catch((err) => {
      console.error("ERROR", err);
    })
    .finally(() => {
      pageLoading.value = false
    });
};

const play = (hash, type) => {
  let source = `/v1/medias/${hash}/${type}`;
  if (navigator.userAgent.indexOf("iPhone") > -1) {
    source = `/v1/medias/${hash}/${type}?token=${__GA}`;
  }

  player = new DPlayer({
    container: document.getElementById('dplayer'),
    video: {
      url: source,
      pic: item.value.poster,
      type: 'customHls',
      customType: {
        customHls: function (video, player) {
          const hls = new Hls({
            xhrSetup: function (xhr, url) {
              xhr.withCredentials = true;
              xhr.setRequestHeader("Authorization", "Bearer " + __GA);
            },
          });
          hls.loadSource(source);
          hls.attachMedia(video);
        },
      },
    }
  });

  player.play();

  // if (Hls.isSupported()) {
  //   var hls = new Hls({
  //     xhrSetup: function (xhr, url) {
  //       xhr.withCredentials = true;
  //     },
  //   });
  //   hls.loadSource(source);
  //   hls.attachMedia(player);
  //   hls.on(Hls.Events.MANIFEST_PARSED, function () {
  //     player.play();
  //   });
  // } else if (player.canPlayType("application/vnd.apple.mpegurl")) {
  //   player.src = source;
  //   player.addEventListener("loadedmetadata", function () {
  //     player.play();
  //   });
  // }
};


const buy = () => {
  // get use balance
  request
    .get("/users/info")
    .then((res) => {
      if (res.data.balance < item.value.price) {
        showConfirmDialog({
          title: '余额不足',
          message: `您的账户余额为 ${res.data.balance} 点，不足以购买此视频。是否前往充值？`,
        })
          .then(() => {
            router.replace({
              name: "tab.user",
              params: {
                tenant: route.params.tenant,
              },
            });
          })
          .catch(() => {
            return;
          });

        return;
      }

      showConfirmDialog({
        title: '购买确认',
        message: `您的账户余额为 ${res.data.balance} 点，购买此视频将花费 ${item.value.price} 点。是否确认购买？`,
      })
        .then(() => {
          request
            .patch(`/medias/${route.params.hash}/checkout`)
            .then((res) => {
              showSuccessToast('购买成功');
              loadMedia(route.params.hash);
            })
            .catch((err) => {
              showFailToast('购买失败: ' + err.response.data.message);
            });
        })
        .catch(() => {
          return;
        });
    });

};

</script>

<style scoped>
#container {
  padding: 1em;
}

#video,
#dplayer {
  background-color: #cccccc;
  aspect-ratio: 16 / 9;
  width: 100%;
  object-fit: fill;
  background-size: cover;
  background-position: center;
}
</style>
