<script setup>
import { ref, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import Container from "@/components/Container.vue";
import AppFooter from "@/components/AppFooter.vue";
import AppBackground from "@/components/AppBackground.vue";
import UserHeader from "@/components/UserHeader.vue";
import SModal from "@/components/SModal.vue";
import Signin from "@/components/Signin.vue";
import BubbleTip from "@/components/BubbleTip.vue";
import {
  getAppConfig,
  getRankListAPI,
  getHomeData,
  getMyDevicesAPI,
} from "@/apis";
import { topThreeColors } from "@/constants";
import useStore from "@/store";
import { storeToRefs } from "pinia";
const store = useStore();
const { updateConfig, updateUser, updateDevice, updateRank } = store;
// 使用storeToRefs，用于UI里显示，保持响应性
const { user, device, rankData } = storeToRefs(store);
const showModal = ref(false);
const isIos = ref(true);
const showGuide = ref(false);

const toPage = (path) => {
  if (!user.value.id) {
    showModal.value = true;
    return;
  }
  if (
    "/pages/first-try,/pages/practise,/pages/friend-battle".indexOf(path) !== -1
  ) {
    if (!device.value.deviceId) {
      return uni.showToast({
        title: "请先绑定设备",
        icon: "none",
      });
    }
    if ("/pages/first-try".indexOf(path) === -1 && !user.value.trio) {
      return uni.showToast({
        title: "请先完成新手试炼",
        icon: "none",
      });
    }
  }
  uni.navigateTo({
    url: path,
  });
};

const toRankListPage = () => {
  uni.navigateTo({
    url: "/pages/rank-list",
  });
};

onShow(async () => {
  const token = uni.getStorageSync("token");
  if (token) {
    const result = await getHomeData();
    updateRank(result);
    console.log("首页数据：", result);
    if (result.user) {
      updateUser(result.user);
      if (result.user.trio <= 0) {
        showGuide.value = true;
        setTimeout(() => {
          showGuide.value = false;
        }, 3000);
      }
      const devices = await getMyDevicesAPI();
      if (devices.bindings && devices.bindings.length) {
        updateDevice(
          devices.bindings[0].deviceId,
          devices.bindings[0].deviceName
        );
      }
    }
  } else {
    const result = await getRankListAPI();
    updateRank(result);
  }
});

onMounted(async () => {
  const deviceInfo = uni.getDeviceInfo();
  isIos.value = deviceInfo.osName === "ios";
  const config = await getAppConfig();
  updateConfig(config);
  console.log("全局配置：", config);
});

const comingSoon = () => {
  uni.showToast({
    title: "敬请期待",
    icon: "none",
  });
};
</script>

<template>
  <Container :isHome="true" :showBackToGame="true">
    <view class="container" :style="{ paddingTop: isIos ? '100rpx' : '70rpx' }">
      <UserHeader showRank :onSignin="() => (showModal = true)" />
      <view :style="{ padding: '12px 10px' }">
        <view class="feature-grid">
          <view class="bow-card">
            <image
              src="https://api.shelingxingqiu.com/attachment/2025-07-15/dbciq9qhkpd3pqxawo.webp"
              mode="widthFix"
              @click="() => toPage('/pages/my-device')"
            />

            <text v-if="!user.id">我的弓箭</text>
            <text v-if="user.id && !device.deviceId">请绑定设备</text>
            <text
              v-if="user.id && device.deviceId"
              class="truncate"
              :style="{ width: '90%', textAlign: 'center' }"
              >{{ device.deviceName }}</text
            >
            <image
              src="../static/a2@2x.png"
              mode="widthFix"
              @click="() => toPage('/pages/first-try')"
            />
            <BubbleTip
              v-if="showGuide"
              :location="{ top: '60%', left: '40%', fontSize: '14px' }"
            >
              <text>新人必刷！</text>
              <text>快来报到吧~</text>
            </BubbleTip>
          </view>

          <view class="practice-card" @click="() => toPage('/pages/practise')">
            <image src="../static/a2@2x(1).png" mode="widthFix" />
          </view>

          <view
            class="friend-card"
            @click="() => toPage('/pages/friend-battle')"
          >
            <image src="../static/a3@2x.png" mode="widthFix" />
          </view>
        </view>
        <view class="ranking-section">
          <image src="../static/a4@2x.png" mode="widthFix" />
          <button
            class="into-btn"
            @click="() => toPage('/pages/ranking')"
            hover-class="none"
          ></button>
          <view class="ranking-players" @click="toRankListPage">
            <img src="../static/juezhanbang.png" mode="widthFix" />
            <view class="divide-line"></view>
            <view class="player-avatars">
              <block v-for="i in 6" :key="i">
                <block v-if="rankData.rank && rankData.rank[i - 1]">
                  <view
                    class="player-avatar"
                    :style="{
                      zIndex: 8 - i,
                      borderColor: topThreeColors[i - 1] || '#000',
                    }"
                  >
                    <image v-if="i === 1" src="../static/champ1.png" />
                    <image v-if="i === 2" src="../static/champ2.png" />
                    <image v-if="i === 3" src="../static/champ3.png" />
                    <view v-if="i > 3">{{ i }}</view>
                    <image
                      :src="
                        rankData.rank[i - 1].avatar || '../static/user-icon.png'
                      "
                      mode="aspectFill"
                    />
                  </view>
                </block>
              </block>
              <view class="more-players">
                <text>{{ rankData.rank.length }}</text>
              </view>
            </view>
          </view>
          <view class="region-stats">
            <view
              v-for="(region, index) in [
                { name: '广东', score: 4291 },
                { name: '湖南', score: 3095 },
                { name: '内蒙', score: 2342 },
                { name: '海南', score: 1812 },
                { name: '四川', score: 1293 },
              ]"
              :key="index"
              class="region-item"
              @click="comingSoon"
            >
              <image src="../static/region-bg.png" mode="widthFix" />
              <image
                v-if="index === 0"
                src="../static/region-1.png"
                mode="widthFix"
              />
              <image
                v-if="index === 1"
                src="../static/region-2.png"
                mode="widthFix"
              />
              <image
                v-if="index === 2"
                src="../static/region-3.png"
                mode="widthFix"
              />
              <image
                v-if="index === 3"
                src="../static/region-4.png"
                mode="widthFix"
              />
              <image
                v-if="index === 4"
                src="../static/region-5.png"
                mode="widthFix"
              />
              <text>{{ region.name }}</text>
              <view>
                <text :style="{ color: '#fff', marginRight: '2px' }">{{
                  region.score
                }}</text>
                <text>分</text>
              </view>
            </view>
            <view class="region-more" @click="comingSoon">
              <image src="../static/region-more.png" mode="widthFix" />
              <text>...</text>
              <text>更多</text>
            </view>
          </view>
        </view>
      </view>
      <SModal :show="showModal" :onClose="() => (showModal = false)">
        <Signin :onClose="() => (showModal = false)" />
      </SModal>
    </view>
    <AppFooter :signin="() => (showModal = true)" />
  </Container>
</template>

<style scoped>
.container {
  width: 100%;
}

.feature-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "bow practice" "bow friend";
  row-gap: 5px;
  column-gap: 10px;
  margin-bottom: 10px;
}

.bow-card {
  grid-area: bow;
  position: relative;
}

.feature-grid > view > image {
  width: 100%;
}

.bow-card > text {
  position: absolute;
  top: 65%;
  left: 50%;
  transform: translate(-50%, -50%);
  white-space: nowrap;
  font-size: 13px;
  color: #b3b3b3;
}

.bow-card > image:first-child {
  transform: scaleY(1.08) translateY(9px);
}

.bow-card > image:nth-child(3) {
  transform: translateY(-1px);
}

.practice-card {
  grid-area: practice;
  width: 100%;
}

.friend-card {
  grid-area: friend;
  width: 100%;
}

.ranking-section {
  border-radius: 15px;
  padding: 15px;
  position: relative;
}

.ranking-section > image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: -1;
}

.into-btn {
  position: absolute;
  top: 40px;
  left: calc(50% - 100px);
  width: 200px;
  height: 100px;
}

.ranking-players {
  display: flex;
  align-items: center;
  padding-bottom: 20px;
  margin-top: 42%;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.ranking-players > image:first-child {
  width: 28%;
  transform: translateX(-10px) translateY(-8px);
}

.player-avatars {
  display: flex;
  align-items: center;
}

.divide-line {
  width: 1px;
  height: 35px;
  background-color: #80808033;
  margin-right: 8px;
}

.player-avatar,
.more-players {
  width: 82rpx;
  height: 82rpx;
  border-radius: 50%;
  margin-right: -10px;
  border: 1px solid #000;
  position: relative;
  box-sizing: border-box;
}

.player-avatar > image:first-child,
.player-avatar > view:first-child {
  position: absolute;
  top: -10px;
  left: 12px;
  width: 16px;
  height: 16px;
}
.player-avatar > view:first-child {
  border-radius: 50%;
  background: #777777;
  text-align: center;
  font-size: 10px;
  line-height: 18px;
  width: 18px;
  height: 18px;
  color: #fff;
}
.player-avatar > image:last-child {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.more-players {
  background: rgba(255, 255, 255, 0.2);
  font-size: 9px;
  line-height: 80rpx;
  text-align: center;
  z-index: 1;
}

.more-players > text {
  margin-left: 2px;
  color: #fff;
}

.region-stats {
  display: flex;
  grid-template-columns: repeat(6, 1fr);
  margin-top: 20px;
  justify-content: space-between;
}

.region-item,
.region-more {
  border-radius: 10px;
  text-align: center;
  position: relative;
  width: 13vw;
  height: 13vw;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #c5c5c5;
  font-size: 12px;
}
.region-item > text {
  margin-top: 10px;
}
.region-more {
  width: 8vw;
  height: 13vw;
}
.region-item > image:first-child,
.region-more > image:first-child {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: -1;
}
.region-item > image:nth-of-type(2) {
  position: absolute;
  top: 0;
  left: 0;
  width: 18px;
}
.region-item > view:last-child {
  display: flex;
  justify-content: center;
  font-size: 10px;
}
.region-more > text:first-of-type {
  font-size: 30px;
  line-height: 20px;
  margin-bottom: 5px;
}
</style>
