<template>
  <index v-if="state.tabIndex === 0" />
  <classify v-if="state.tabIndex === 1" />
  <cart v-if="state.tabIndex === 2" @setCartCount="setCartCount" />
  <my v-if="state.tabIndex === 3" />
  <tabbar :current="state.tabIndex" :list="state.list" @tab-change="(index) => state.tabIndex = index" />
</template>

<script setup lang="ts">
import api from "@/api";
import { onBeforeMount, reactive } from "vue";
import index from "./index/index.vue";
import classify from "./classify/index.vue";
import cart from "./cart/cart.vue";
import my from "./my/index.vue";
import tabbar from "@/components/layout/tabbar.vue";
import { PageUtils } from '@/utils/utils'
import { onPageScroll, onShow } from '@dcloudio/uni-app'
onPageScroll(e => { }) // uniapp的Bug，这句话不要去掉，否则to-top不生效
const state = reactive({
  tabIndex: 0,
  list: [
    {
      text: "首页",
      icon: "wap-home",
    },
    {
      text: "分类",
      icon: "bars",
    },
    {
      text: "购物车",
      icon: "shopping-cart",
      badge: 0
    },
    {
      text: "我的",
      icon: "manager",
    },
  ],
});
onShow(() => {
  const { token } = uni.getStorageSync("user") || {};
  if (token) {
    api.cartCount().then((data: any) => {
      const item = state.list.find((item: any) => item.text == '购物车')
      if (item) item.badge = data
    })
  }
})
onBeforeMount(() => {
  const query: any = PageUtils.getCurQuery()
  if (query.index) state.tabIndex = Number(query.index)
});

function setCartCount(num: number) {
  const item = state.list.find((item: any) => item.text == '购物车')
  if (item) item.badge = num
}
</script>

<style lang="scss" scoped>
</style>
