<script setup>
import { ref, onMounted, computed, watch } from "vue"
import { Request, Storage } from "../libs/utils"
import ModalTransition from "./ModalTransition.vue"
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus';
import { RecycleScroller } from "vue-virtual-scroller";
import "vue-virtual-scroller/dist/vue-virtual-scroller.css";

const props = defineProps({
  show: false
})

watch(() => props.show, async (newVal) => {
  if (!newVal) {
    return
  }
  fetchImages();
})

const emit = defineEmits(['go-my-photo', 'update:show']);
const router = useRouter();
const goBack = () => {
  emit('update:show', false);
};

const username = ref();
const likesCount = ref();
const userImg = ref();
const ranking = ref();

const fetchImages = async () => {
  
  try {
    const url = new URL('https://huodong2.lzlj.com/api/faceFamily/face/square');
    url.searchParams.append('my_only', '0');
    
    const response = await fetch(url.toString(), {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${Storage.get("userinfos").api_token}`
      }
    })
    const data = await response.json()
    console.log('Success:', data)
    images.value = data.data
    username.value = data.my_published_photo.user_name;
    likesCount.value = data.my_published_photo.likes_count;
    userImg.value = data.my_published_photo.result_url;
    ranking.value = data.my_published_photo.ranking;
  } catch (error) {
      console.error('Error:', error)
  }
}

// 图片数据
const images = ref([]);
const disableInviteHelp = ref(false);
const userinfos = Storage.get("userinfos")

// TODO 需要测试邀请进来的情况
const mergeId = ref();
const rankingInvite = ref(0);
const nameInvite = ref('');
const linkCountInvite = ref(0);

const urlParams = new URLSearchParams(window.location.search);
mergeId.value = urlParams.get('merge_id');
watch(() => mergeId, async (newVal) => {
  if (!newVal) {
    return
  }
  if (newVal.value) {
    getInviteInfo();
  }
})

const getInviteInfo = ()=> {
  const urlParams = new URLSearchParams(window.location.search);
  mergeId.value = urlParams.get('merge_id');
  fetch(`https://huodong2.lzlj.com/api/faceFamily/face/merge/${mergeId.value}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${Storage.get("userinfos").api_token}`
    }
  })
  .then(response => response.json())
  .then(data => {
    rankingInvite.value = data.ranking;
    nameInvite.value = data.user_name;
    linkCountInvite.value = data.likes_count;

  })
  .catch((error) => {
    ElMessage.success('点赞失败！');
    console.error('Error:', error);
  }); 
}

const inviteHelp = ()=> {
  const formData = {
    invite_code: userinfos.invite_code,
    merge_id: ''
  }
  fetch('https://huodong2.lzlj.com/api/faceFamily/face/like', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${Storage.get("userinfos").api_token}`
    },
    body: JSON.stringify(formData)
  })
  .then(response => response.json())
  .then(data => {
    disableInviteHelp.value = true;
    ElMessage.success('点赞成功！');
  })
  .catch((error) => {
    ElMessage.success('点赞失败！');
    console.error('Error:', error);
  }); 
}

// onMounted(()=> {
//   getInviteInfo()
// })
const markers = ref([]);
markers.value = [
  { x: 50, y: 32, width: 50, height: 14 }
];

</script>

<template>
  <ModalTransition class="photoSquare" :no-animation="true" :show="show">
    <div class="photoSquare-bg">
      <div class="scene-item item-1" @click="goBack">
        <img src="../assets/images/close-btn.webp" alt="关闭按钮">
      </div>

      <div v-for="(marker, index) in markers" 
          :key="index"
          class="marker"
          :style="{
            left: marker.x + 'vw',
            top: marker.y + 'vw',
            width: marker.width + 'vw',
            height: marker.height + 'vw'
          }"
          @click.stop="$emit('go-my-photo')">
      </div>

      <div v-if="!disableInviteHelp" class="image-gallery ">
        <RecycleScroller
            class="scroller"
            :items="images"
            :item-size="8"
            key-field="id"
            v-slot="{ item, index }"
          >
          <div class="image-wrapper">
            <div class="image-container mask-background">
            </div>          
            <img 
              src="../assets/images/zpgc-border.webp" 
              class="border-image"
              alt="border"
            />
            <div class="list-item">
              <div class="flex-container-detail">
                <div class="left-group">
                  <p class="photo-number">{{ (index + 1).toString().padStart(3, '0') }}</p>
                  <p class="photo-name">{{ item.user_name }}</p>
                </div>
                <p class="right-item photo-name" style="padding-left: 3vw;">{{ item.likes_count }}赞</p>
              </div>
            </div>
          </div>
        </RecycleScroller>
        <!-- <div 
          v-for="(item, index) in images" 
          :key="index" 
          class="image-wrapper"
        >
          <div class="image-container mask-background">
          </div>          
          <img 
            src="../assets/images/zpgc-border.webp" 
            class="border-image"
            alt="border"
          />
          <div class="flex-container-detail">
            <div class="left-group">
              <p class="photo-number">{{ (index + 1).toString().padStart(3, '0') }}</p>
              <p class="photo-name">{{ item.user_name }}</p>
            </div>
            <p class="right-item photo-name" style="padding-left: 3vw;">{{ item.likes_count }}赞</p>
          </div>
        </div> -->
      </div>
      <div v-if="!disableInviteHelp" class="fixed-background-container">
        <div class="flex-container">
          <div class="left-group">
            <p class="photo-number">{{ ranking }}</p>
            <img :src="userImg" class="user-img" alt="我的照片">
            <p class="photo-name bold">{{ username }}</p>
          </div>
          <p class="right-item photo-name bold" style="padding-left: 3vw;">{{ likesCount }}赞</p>
        </div>
      </div>

      <div v-if="disableInviteHelp">
        <div class="image-gallery-share">
          <div class="image-wrapper-share">
            <div class="image-container-share mask-background">
            </div>          
            <img src="../assets/images/zpgc-border.webp" class="border-image-share" alt="border" />
            <div class="flex-container-detail-invite">
              <div class="left-group-left">
                <p class="photo-number">111</p>
                <p class="photo-name">222</p>
              </div>
              <p class="right-item photo-name" style="padding-left: 3vw;">333赞</p>
            </div>
          </div>
        </div>

        <div class="ranking-title" @click="inviteHelp">
          <img src="/src/assets/images/dianzan.webp" alt="点赞">
        </div>
      </div>
    </div>
  </ModalTransition>
</template>

<style scoped>
.scroller {
  height: 124vw;
  overflow-y: auto;
}
.list-item {
  height: 8vw;
  line-height: 50px;
}
.marker {
  position: absolute;
}
.flex-container-detail-invite {
  display: flex;
  flex-flow: row;
  justify-content: center;
  position: relative;
  top: -8vw;
}
.left-group-left {
  display: flex;
  flex-flow: row;
  padding-right: 16vw;
  gap: 3vw;
}
.ranking-title {
  width: 48vw;
  position: absolute;
  bottom: 20vw;
  left: 27vw;
}
.ranking-title img {
  width: 100%;
}
.image-gallery-share {
  margin: 0 auto;
  position: relative;
  overflow-y: auto;
  display: block;
  width: 84vw;
  height: 57vh;
  top: 16%;
}
.image-wrapper-share {
  position: relative;
  margin-bottom: -10vw;
  float: left;
  margin-left: 4vw;
}
.image-container-share {
  width: 77vw;
  height: 43vh;
  background-image: url(/src/assets/images/test.webp);
  background-size: cover;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: -webkit-fill-available;
  position: relative;
  cursor: pointer;
}
.border-image-share {
  position: absolute;
  width: 72vw;
  top: -0.5vw;
  left: 2.6vw;
}
.bold {
  font-weight: bold;
}
.photo-number {
  color: red;
}
.photo-name {
  color: #93551f;
}
.flex-container-detail {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 3vh;
  top: -11vw;
  font-size: 11px;
}
.flex-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 8vh;
  padding: 0 6vw;
}

.left-group {
  display: flex;
  align-items: center;
  gap: 1vw;
}
.user-img {
  width: 8vw;
  height: 8vw;
  border-radius: 50%;
}

.left-group p, .right-item {
  margin: 0;
}
.fixed-background-container {
  background-image: url('../assets/images/paiming-border.webp');
  position: fixed;
  bottom: 1vh;
  left: 5vw;
  width: 90vw;
  height: 8vh;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: bottom center;
}
.image-wrapper {
  position: relative;
  margin-bottom: -10vw;
  float: left;
  margin-right: 2vw;
  margin-left: 2vw;
}
.border-image {
  position: absolute;
  width: 40vw;
  top: 1.6333vh;
  left: -0.4vw;
}
.image-gallery {
  overflow-y: auto;
  display: block;
  width: 84vw;
  height: 57vh;
  position: absolute;
  top: 28%;
}

.image-container {
  width: 38vw;
  height: 28vh;
  background-image: url('../assets/images/test.webp');
  background-size: cover;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  min-height: -webkit-fill-available;
  position: relative;
  cursor: pointer;
}

.mask-background {
  -webkit-mask-image: url("../assets/images/my-photo-mengban.webp");
  mask-image: url("../assets/images/my-photo-mengban.webp");
  -webkit-mask-size: contain;
  mask-size: contain;
  -webkit-mask-position: center;
  mask-position: center;
  -webkit-mask-repeat: no-repeat;
  mask-repeat: no-repeat;
}

.content-image {
  position: relative;
}

.photoSquare-bg {
  width: 100%;
  height: 92vh;
  background-image: url('../assets/images/photo-squarev2.webp');
  background-size: cover;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  min-height: -webkit-fill-available;
}
.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);
}
.btn-login {
  text-align: center;
  border-radius: 1vw;
  background-color: #70b2e2;
  margin-top: 4vw;
  padding: 3vw;
  color: #fff;
  position: relative;
}
.item-1 {
  top: 9%;
  width: 10vw;
  right: 4%;
}
.item-3 {
  top: 16.3vh;
  width: 32vw;
  position: absolute;
  right: 11vw;
}

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

.btn-login.disable {
  opacity: .6;
}

.btn-login.subloading {
  opacity: .6;
}

.btn-login.subloading::before {
  content: "";
  position: absolute;
  border: .5vw solid #fff;
  border-color: rgba(255, 255, 255, .8) transparent transparent transparent;
  border-radius: 50%;
  width: 3vw;
  height: 3vw;
  top: 30%;
  left: calc(50% - 14vw);
  animation: loginloading 1s linear infinite;
}

@keyframes loginloading {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>