<script setup>
import { ref, computed, watch, onMounted } from "vue"
import { useRouter, useRoute } from 'vue-router'
import faceFamily from "../assets/audio/faceFamily.mp3"
import MyPhoto from './MyPhoto.vue'
import PhotoSquare from './PhotoSquare.vue'
import globalToastEvent, { ToastType } from '../globalToastEvent';
import { globalStore } from "../globalstore.js";
import Login from '../components/Login.vue'
import { isWeixin, isLogin, getParam, Storage, Request } from "../libs/utils"

defineProps({
  show: true
})
const isMusicOn = ref(false);
const audioElement = ref(null);
onMounted(() => {
  audioElement.value = new Audio(faceFamily);
  tryAutoPlay();
})

// 尝试自动播放
const tryAutoPlay = () => {
  // 先加载音频
  audioElement.value.load();
  // 尝试播放
  const playPromise = audioElement.value.play();
  if (playPromise !== undefined) {
    playPromise.then(() => {
      // 自动播放成功
      isMusicOn.value = true;
      console.log("自动播放成功");
    })
    .catch(error => {
      // 自动播放被阻止
      console.log("自动播放被阻止，需要用户交互:", error);
      isMusicOn.value = false;
      audioElement.value.pause();
    });
  }
};

// 播放/暂停切换
const toggleMusicState = () => {
  isMusicOn.value = !isMusicOn.value;
  if (!isMusicOn.value) {
      audioElement.value.pause();
  } else {
    audioElement.value.play().catch(error => {
      console.log("播放失败:", error);
    });
  }
};

const navigateTodoList = () => {
  globalToastEvent.emit(ToastType.SHOW_TODO)
}
const handlePrizeList = async () => {
  globalToastEvent.emit(ToastType.SHOW_PRIZELIST)
}
const handleRule = () => {
  globalToastEvent.emit(ToastType.SHOW_RULE)
}
const handleLottery = () => {
  globalToastEvent.emit(ToastType.SHOW_LOTTERY)
  if (globalStore.draw_chances <= 0) return;
  globalStore.reducerDrawChances();
}

const router = useRouter();
const navigateSelectTemplatePage = () => {
  if (globalStore.game_chances <= 0) return;
  globalStore.reducerGameChances();
  router.push({
    name: 'selectTemplateV2'
  })
}
const route = useRoute()
const myPhotoValue = route.query.myPhotoValue;

const isMyPhotoVisible = ref(false);
const isPhotoSquareVisible = ref(false);

const showMyPhoto = () => { 
  isMyPhotoVisible.value = true;
  isPhotoSquareVisible.value = false;
}
const showPhotoSquare=()=>{
  isMyPhotoVisible.value = false;
  isPhotoSquareVisible.value = true;
}

watch(() => myPhotoValue, async (newVal) => {
  if (!newVal) {
    return
  }
  
  isMyPhotoVisible.value = true;
}, { immediate: true })

const loginShow = ref(false)
// 登录状态
const userStatus = async (callback) => {
  const pageCode = getParam("code")
  const userinfos = Storage.get("userinfos")
  if (isWeixin()) {
    if (!pageCode) {
      weui.alert("未获取到code")
      return
    }
    const weixinResult = await Request("wechat/login", {
      code: pageCode
    })
    Storage.set("userinfos", weixinResult.json)
    if (weixinResult.json && weixinResult.json.phone) {
      loginShow.value = false
      callback && callback()
    } else {
      loginShow.value = true
    }
  } else {
    loginShow.value = true
  }
}

//初始化持久数据
const initUserGameInfos = async (refresh_official, refresh_cap_scan) => {
  const result = await Request('game/info', { refresh_official: refresh_official, refresh_cap_scan: refresh_cap_scan }, "GET")

  if (result.res.status === 200) {
    globalStore.draw_chances = result.json.draw_chances
    globalStore.game_chances = result.json.game_chances
    globalStore.invitees = result.json.invitees
    globalStore.followed_official = result.json.followed_official
    globalStore.cap_scan = result.json.cap_scan
    globalStore.game_chances_view_recipes = result.json.game_chances_view_recipes
    globalStore.MAX_VIEW_RECIPES_DAILY = result.json.constants.MAX_VIEW_RECIPES_DAILY
    globalStore.CONSUME_POINT_1_PER_DRAW = result.json.constants.CONSUME_POINT_1_PER_DRAW
    globalStore.MAX_CAP_SCAN = result.json.constants.MAX_CAP_SCAN
    globalStore.MAX_INVITE_DAILY = result.json.constants.MAX_INVITE_DAILY

    globalToastEvent.emit(ToastType.MOUNTED)
  }
}

const handleLoginSuccess = async () => {
  console.log("已登录")
  loginShow.value = false

  await initUserGameInfos(true, true)
}

if (isLogin()) {
  handleLoginSuccess()
} else {
  userStatus(handleLoginSuccess)
}


</script>

<template>
  <div :show="show">
    <div class="home-wrapper">
      <div class="scene-item item-1" @click="handleLottery" :class="{ 'disabled': globalStore.draw_chances <= 0 }">
        <img src="../assets/images/lottery.webp" alt="抽奖">
        <div class="lottery-main">
          <p class="lottery-value">{{ globalStore.draw_chances }}</p>
        </div>
      </div>
      <div class="scene-item item-2" @click="navigateSelectTemplatePage" :class="{ 'disabled': globalStore.game_chances <= 0 }">
        <img src="../assets/images/join.webp" alt="立即参与">
        <div class="join-main">
          <p class="join-value">{{ globalStore.game_chances }}</p>
        </div>
      </div>
      <div class="scene-item item-3" @click="navigateTodoList">
        <img src="../assets/images/task.webp" alt="任务">
      </div>

      <div @click="toggleMusicState">
        <div v-if="isMusicOn" key="on" class="scene-item item-4">
          <img src="../assets/images/music-on.webp" alt="音乐开">
        </div>
        <div v-else key="off" class="scene-item item-5">
          <img src="../assets/images/music-off.webp" alt="音乐关">
        </div>
      </div>
      <div class="scene-item item-6" @click="handleRule">
        <img src="../assets/images/rule.webp" alt="规则">
      </div>
      <div class="scene-item item-7" @click="handlePrizeList">
        <img src="../assets/images/award.webp" alt="奖励">
      </div>
      <div class="scene-item item-8" @click="showMyPhoto">
        <img src="../assets/images/my-photo.webp" alt="我的照片">
      </div>
      <div class="scene-item item-9" @click="showPhotoSquare">
        <img src="../assets/images/photos.webp" alt="照片广场">
      </div>
    </div>
  </div>

  <MyPhoto @go-photo-square="showPhotoSquare" v-model:show="isMyPhotoVisible" />
  <PhotoSquare @go-my-photo="showMyPhoto" v-model:show="isPhotoSquareVisible" />
  <Login :show="loginShow" @login-success="handleLoginSuccess" />
</template>

<style scoped>
.home-wrapper {
  width: 100%;
  height: 92vh;
  background-image: url('../assets/images/home-bg.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;
  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: 21vw;
  bottom: 0;
  left: 0;
  animation-delay: 0s;
}

.lottery-main {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 4vw;
  height: 3.5vw;
  position: absolute;
  top: 1.5vw;
  right: 6.6vw;
  color: #fff;
}

.lottery-main .lottery-value {
  font-size: 10px;
}

.item-2 {
  width: 48vw;
  bottom: 0;
  animation-delay: 0s;
}

.join-main {
  position: absolute;
  top: 3.4vw;
  right: 2.6vw;
  width: 7vw;
  line-height: 7vw;
  text-align: left;
}

.join-main .join-value {
  margin: 0;
  color: white;
  text-stroke: 4px #ff0000;
  -webkit-text-stroke: 1px #ff0000;
  font-size: 24px;
  font-weight: 900;
}

.item-3 {
  width: 21vw;
  bottom: 0;
  right: 0;
  animation-delay: 0s;
}
.item-4 {
  width: 11vw;
  top: 1.5%;
  right: 1.5%;
  animation-delay: 0s;
}
.item-5 {
  width: 11vw;
  top: 1.5%;
  right: 1.5%;
  animation-delay: 0s;
}
.item-6 {
  width: 14.5vw;
  top: 8%;
  right: 0;
  animation-delay: 0s;
}
.item-7 {
  width: 14.5vw;
  top: 13.5%;
  right: 0;
  animation-delay: 0s;
}
.item-8 {
  width: 11vw;
  bottom: 32%;
  right: 1%;
  animation-delay: 0s;
}
.item-9 {
  width: 11vw;
  bottom: 23%;
  right: 1%;
  animation-delay: 0s;
}

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

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