<route lang="json5">
  {
    layout: 'tabbar',
    style: {
      navigationStyle: 'custom',
    },
  }
  </route>

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

import { getConfigByCode } from '@/api/common'
import { pendingRedDots } from '@/api/order'
import { getWalletAccountInfo } from '@/api/wallet'
import { t } from '@/locale'
import i18n from '@/locale/index'
import { useUserStore } from '@/store/user'
import { formatNumber } from '@/utils'
import { toPage } from '@/utils/page'
import { checkAppInstalled, getPlusRuntime, handleWhatsApp } from '@/utils/social'

defineOptions({
  name: 'Mine', // 我的
})

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

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

// 用户状态管理
const userStore = useUserStore()

// 判断是否已登录
const isLoggedIn = computed(() => !!userStore.token)

// 获取用户信息
const userInfo = computed(() => userStore.userInfo)

function copyReferrerCode() {
  const code = userInfo.value?.invitedCode
  if (!code)
    return
  uni.setClipboardData({
    data: code,
    success: () => {},
  })
}

function openWhatsAppStore() {
  const runtime = getPlusRuntime()
  if (!runtime)
    return

  const platform = uni.getSystemInfoSync().platform
  // Android：优先使用 market:// 拉起 Google Play，其次回退 https
  if (platform === 'android') {
    runtime.openURL(
      'market://details?id=com.whatsapp',
      () => {
        runtime.openURL('https://play.google.com/store/apps/details?id=com.whatsapp&pli=1')
      },
    )
    return
  }

  // iOS：使用 itms-apps:// 拉起 App Store，其次回退 https
  if (platform === 'ios') {
    runtime.openURL(
      'itms-apps://itunes.apple.com/app/id310633997',
      () => {
        runtime.openURL('https://apps.apple.com/app/id310633997')
      },
    )
  }
}

const groupList = computed(() => {
  // 依赖 locale，确保切换语言后这里会重新计算
  const _locale = i18n.global.locale
  void _locale
  return [
    { name: t('mine.group.toPay'), url: `/pages/myOrders/myOrders`, dotName: 'toPayNum', type: 1, icon: '/static/icons/to-pay.png' },
    { name: t('mine.group.success'), url: `/pages/myOrders/myOrders`, type: 2, dotName: 'successNum', icon: '/static/icons/success.png' },
    { name: t('mine.group.failed'), url: `/pages/myOrders/myOrders`, type: 3, dotName: 'failedNum', icon: '/static/icons/failed.png' },
    { name: t('mine.group.reward'), url: `/pages/myOrders/myOrders`, type: 4, dotName: 'rewardNum', icon: '/static/icons/reward.png' },
  ]
})

const menuList = computed(() => {
  const _locale = i18n.global.locale
  void _locale
  return [
    { name: t('mine.menu.profile'), url: '/pages/mine/myProfile', icon: '/static/icons/my-profile.png' },
    { name: t('mine.menu.address'), url: '/pages/mine/addressBook', icon: '/static/icons/address-book.png' },
    { name: t('mine.menu.share'), url: '/pages/mine/share', icon: '/static/icons/share.png' },
    { name: t('mine.menu.favorite'), url: '/pages/mine/myFavorite', icon: '/static/icons/my-favorite.png' },
    { name: t('mine.menu.chat'), config: 'live_chat', icon: '/static/icons/live-chat.png' },
    // { name: t('mine.menu.activity'), config: 'activity_group', icon: '/static/icons/activity-group.png' },
  ]
})

async function getConfig(code: string) {
  try {
    let value = ''
    const res = await getConfigByCode({ code })
    if (res.code === '200') {
      switch (code) {
        case 'live_chat':
          value = res.data.valueInfo
          break
        case 'activity_group':
          value = res.data.valueInfo
          break
        default:
          break
      }
    }
    return value
  }
  catch {

  }
}
async function menuClick(item: any) {
  if (item.url) {
    toPage({ url: item.url })
  }
  else {
    const res = await getConfig(item.config)
    const runtime = getPlusRuntime()
    if (runtime && !checkAppInstalled('whatsapp')) {
      openWhatsAppStore()
      return
    }
    handleWhatsApp(item.config as 'live_chat' | 'activity_group', res)
  }
}
const walletInfo = ref<any>({})
async function getWalletInfo() {
  if (!isLoggedIn.value)
    return
  // 获取钱包信息-查询余额
  const res = await getWalletAccountInfo()
  console.log(res)
  walletInfo.value = res?.data
}

const pendingRedDotsData = ref<any>({})
async function getPendingRedDots() {
  if (!isLoggedIn.value)
    return
  try {
    const res = await pendingRedDots()
    if (res.code === '200') {
      console.log(res)
      pendingRedDotsData.value = res?.data
    }
  }
  catch {}
}

// 下拉刷新时调用
async function handleRefresh() {
  if (!isLoggedIn.value) {
    walletInfo.value = {}
    pendingRedDotsData.value = {}
    paging.value?.complete()
    return
  }
  await Promise.all([
    getWalletInfo(),
    getPendingRedDots(),
    userStore.getUserInfo(),
  ])
  paging.value?.complete()
}

onShow(() => {
  if (isLoggedIn.value) {
    getWalletInfo()
    getPendingRedDots()
    userStore.getUserInfo()
  }
  else {
    walletInfo.value = {}
    pendingRedDotsData.value = {}
  }
})
</script>

<template>
  <z-paging ref="paging" use-page-scroll refresher-only @refresh="handleRefresh">
    <view
      class="flex items-center justify-between bg-[rgba(var(--wot-color-theme-rgb),0.3)] pb-72rpx pl-24rpx pr-54rpx"
      :style="{ paddingTop: `${safeAreaInsets?.top + 24}px` }"
    >
      <view class="flex items-center">
        <wd-img
          width="96rpx"
          height="96rpx"
          round
          :src="isLoggedIn ? userInfo?.headPic : '/static/images/default-avatar.png'"
        />
        <!-- 已登录 -->
        <view v-if="isLoggedIn" class="ml-24rpx flex flex-col">
          <view class="flex items-center">
            <view class="text-32rpx font-bold">
              {{ userInfo?.name || userInfo?.username || 'User' }}
            </view>
            <view
              v-if="userInfo?.level !== undefined && userInfo?.level !== null"
              class="ml-12rpx rounded-full bg-#DFBA86 px-16rpx py-2rpx text-24rpx text-white font-bold"
            >
              V{{ userInfo?.level }}
            </view>
          </view>
          <view class="mt-12rpx flex items-center text-24rpx">
            <text>{{ $t('mine.header.referrerCode') }}:</text>
            <text class="ml-12rpx font-bold">
              {{ userInfo?.invitedCode || '-' }}
            </text>
            <text class="mx-12rpx">
              |
            </text>
            <text class="font-bold" @click.stop="copyReferrerCode">
              {{ $t('mine.header.copy') }}
            </text>
          </view>
        </view>
        <!-- 未登录 -->
        <view v-else class="ml-24rpx flex items-center">
          <wd-button size="small" custom-class="mr-20rpx! bg-transparent!" plain @click="toPage({ url: '/pages/register/register' })">
            {{ $t('mine.auth.register') }}
          </wd-button>
          <wd-button size="small" @click="toPage({ url: '/pages/login/login' })">
            {{ $t('mine.auth.login') }}
          </wd-button>
        </view>
      </view>
      <wd-icon name="setting" color="#3A444C" size="36rpx" @click="toPage({ url: '/pages/mine/setting' })" />
    </view>
    <view class="relative rounded-tl-24rpx rounded-tr-24rpx bg-white px-24rpx pb-36rpx pt-32rpx -top-24rpx" @click="toPage({ url: '/pages/wallet/myWallet' })">
      <view class="mb-24rpx text-32rpx">
        {{ $t('mine.wallet.title') }}
      </view>
      <view
        class="flex items-center justify-between rounded-12rpx bg-[rgba(var(--wot-color-theme-rgb),0.1)] px-16rpx py-34rpx"
      >
        <view class="flex items-center">
          <wd-img width="84rpx" height="84rpx" round src="/static/icons/wallet-balance.png" />
          <view class="ml-18rpx">
            <view class="mb-3px text-22rpx text-#595959">
              {{ $t('mine.wallet.balance') }}
            </view>
            <view class="text-44rpx text-[var(--wot-color-theme)] font-bold">
              {{ formatNumber(walletInfo.balance) }}
            </view>
          </view>
        </view>
        <view class="flex flex-col items-end" @click.stop="toPage({ url: '/pages/wallet/recharge' })">
          <wd-button size="small">
            {{ $t('mine.wallet.recharge') }}
          </wd-button>
        </view>
      </view>
    </view>
    <view class="mb-24rpx bg-white px-24rpx pb-32rpx pt-26rpx">
      <view class="mb-24rpx flex items-center justify-between">
        <text class="text-32rpx">
          {{ $t('mine.group.title') }}
        </text>
        <view class="flex items-center" @click="toPage({ url: '/pages/myOrders/myOrders' })">
          <text class="mr-8rpx text-22rpx text-#3A444C">
            {{ $t('mine.group.all') }}
          </text>
          <wd-icon name="chevron-right" size="28rpx" />
        </view>
      </view>
      <view class="grid grid-cols-4 gap-24rpx">
        <view v-for="(item, index) in groupList" :key="index" class="flex flex-col items-center" @click="toPage({ url: item.url, params: { type: item.type } })">
          <wd-badge :model-value="item.type === 3 ? 0 : pendingRedDotsData[item.dotName]" :max="99">
            <wd-img width="48rpx" height="48rpx" :src="item.icon" />
          </wd-badge>
          <view class="mt-24rpx text-22rpx text-#3A444C">
            {{ item.name }}
          </view>
        </view>
      </view>
    </view>
    <view class="grid grid-cols-3 gap-48rpx bg-white py-65rpx">
      <view v-for="(item, index) in menuList" :key="index" class="flex flex-col items-center" @click="menuClick(item)">
        <wd-img width="48rpx" height="48rpx" :src="item.icon" />
        <view class="mt-24rpx text-22rpx text-#3A444C">
          {{ item.name }}
        </view>
      </view>
    </view>
  </z-paging>
  <!-- 在页面最下方添加占位视图，高度等于 tabBar 的高度 -->
  <!-- <view class="edgeInsetBottom" /> -->
</template>
