<script lang="ts" setup>
import {useConfigStore, useUserStore} from "@/store";
import TabbarHome from "@/pages/home/components/tabbar-home/tabbar-home.vue";
import TabbarOrder from "@/pages/home/components/tabbar-order/tabbar-order.vue";
import TabbarMine from "@/pages/home/components/tabbar-mine/tabbar-mine.vue";
import TabbarMenu from "@/pages/home/components/tabbar-menu/tabbar-menu.vue";
import LogOut from "@/pages/home/components/tabbar-mine/components/log-out/log-out.vue";
import ChooseLanguage from "@/pages/home/components/tabbar-mine/components/choose-language/choose-language.vue";
import Menu from "./components/tabbar-menu/components/menu.vue";
import store from "./components/tabbar-home/components/store.vue";
import Config from "@/config";
import {useMessage} from "wot-design-uni";
import type UseCode from "@/components/use-code/use-code.vue";
import {appMerchantSwitchMerchantIdGet, appMessageUnreadCountPost} from "@/service";
import {getDictFineList} from "@/pages-user/service";
import {appUpdate} from "@/utils/update";


const userStore = useUserStore()
const configStore = useConfigStore()
const message = useMessage()
const {t} = useI18n()
const tabbarHomeRef = ref<InstanceType<typeof TabbarHome>>()
const tabbarOrderRef = ref<InstanceType<typeof TabbarOrder>>()
const tabBarMineRef = ref<InstanceType<typeof TabbarMine>>()
const tabbarMenuRef = ref<InstanceType<typeof TabbarMenu>>()
const chooseLanguageRef = ref<InstanceType<typeof ChooseLanguage>>()

const logOutRef = ref()
const useCodeRef = ref<InstanceType<typeof UseCode>>()

const activeIndex = ref('home')
const tabBarList = ref([
  {
    iconPath: '/static/tabbar/home.png',
    selectedIconPath: '/static/tabbar/homeHL.png',
    text: t('tabBar.home'),
    code: 'home',
  },
  {
    iconPath: '/static/tabbar/order.png',
    selectedIconPath: '/static/tabbar/orderHL.png',
    text: t('tabBar.order'),
    code: 'order',
  },
  {
    iconPath: '/static/tabbar/menu.png',
    selectedIconPath: '/static/tabbar/menuHL.png',
    text: t('tabBar.menu'),
    code: 'menu',
  },
  {
    iconPath: '/static/tabbar/user.png',
    selectedIconPath: '/static/tabbar/userHL.png',
    text: t('tabBar.mine'),
    code: 'mine',
  },
])


function handleLogOut() {
  if (logOutRef.value) {
    logOutRef.value.init()
  }
}


function handleChooseLanguage() {
  if (chooseLanguageRef.value) {
    chooseLanguageRef.value.init()
  }
}

const changeMenuRef = ref()

function changeMenu() {
  const menuId = tabbarMenuRef.value?.getCurrentMenuId?.()
  if (changeMenuRef.value) {
    changeMenuRef.value.onOpen(menuId)
  }
}

function confirmChangeMenu(id: string) {
  console.log('切换菜单了', id)
  tabbarMenuRef.value?.indexChangeMenu(id)
}

const changeStoreRef = ref()

function changeStore() {
  if (changeStoreRef.value) {
    changeStoreRef.value.onOpen()
  }
}

// 确认切换店铺了
function confirmChangeStore(data) {
  console.log('切换店铺了', data)
  if (userStore.currenMerchantInfo && data.value === userStore.currenMerchantInfo?.id) return
  appMerchantSwitchMerchantIdGet({
    params: {
      merchantId: data.value
    }
  }).then(res => {
    if (res.data) {
      userStore.currentMerchantToken = res.data
      userStore.getSwitchableMerchantInfo()

      handleTabbarChange({value: activeIndex.value})
    }
    // 查询商户首页数据
    // tabbarHomeRef.value?.initData()
  })
}

function handleTabbarChange({value}: { value: string }) {
  console.log('onShow执行到这里', value)
  switch (value) {
    case 'home':
      tabbarHomeRef.value?.init()
      tabbarHomeRef.value?.initData()
      getUnreadMessageCount()
      break
    case 'menu':
      tabbarMenuRef.value?.init()
      tabbarMenuRef.value?.initData()
      break
    case 'order':
      tabbarOrderRef.value?.initData()
      break
    case 'mine':
      tabBarMineRef.value?.init()
  }
}


function getFontUrl(fontRelativeUrl: string): string {
  let fontUrl = `url(/static/fonts/${fontRelativeUrl})`
  // #ifdef APP-PLUS
  fontUrl = `url(${plus.io.convertLocalFileSystemURL(`_www/static/fonts/${fontRelativeUrl}`)})`
  // #endif
  console.log('fontUrl', fontUrl)
  return fontUrl
}

function loadFonts() {
  // ---------------- 加载Helveticanowtext字体 ----------------
  uni.loadFontFace({
    family: 'UberMove',
    source: getFontUrl('UberMoveRegular.ttf'),
    success() {
      console.log('加载字体成功 UberMoveRegular')
    },
    fail(error) {
      console.log('加载字体失败')
      console.log(error)
    },
  })
  uni.loadFontFace({
    family: 'UberMove',
    source: getFontUrl('UberMoveMedium.otf'),
    desc: {
      weight: '500',
    },
    success() {
      console.log('加载字体成功 UberMoveMedium')
    },
    fail(error) {
      console.log('加载字体失败')
      console.log(error)
    },
  })
  uni.loadFontFace({
    family: 'UberMove',
    source: getFontUrl('UberMoveBold.otf'),
    desc: {
      weight: '700',
    },
    success() {
      console.log('加载字体成功 UberMoveBold')
    },
    fail(error) {
      console.log('加载字体失败')
      console.log(error)
    },
  })
}

useNetworkStatusChange(() => {
  nextTick(() => {
    // tabbarHomeRef.value?.initData()
    // tabbarShopRef.value?.initData()
    // tabbarShopRef.value?.init()
    // tabbarOrderRef.value?.initData()
    // tabBarMineRef.value?.init()
  })
})


onLoad(() => {
  loadFonts()
  uni.hideTabBar()
  // #ifdef APP-PLUS
  setTimeout(() => {
    appUpdate()
  }, 3000)
  // #endif

  // 获取支付相关配置
  getDictFineList({
    dictType: 'app_config'
  }).then(res => {
    res.data.map(item => {
      if (item.dictValue === 'stripeKey') {
        Config.stripeKey = item.remark
      }
    })
  })
})

onShow(() => {
  if (configStore.tabbarIndex) {
    activeIndex.value = configStore.tabbarIndex
  }
  nextTick(() => {
    handleTabbarChange({value: activeIndex.value})
  })

  if (userStore.isLogin) {
    getUnreadMessageCount()
    userStore.getFirstShopSettled()
    userStore.getSwitchableMerchants(() => {
      // 自动切换店铺
      setTimeout(() => {
        console.log('开始自动切换店铺')
        if (!userStore.currentMerchantToken && userStore.merchants.length > 0) {
          console.log('自动切换店铺', userStore.merchants[0].id)
          console.log('自动切换店铺', userStore.merchants[0].merchantName)
          confirmChangeStore({
            value: userStore.merchants[0].id
          })
        }
      }, 10)
    })
    userStore.getSwitchableMerchantInfo()
  }
})

// 获取未读消息数量
function getUnreadMessageCount() {
  if (!userStore.isLogin) return
  console.log('--------------------获取未读消息数量',)
  appMessageUnreadCountPost({}).then(res => {
    console.log('--------------------获取未读消息数量', res)
    userStore.unreadMessageCount = res.data || 0
  })
}
</script>

<template>
  <view class="page">
    <tabbar-home v-show="activeIndex==='home'" ref="tabbarHomeRef" @changeStore="changeStore"/>
    <tabbar-order v-show="activeIndex==='order'" ref="tabbarOrderRef" @changeStore="changeStore"/>
    <tabbar-menu v-show="activeIndex==='menu'" ref="tabbarMenuRef" @changeMenu="changeMenu"
                 @changeStore="changeStore"/>
    <tabbar-mine
        v-show="activeIndex==='mine'"
        ref="tabBarMineRef"
        @chooseLanguage="handleChooseLanguage"
        @logOut="handleLogOut"
    />
    <wd-tabbar
        v-model="activeIndex"
        activeColor="#333"
        custom-class="bg-#fff shadow-[0rpx_-6rpx_24rpx_rgba(0,0,0,0.1)]"
        fixed
        inactiveColor="#999"
        placeholder
        safeAreaInsetBottom
        @change="handleTabbarChange"
    >
      <wd-tabbar-item v-for="(item) in tabBarList" :key="item.code" :name="item.code" :title="item.text">
        <template #icon>
          <view class="relative center">
            <wd-img
                v-show="activeIndex===item.code"
                :src="item.selectedIconPath"
                class="absolute" custom-class="animate-in fade-in-50 zoom-in-80"
                height="46rpx" width="46rpx"></wd-img>
            <wd-img
                v-show="activeIndex!==item.code"
                :src="item.iconPath"
                class="absolute" custom-class="animate-in fade-in-50" height="46rpx"
                width="46rpx"></wd-img>
          </view>
        </template>
      </wd-tabbar-item>
    </wd-tabbar>
  </view>
  <log-out ref="logOutRef"/>
  <use-code ref="useCodeRef"/>
  <choose-language ref="chooseLanguageRef"/>
  <Menu ref="changeMenuRef" @confirm="confirmChangeMenu"/>
  <store ref="changeStoreRef" @confirm="confirmChangeStore"/>
</template>

<style lang="scss">

</style>
