<template>
  <!-- 头部 -->
  <div class="home">
    <nav-top />
    <div class="content">
      <!-- 主题内容 -->
      <div class="content-box">
        <!-- 轮播 -->
        <swipe :carouselData="carouselData" />
        <!-- 广告 -->
        <notice />
        <!-- 中奖热门游戏介绍 -->
        <hot-user-game />
        <!-- 搜索 -->
        <search />
        <!-- 游戏分类 -->
        <div class="flex-type">
          <div class="first" @click="onClickFloat('gameTask')">
            <h-img
              style="width: 0.6rem; height: 0.6rem"
              type="local"
              src="base/icon.png"
            ></h-img>
            <div class="title">Missões</div>
            <h-img class="hot" type="local" src="base/Hot.png"></h-img>
          </div>
          <game-class @change="changeGameClass" />
        </div>
      </div>
      <!-- 游戏 -->
      <div
        class="game"
        v-for="(item, index) in getGameClassIdData"
        :key="index"
      >
        <!-- 链接导航 -->
        <nav-middle
          :providerList="providerList"
          v-if="item._id == '656587d196233dfbe2c185d5'"
        />
        <div class="game-list">
          <swiper-game-list
            ref="swiper"
            :list="newList(item)"
            :className="item.gameClassName"
          >
            <template v-slot:header>
              <div class="flex-sb bgimg imgShow">
                <div class="left flex-ct">
                  <img :src="getImage(item.gameClassImg)" />
                  <span>{{ item.gameClassName }}</span>
                  <span style="color: #58e02e">Jogos</span>
                </div>
                <div class="right">
                  <h-paging
                    :total="item.gameList.length"
                    @on-previous="previous(index)"
                    @on-nextPage="nextPage(index)"
                    @on-look="lookAll(item)"
                  />
                </div>
              </div>
            </template>
          </swiper-game-list>
        </div>
      </div>
      <!-- 链接导航 -->
      <div style="padding: 0.2rem">
        <nav-middle :providerList="providerList" />
      </div>
      <!-- 尾部 -->
      <footer-bar @goTop="goPosition" />
      <!-- 添加主屏幕 -->
      <!-- <add-to-home /> -->
      <!-- 转盘弹框 -->
      <turntable-popup v-model="showTurntable" />

      <h-tabbar />
    </div>
    <!-- 公告弹出框 -->
    <home-promotion />
    <!-- 首次充值 -->
    <div class="right-float2">
      <van-overlay
        :z-index="1000"
        :show="showOneRecharge && showOne"
        lock-scroll
      >
        <div class="deposit-box">
          <h-img type="local" src="deposit/OEM.png" />
          <div class="btn" @click="openDeposito">Depositar</div>
          <h-img
            @click.stop="closeOneDepost"
            type="local"
            src="deposit/close.png"
          />
        </div>
      </van-overlay>
    </div>
    <!-- 悬浮按钮 -->
    <float-handle @on-click="onClickFloat" />
    <!-- 客服 -->
    <div v-if="serviceShow" class="service-box">
      <div class="close">
        <img
          :src="getAssets('base/close.png')"
          @click.stop="closeIService"
          width="25"
        />
      </div>
      <iframe
        allow="fullscreen"
        id="iframe"
        :src="serviceSrc"
        style="width: 100%; height: 100vh; background-color: rgb(255, 255, 255)"
        frameborder="0"
      >
      </iframe>
    </div>
    <!-- 拼单单中奖提示 -->
    <h-center-popup
      v-model="pddAwardShow"
      :z-index="1001"
      title="Lembrete Vencedor"
      contentBgcolor="#004f43"
      @on-close="closePddAwardShow"
    >
      <div class="lembrete">
        <div>Parabéns por ganhar o prémio</div>
        <img
          class="left-box-phone"
          :src="getImage(propsListValue[0].iconUrl)"
        />
        <p>
          x
          {{
            userStore.pddAward[0]
              ? userStore.pddAward[0].num > 10000
                ? userStore.pddAward[0].num / 10000
                : 1
              : 0
          }}
        </p>
      </div>
    </h-center-popup>
  </div>
</template>
<script setup lang="ts">
import navTop from "./nav-top/index.vue";
import socketApi from "@/socket/socketApi";
import navMiddle from "./nav-middle/index.vue";
import hotUserGame from "./hot-user-game/index.vue";
import swipe from "./swipe/index.vue";
import notice from "./notice/index.vue";
import search from "./search/index.vue";
import footerBar from "./footer/index.vue";
import homePromotion from "../home-promotion/index.vue";
// import AddToHome from "./add-to-home/index.vue";
import { ref, onMounted, onBeforeMount, watch, computed } from "vue";
import TurntablePopup from "@/views/turntable/modal/index.vue";
import storage, { actions } from "@/utils/storage";
import { useBaseStore } from "@/stores/modules/base";
import { gameListStore } from "@/stores/modules/game-list";
import {
  formatGameList,
  getImage,
  getAssets,
  getLocationParams,
} from "@/utils";
// import useGift from "@/hooks/useGift";
import emitter from "@/utils/eventBus";
import router from "@/router";
import GameClass from "./components/game-class.vue";
import { useGameStore } from "@/stores/modules/game";
import { useUserStore } from "@/stores/modules/user";
import { googleOneTap, decodeCredential } from "vue3-google-login";
import useLogin from "@/hooks/useLogin";
import { onBeforeRouteLeave } from "vue-router";
import https from "@/https";
import { showLoading, closeLoading, toast } from "@/utils/toast";
import http from "@/https";
const { connectSocket } = useLogin();
const propsListValue = ref<Array<any>>([]);

// const { hasShowOneOfThree } = useGift();
const baseStore = useBaseStore();
const gameStore = gameListStore();
const GameStore = useGameStore();
const userStore = useUserStore();
const swiper = ref();
const providerList = computed(() => {
  return formatGameList(gameStore.providerList, 4);
});
const ID_LIST = [
  "656587af96233dfbe2c185a1",
  "654331e749e19afee35b4848",
  "656587d196233dfbe2c185d5",
];

const pddAwardShow = ref(false);
const serviceShow = ref(false);
const serviceSrc = ref("");
const closeIService = () => {
  serviceShow.value = false;
};
const openService = (url: any) => {
  serviceSrc.value = url;
  serviceShow.value = true;
};

emitter.on("openService", openService);

const getPropsCache = async () => {
  const res = await http.getPropsCache({
    propIds: [userStore.pddAward[0].propId],
  });
  if (res.code != 0) return;
  propsListValue.value = [...res.data.props];
};

const showOneRecharge = computed(() => {
  return userStore.userInfo && userStore.userInfo.totalPay == 0;
});
const closePddAwardShow = () => {
  userStore.setPddAward([]);
};
const showOne = ref(false);
watch(
  () => userStore.pddAward,
  async () => {
    console.log(userStore.pddAward);
    if (userStore.pddAward.length > 0) {
      await getPropsCache();
      console.log(propsListValue.value, "propsListValue.value");
      pddAwardShow.value = true;
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
watch(
  () => window.sessionStorage.getItem("showOne"),
  () => {
    if (window.sessionStorage.getItem("showOne") == "1") {
      showOne.value = false;
    } else {
      showOne.value = true;
    }
    if (window.sessionStorage.getItem("showOne") == "1") {
      showOne.value = false;
    } else {
      showOne.value = true;
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
async function onClickFloat(type: string) {
  if (!userStore.userInfo.uid) {
    return router.push("/login");
  }
  if (type == "redicon") {
    // 三合一礼包
    emitter.emit("openThreeInOne");
  } else if (type == "gameTask") {
    // 游戏任务
    router.push("/gameTask");
  } else if (type == "loteria") {
    // 拼单单
    router.push("/loteria");
  } else if (type == "signIn") {
    // 签到
    router.push("/signIn");
  }
}

const newList = computed(() => (item: any) => {
  if (item.gameList.length === 0) return [];
  if (ID_LIST.find((el: any) => el === item._id)) {
    return formatGameList(item.gameList.slice(0, 27), 9);
  } else {
    return formatGameList(item.gameList.slice(0, 18), 6);
  }
});

const openDeposito = () => {
  router.push("/deposit");
};
const closeOneDepost = () => {
  window.sessionStorage.setItem("showOne", "1");
  showOne.value = false;
};

const showTurntable = ref(false);

const carouselData = computed(() => {
  return gameStore.carouselData;
});

const getGameClassIdData = computed(() => {
  return gameStore.gameList;
});

const token = computed(() => storage.getStorage(actions.USER_TOEKN));

onBeforeMount(async () => {
  // storage.removeSessionStorage(actions.SEARCH_DATA);
  if (token.value) {
    await baseStore.getHelpTurntable();
    if (Number(storage.getSessionStorage(actions.DRAW_POPUP))) {
      showTurntable.value = false;
    } else if (
      baseStore.turntableConfig &&
      baseStore.turntableConfig.helpTurntable2Count !== 0 
    ) {
      showTurntable.value = true;
    } else {
      showTurntable.value = false;
    }
  } else {
    if (Number(storage.getSessionStorage(actions.DRAW_POPUP))) {
      showTurntable.value = false;
    } else {
      showTurntable.value = true;
    }
  }
});

onBeforeRouteLeave((to, from, next) => {
  let top: number;
  if (
    /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
      navigator.userAgent
    )
  ) {
    // 手机设备
    top = document.documentElement.scrollTop;
  } else {
    // PC设备
    top = 0;
  }
  // 记录页面高度
  storage.setSessionStorage(actions.HOME_POSITION, top);
  next();
});

onMounted(async () => {
  await gameStore.getGameList();
  const homePosition: string = <string>(
    storage.getSessionStorage(actions.HOME_POSITION)
  );
  console.log(homePosition);
  if (homePosition) {
    goPosition(Number(homePosition));
  }
  const token = storage.getStorage(actions.USER_TOEKN);
  setTimeout(() => {
    if (!token && baseStore.globalConfig.platformConfig) {
      googleOneTap()
        .then(async (response: any) => {
          const userData: any = decodeCredential(response.credential);
          showLoading();
          let params: any = {
            google: userData.sub,
          };
          let uid = getLocationParams(window.location.href);
          if (uid.u) {
            params.inviteUid = uid.u;
          }
          const { code, data, txt }: ResultData = await https.googleLogin(
            params
          );
          if (code !== 0) {
            toast(txt);
            closeLoading();
            return;
          }
          storage.setStorage(actions.USER_INFO, JSON.stringify(data));
          storage.setStorage(actions.USER_TOEKN, data.token);
          userStore.setUserInfo(data);
          connectSocket(data);
          closeLoading();
        })
        .catch((error: any) => {
          console.log(error, "googleOneTap error");
        });
    }
  }, 1000);

  if (!baseStore.globalConfig) {
    await baseStore.setGlobalConfig();
  }
  if (!baseStore.shareLinkUrl) {
    await baseStore.setShareLinkUrl();
  }
});

const goPosition = (top: number = 0) => {
  if (baseStore.innerWidth > 600) {
    const app: any = document.getElementById("app");
    app.scrollTo({
      top,
      left: 0,
      behavior: "smooth",
    });
    return;
  }
  setTimeout(() => {
    window.scrollTo({
      top,
      left: 0,
      behavior: "smooth",
    });
  }, 300);
};
// 上一页
function previous(index: number) {
  if (getGameClassIdData.value[index].gameList.length === 0) return;
  swiper.value[index].prevSwiper();
}
// 下一页
function nextPage(index: number) {
  if (getGameClassIdData.value[index].gameList.length === 0) return;
  swiper.value[index].nextSwiper();
}
function lookAll(data: any) {
  if (data.gameClassId === 14) return;
  storage.setStorage(actions.ALL_GAME_CLASS, data.gameClassId);
  router.push("/allGame");
}

// 首页点击搜索
const changeGameClass = (item: any) => {
  // const p = JSON.stringify({ type: 2, value: item.gameClassId });
  // storage.setSessionStorage(actions.SEARCH_DATA, p);
  const p = { type: 2, value: item.gameClassId };
  GameStore.setSearchData(p);
  router.push("/search");
};
</script>
<style lang="scss" scoped>
.lembrete {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  padding: 0.3rem;
  > div {
    font-size: 0.4rem;
    text-align: left;
    color: #fffd2c;
    width: 100%;
  }
  img {
    margin: 0.2rem;
  }
  > p {
    text-align: center;
    font-size: 0.4rem;
    font-weight: 600;
    color: red;
  }
}
.content {
  background: url("../../assets/img/base/bg.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  &-box {
    padding: 0 0.2rem;
    .flex-type {
      display: flex;
      justify-content: left;
      align-items: center;
      margin: 0.2rem 0 0.1rem 0;
      > .first {
        cursor: pointer;
        font-size: 0.3rem;
        margin-right: 0.1rem;
        padding: 0.1rem 0.15rem;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #2e3435;
        border-radius: 0.1rem;
        color: #bbb;
        border: 1px solid #2e3435;
        position: relative;
        > .title {
          margin-left: 0.1rem;
          font-weight: 500;
        }
        > .hot {
          width: 0.6rem;
          position: absolute;
          top: -0.3rem;
          right: 0;
        }
      }
    }
  }
  .game {
    padding: 0 0.2rem;
    .game-list {
      padding: 0.1rem 0;
    }
  }
  .imgShow {
    background-image: url("https://cdn.bxreplace.com/static/home/bj_yixing.png");
    background-size: 100% 190%;
    background-repeat: no-repeat;
  }
  .bgimg {
    .left {
      font-size: 0.4rem;
      font-weight: 600;
      justify-content: left;
      img {
        width: 1rem;
      }
      span {
        padding-left: 0.2rem;
      }
    }
  }
}
.right-float {
  position: fixed;
  right: 3%;
  bottom: 30%;
  z-index: 30;
}
.right-float2 {
  :deep(.van-overlay) {
    backdrop-filter: blur(6px);
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.3);
    background: rgba(0, 0, 0, 0.3);
  }
  .deposit-box {
    text-align: center;
    .btn {
      width: 5rem;
      height: 1rem;
      margin: 0.3rem auto;
      color: #8f310f;
      font-size: 0.4rem;
      margin: 0.3rem auto;
      color: #8f310f;
      font-size: 0.4rem;
      line-height: 1rem;
      font-weight: 600;
      background-image: url("../../assets/img/deposit/button.png");
      background-size: 100% 100%;
      background-repeat: no-repeat;
    }
  }
  // position: fixed;
  // right: 3%;
  // top: 30%;
  // z-index: 30;
  // cursor: pointer;
  // > img {
  //   width: 1.3rem;
  // }
}
.service-box {
  position: fixed;
  top: 0;
  @include pc {
    width: 500px !important;
    margin: 0 auto;
  }
  width: 100%;
  height: 100vh;
  z-index: 999999999999;
  .close {
    z-index: 999999999999;
    position: absolute;
    right: 5%;
    top: 2%;
  }
}
</style>
