<script setup lang="ts">
  import { nextTick, ref } from 'vue'
  import { getBannerApi, getHotRecommendApi, getNoticeBartApi } from '@/api/home'
  import type { bannerItem, noticeBarItem } from '@/types/home'
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import categoryGroup from './components/categoryGroup.vue'
  import noticeBar from './components/notice-bar.vue'
  import hotRecommend from './components/hotRecommend.vue'
  import { getTopCategoryApi } from '@/api/catogory'
  import { useCartStore, useMemberStore } from '@/stores'
  import { getCartTotalNumApi } from '@/api/cart'

  //轮播图
  const bannerList = ref<bannerItem[]>([])
  const getBannerListData = async () => {
    const res = await getBannerApi()
    bannerList.value = res.result
  }
  //公告
  const noticeBarList = ref<noticeBarItem[]>([])
  const getNoticeBarData = async () => {
    const res = await getNoticeBartApi()
    noticeBarList.value = res.result
  }
  //分类
  const categoryList = ref()
  const getTopCategoryListData = async () => {
    const res = await getTopCategoryApi()
    categoryList.value = res.result
  }
  //热卖推荐
  const hotRecommendList = ref()
  const getHotRecommend = async () => {
    const res = await getHotRecommendApi()
    hotRecommendList.value = res.result
  }
  //商品列表
  const shopGoodsListRef = ref()

  const getIndexData = () => {
    return Promise.all([
      getBannerListData(),
      getNoticeBarData(),
      getTopCategoryListData(),
      getHotRecommend(),
    ])
  }

  onLoad(() => {
    getIndexData()
    // 首页分享
    // #ifdef MP-WEIXIN
    uni.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage'],
    })
    // #endif
  })

  onShow(() => {
    nextTick(() => {
      shopGoodsListRef.value.refresh()
    })

    const cartStore = useCartStore()
    //首页初始化设置购物车角标
    if (useMemberStore().profile) {
      getCartTotalNumApi().then((res) => {
        cartStore.setCartTotalNum(res.result)
      })
    } else {
      cartStore.setCartTotalNum(0)
    }
    cartStore.setCartTabBadge()
  })

  const handleRefresh = async (status : number) => {
    //触发刷新状态
    if (status === 2) {
      getIndexData()
    }
  }
</script>
<template>
  <shop-goods-list ref="shopGoodsListRef" @refresher-status-changed="handleRefresh" :options="{
      auto: false,
    }">
    <template #top>
      <shop-goods-search />
    </template>
    <template #middle>
      <shop-swiper :list="bannerList" v-if="bannerList" />
      <noticeBar :list="noticeBarList" />
      <category-group :list="categoryList" v-if="categoryList" />
      <hot-recommend :list="hotRecommendList" />
      <uni-section title="商品列表" type="line"></uni-section>
    </template>
  </shop-goods-list>
</template>

<style lang="scss">
  page {
    background-color: #f9f9f9;
  }
</style>
