<template>
  <view class="tab-page">
    <SupplierHomePanel
      v-if="isSupplier && isLoggedIn"
      ref="homePanel"
    />
    <DistributorHomePanel
      v-else-if="isDistributor && isLoggedIn"
      ref="homePanel"
    />
    <GuestView
      v-else-if="!isLoggedIn"
      hint="登录后查看交易数据"
      @login="goLogin"
    />
  </view>
</template>

<script>
import SupplierHomePanel from '@/components/supplier/home-panel.vue'
import DistributorHomePanel from '@/components/distributor/home-panel.vue'
import GuestView from '@/components/partner/guest-view.vue'
import { useUserStore } from '@/store/user'
import { isEffectiveDistributorRole, isEffectiveSupplierRole } from '@/utils/partnerRole'
import { refreshTabPanelOnShow } from '@/utils/tabPanel'

export default {
  components: {
    SupplierHomePanel,
    DistributorHomePanel,
    GuestView
  },
  data() {
    return {
      isLoggedIn: false,
      isSupplier: false,
      isDistributor: false
    }
  },
  onShow() {
    refreshTabPanelOnShow(this, {
      refreshRole: this.refreshRole,
      refName: 'homePanel',
      shouldReload: () => this.isLoggedIn && (this.isSupplier || this.isDistributor)
    })
  },
  onHide() {
    const panel = this.$refs.homePanel
    if (panel && typeof panel.stopRealtimePoll === 'function') {
      panel.stopRealtimePoll()
    }
  },
  methods: {
    refreshRole() {
      const userStore = useUserStore()
      const roles = userStore.state.roles
      this.isLoggedIn = userStore.isLoggedIn()
      this.isSupplier = isEffectiveSupplierRole(roles)
      this.isDistributor = isEffectiveDistributorRole(roles)
    },
    goLogin() {
      uni.navigateTo({ url: '/pages/login/index' })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/tab-page.scss';
</style>
