<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
  layout: 'tabbar',
  style: {
    // 'custom' 表示开启自定义导航栏，默认 'default'
    navigationStyle: 'custom',
  },
}
</route>

<script lang="ts" setup>
// 必须导入需要用到的页面生命周期（即使在当前页面上没有直接使用到）
// eslint-disable-next-line unused-imports/no-unused-imports
import { onPageScroll, onReachBottom } from '@dcloudio/uni-app'
import useZPaging from 'z-paging/components/z-paging/js/hooks/useZPaging.js'

import { bannerList, noticeUnread } from '@/api/common'
import { getList } from '@/api/product'
import { parseQs } from '@/utils'
import { toPage } from '@/utils/page'

defineOptions({
  name: 'Index', // 首页
})

// 获取屏幕边界到安全区域距离
const systemInfo = uni.getSystemInfoSync()
const safeAreaInsets = systemInfo.safeAreaInsets

// z-paging
const paging = ref(null)
// 类似mixins，如果是页面滚动务必要写这一行，并传入当前ref绑定的paging，注意此处是paging，而非paging.value
useZPaging(paging)

// 轮播图
const current = ref<number>(0)
const swiperList = ref([])
function handleSwiperClick(e: any) {
  if (e.item.linkType === 0) {
    const url = e.item.link.split('?')[0]
    const params = parseQs(e.item.link.split('?')[1] || '')
    toPage(url, params)
  }
  else {
    toPage('/pages/webLink/webLink', { title: e.item.title, link: e.item.link })
  }
}

// 导航图标
const navIcons = ref([
  {
    image: '/static/icons/mission-center.png',
    title: 'home.missionCenter',
    size: '100rpx',
    url: '/pages/missionCenter/missionCenter',
  },
  {
    image: '/static/icons/refer-earn.png',
    title: 'home.refer&earn',
    size: '100rpx',
    url: '/pages/referEarn/referEarn',
  },
  {
    image: '/static/icons/vip-membership.png',
    title: 'home.vip',
    size: '112rpx',
    url: '/pages/vipMembership/vipMembership',
  },
  {
    image: '/static/icons/best-sellers.png',
    title: 'home.bestSellers',
    size: '100rpx',
    url: '/pages/bestSellers/bestSellers',
  },
  {
    image: '/static/icons/top-champions.png',
    title: 'home.topChampions',
    size: '100rpx',
    url: '/pages/topChampions/topChampions',
  },
])

// 新品列表
const newProducts = ref<any>([])

async function getNewList() {
  const res = await getList({ page: 1, size: 20 })
  console.log(res)
  newProducts.value = res.data.list
}

//  商品列表
const priceTab = ref<number>(0)

// 300Spot    500Spot    1000Spot    2000Spot
const priceTabList = ref([
  {
    title: 'home.priceTab.300spot',
    value: 300,
    minPrice: 0,
    maxPrice: 300,
  },
  {
    title: 'home.priceTab.500spot',
    value: 500,
    minPrice: 300,
    maxPrice: 500,
  },
  {
    title: 'home.priceTab.1000spot',
    value: 1000,
    minPrice: 500,
    maxPrice: 1000,
  },
  {
    title: 'home.priceTab.2000spot',
    value: 2000,
    minPrice: 1000,
    maxPrice: 2000,
  },
])

const dataList = ref<any>([])
async function queryList(pageNo: number, pageSize: number) {
  // 获取当前选中tab的价格范围，默认为第一个tab (0-300)
  const currentTab = priceTabList.value[priceTab.value] || priceTabList.value[0]
  const minPrice = currentTab?.minPrice ?? 0
  const maxPrice = currentTab?.maxPrice ?? 300

  const params = {
    page: pageNo,
    size: pageSize,
    minPrice,
    maxPrice,
  }
  const res = await getList(params)
  paging.value.complete(res.data.list)
}

async function getBannerList() {
  const res = await bannerList({ page: 1, size: 20 })
  swiperList.value = res.data.list
}

// 价格tab切换事件
function onPriceTabChange() {
  paging.value.reload()
}
const unread = ref(0)
async function getUnread() {
  try {
    const res = await noticeUnread()
    if (res.code === '200') {
      unread.value = Number(res.data) || 0
    }
  }
  catch {

  }
}

onShow(() => {
  getUnread()
  getNewList()
  getBannerList()
})
</script>

<template>
  <z-paging ref="paging" v-model="dataList" bg-color="#fff" use-page-scroll @query="queryList">
    <template #top>
      <view
        class="flex items-center justify-between bg-white pb-40rpx pl-42rpx pr-34rpx pt-26rpx"
        :style="{ paddingTop: `${safeAreaInsets?.top + 13}px` }"
      >
        <image src="/static/header-logo.png" class="h-44rpx w-275rpx" />
        <view class="flex items-center">
          <image src="/static/icons/search.png" class="mr-20rpx h-36rpx w-36rpx" @click="toPage('/pages/search/search')" />
          <wd-badge :model-value="unread" :max="99">
            <image src="/static/icons/notifications.png" class="h-36rpx w-36rpx" @click="toPage('/pages/notifications/notifications')" />
          </wd-badge>
        </view>
      </view>
    </template>
    <wd-swiper
      v-model:current="current"
      :list="swiperList"
      value-key="image"
      autoplay
      :indicator="{ type: 'fraction' }"
      indicator-position="bottom-right"
      @click="handleSwiperClick"
    />
    <view class="px-24rpx pb-24rpx">
      <view class="flex items-end justify-between pb-22rpx pt-24rpx">
        <view v-for="(item, index) in navIcons" :key="index" class="flex flex-col items-center" @click="toPage(item.url)">
          <image :src="item.image" :style="`width: ${item.size}; height: ${item.size};`" />
          <view class="mt-14rpx whitespace-pre-line text-center text-22rpx text-#898989 font-bold">
            {{ $t(item.title) }}
          </view>
        </view>
      </view>
      <view v-if="newProducts.length">
        <view class="mb-16rpx text-32rpx">
          {{ $t('home.news') }}
        </view>
        <scroll-view scroll-x>
          <view class="flex items-center gap-22rpx pb-24rpx">
            <product v-for="(item, index) in newProducts" :key="index" :item="item" @item-click="toPage('/pages/productDetail/productDetail', { productId: item.productId })" />
          </view>
        </scroll-view>
      </view>
      <view>
        <wd-tabs v-model="priceTab" :line-width="0" :line-height="0" @change="onPriceTabChange">
          <template v-for="item in priceTabList" :key="item">
            <wd-tab :title="$t(item.title)" />
          </template>
        </wd-tabs>
        <view class="grid grid-cols-2 gap-22rpx">
          <product v-for="(item, index) in dataList" :key="index" width="100%" :height="340" :item="item" @item-click="toPage('/pages/productDetail/productDetail', { productId: item.productId })" />
        </view>
      </view>
    </view>
  </z-paging>
</template>

<style>
page {
  background: #fff;
}
</style>
