<template>
  <ModalTransition class="todolist" :show="show">
    <div class="todolist-wrapper">
      <div class="btn-group">
        <div class="btn-qiwei" :class="globalStore.followed_official && 'has'" @click="openQiwei($event)"></div>
        <div class="btn-scan" :class="globalStore.cap_scan >= globalStore.MAX_CAP_SCAN && 'has'"
          @click="handleScan($event)"></div>
        <div class="btn-share" :class="globalStore.invitees >= globalStore.MAX_INVITE_DAILY && 'has'"
          @click="openHaibao($event)"></div>
      </div>
      <div class="close" @click="$emit('close')"></div>
    </div>
    <div class="fullsection" v-show="haibaoShow">
      <div class="haibao" :style="userhaibaoCover">
        <img :src="haibaoUrl" alt="">
        <div class="close" @click="haibaoShow = false"></div>
      </div>
    </div>

    <div class="fullsection" v-show="qiweiShow">
      <div class="qiwei">
        <img src="../assets/images/qiwei-bg.webp" alt="">
        <div class="close" @click="qiweiShow = false"></div>
      </div>
    </div>
  </ModalTransition>
</template>

<script setup>
import { ref, computed } from "vue"
import { globalStore } from "@/globalstore";
import ModalTransition from "./ModalTransition.vue"
import { Storage, generateQR, isWeixin, isMiniPage } from "../libs/utils"
import Haibao from "@/libs/haibao"
import bg from "../assets/images/haibao-bg.webp"
import mask from "../assets/images/haibao-mask.webp"
import haibaoCoverBorder from "../assets/images/haibao-cover.webp"
const props = defineProps({
  show: false,
})

const emit = defineEmits(['close', 'open'])
const shareShow = ref(false)
const qiweiShow = ref(false)
const haibaoShow = ref(false)
const haibaoUrl = ref('')
const userHaibaoUrl = ref('')
const userhaibaoCover = computed(() => {
  return { backgroundImage: `url(${userHaibaoUrl.value})` }
})

const handleHaibao = async () => {
  if (haibaoUrl.value) {
    return
  }
  const loading = weui.loading()
  // let userPicture = 'https://lzlj123.oss-cn-shanghai.aliyuncs.com/face-merged/20250914/face-merge-5c90bb95-d1d2-479a-a13b-ada7ba8e7152.jpg'
  let userPicture = await loadImage(globalStore.result_url)
  // let userPicture = await loadImage('https://lzlj123.oss-cn-shanghai.aliyuncs.com/face-merged/20250914/face-merge-5c90bb95-d1d2-479a-a13b-ada7ba8e7152.jpg')

  const infos = Storage.get("userinfos")
  const haibaoCover = new Haibao(951, 1607)
  haibaoCover.add(userPicture, 0, 50, 951, 1698)
  haibaoCover.add(mask, 10, 100)
  haibaoCover.add(haibaoCoverBorder, 0, 0)
  haibaoCover.draw('destination-in').then(() => {
    haibaoCover.generate({ mimeType: 'image/png' }).then(async (url) => {
      userHaibaoUrl.value = url

      const haibaoSave = new Haibao(1080, 2160)
      const qrcode = await generateQR(`fromid=${infos.invite_code}&org_id=${infos.org_id}`, 200, 200)
      haibaoSave.add(url, 62, 350)
      haibaoSave.add(bg, 0, 0)
      haibaoSave.add(qrcode, 115, 1875)
      haibaoSave.draw().then(() => {
        haibaoSave.text(infos.nickname, haibaoSave.canvas.width / 2, 200, { font: 'bold 50px Arial', color: '#ffee6f' })
        haibaoSave.generate({ mimeType: 'image/png' }).then(url => {
          haibaoUrl.value = url
          loading.hide()
        }).catch(err => {
          console.log(err)
          weui.alert("海报生成失败，请重新生成")
          loading.hide()
        })
      }).catch(err => {
        console.log(err)
        weui.alert("海报生成失败，请重新生成")
        loading.hide()
      })
    })
  })

}

function loadImage (src) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "Anonymous";
    img.onload = () => resolve(img);
    img.onerror = () => reject(new Error(`无法加载图片: ${src}`));
    img.src = src;
  });
}


const openQiwei = (e) => {
  const target = e.currentTarget

  if (target.classList.contains("has")) {
    return
  }

  qiweiShow.value = true
}
const openHaibao = (e) => {
  const target = e.currentTarget

  if (target.classList.contains("has")) {
    return
  }
  if (!globalStore.result_url) {
    return weui.alert("请先参与活动合成图片并打榜！")
  }
  haibaoShow.value = true
  handleHaibao()
}
const openPeifang = (e) => {
  const target = e.currentTarget

  if (target.classList.contains("has")) {
    return
  }
  emit('open', { type: 'peifang' })
}
const handleScan = (e) => {
  const target = e.currentTarget

  if (target.classList.contains("has")) {
    return
  }
  if (!(isWeixin() || isMiniPage())) {
    weui.alert("请使用微信打开进行扫码")
    return
  }

  wx.scanQRCode({
    needResult: 0, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
    scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
    fail (err) {
      weui.alert(err.errMsg)
    }
  });
}

</script>

<style scoped>
.home-wrapper {
  width: 100%;
  position: relative;
  min-height: -webkit-fill-available;
}

.home-wrapper img {
  width: 100%;
  background-size: cover;
  background-repeat: no-repeat;
}

.scene-item {
  position: absolute;
  cursor: pointer;
  transition: all 0.4s ease;
  border-radius: 8px;
  overflow: hidden;
  border: 3px solid transparent;
  animation: float 4s ease-in-out infinite;
}

.scene-item:hover {
  transform: scale(1.05);
}

.scene-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.item-1 {
  width: 10vw;
  bottom: 54%;
  right: 3%;
  animation-delay: 0s;
}

.item-1 {
  width: 10vw;
  bottom: 54%;
  right: 3%;
  animation-delay: 0s;
}

.item-2 {
  width: 110px;
  bottom: 36%;
  right: 6%;
  animation-delay: 0s;
}

.item-3 {
  width: 110px;
  bottom: 25%;
  right: 6%;
  animation-delay: 0s;
}

.item-4 {
  width: 110px;
  bottom: 14%;
  right: 6%;
  animation-delay: 0s;
}

.qiwei {
  position: relative;
  width: 80.740741vw;
  /* height: 89.259259vw; */
}

.qiwei img {
  width: 100%;
  height: 100%;
  display: block;
}

.fullsection {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, .7);
}

.haibao {
  position: relative;
  width: 65.37037vw;
  height: 119.444444vw;
  background-image: url("../assets/images/haibao-cover.webp");
  background-repeat: no-repeat;
  background-size: 100%;
}

.haibao img {
  width: 100%;
  height: 100%;
  display: block;
  opacity: 0;
}

.close {
  position: absolute;
  width: 8.148148vw;
  height: 8.148148vw;
  right: 5vw;
  top: 15vw;
  background-image: url("../assets/images/close-btn.webp");
  background-repeat: no-repeat;
  background-size: 100%;
}

.haibao .close {
  left: 50%;
  bottom: -5vw;
  top: initial;
  transform: translate3d(-50%, 0, 0);
}

.qiwei .close {
  right: 50%;
  top: 90vw;
  margin-right: -4vw;
}

.todolist-wrapper {
  position: relative;
  width: 100vw;
  height: 123.333333vw;
  background-image: url("../assets/images/todo-bg.webp");
  background-repeat: no-repeat;
  background-size: 100%;
}

.btn-group {
  position: absolute;
  right: 6vw;
  top: 45vw;
  width: 24.907407vw;
  height: 70vw;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.btn-group div {
  width: 24.907407vw;
  height: 10vw;
  background-repeat: no-repeat;
  background-size: 100%;
}

.btn-share {
  background-image: url("../assets/images/share-link.webp");
}

.btn-share.has {
  background-image: url("../assets/images/btn-max.webp");
}

.btn-qiwei {
  background-image: url("../assets/images/add-wx.webp");
}

.btn-qiwei.has {
  background-image: url("../assets/images/btn-added.webp");
}

.btn-scan {
  background-image: url("../assets/images/scan-code.webp");
}

.btn-scan.has {
  background-image: url("../assets/images/btn-max.webp");
}
</style>