<template>
  <div>
    <!-- <div class="back-btn" @click="router.back()">
      <img src="@/assets/images/back.png">
    </div> -->
    <div ref="pageRef" class="page">
      <div class="home">
        <img ref="bgRef" class="bgBox" draggable="false" :src="bgUrl" />
        <img ref="btnRef" class="btnBox" draggable="false" :src="btnUrl" @click="toPage" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from "vue";
import { useRoute } from "vue-router";
import { showToast } from 'vant';

import { queryCourseDetail, getPageDetail } from '@/api/course';

const route = useRoute()
// const router = useRouter()

const page = ref(null)
const pageRef = ref(null)
const bgRef = ref(null)
const btnRef = ref(null)

const bgUrl = computed(() => page.value?.bgUrl || "")
const btnUrl = computed(() => page.value?.btnUrl || "")

function toPage() {
  if (page.value?.paymentUrl === '') {
    showToast('暂无支付链接');
    return;
  }

  window.open(page.value?.paymentUrl)
}

const getcourseDetailFn = async () => {
  try {
    if (route.query.preview) {
      const ret = await getPageDetail({ id: route.query.id });
      page.value = ret.data;
    } else {
      const ret = await queryCourseDetail({ id: route.query.id });
      page.value = ret.data.page;
    }

    document.title = page.value.name;
    nextTick(() => {
      Promise.all([getNaturalWidth(bgRef.value), getNaturalWidth(btnRef.value)]).then(([bgWidth, btnWidth]) => {
        const addBtnStyle = `;width:${btnWidth / bgWidth * 100}%;height: auto;background-image: none;`;

        btnRef.value.style.cssText = page.value.btnStyle + addBtnStyle;
      })
      pageRef.value.style = `min-height: 100vh;background-image:url(${bgRef.value.src});background-position:bottom;background-size: 100000px;`
    })
  } catch (e) {
    console.log(e);
  }
}
getcourseDetailFn();

function getNaturalWidth(DomElement) {
  if (DomElement.naturalWidth) {
    return DomElement.naturalWidth;
  } else {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.onload = function () {
        resolve(img.width);
      };
      img.onerror = function () {
        reject(new Error('error'));
      };
      img.src = DomElement.src;
    });
  }
}


</script>
<style scoped lang="scss">
.back-btn {
  z-index: 100;
  position: fixed;
  top: 112px;
  left: 30px;
  width: 40px;
  height: 40px;
}

.page {
  overflow-x: hidden;
  margin: 0;
  background: #f5f5f5;
}

.home {
  position: relative;
  width: 100%;
  max-width: 100vw;
  background: #f5f5f5;

  .bgBox {
    width: 100%;
  }

  .btnBox {
    position: absolute;
  }
}
</style>
