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

<script lang="ts" setup>
import { pendingRedDots } from '@/api/order'
import { getWalletAccountInfo } from '@/api/wallet'
import { t } from '@/locale'
import { useUserStore } from '@/store/user'
import { formatNumber } from '@/utils'
import { toPage } from '@/utils/page'

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

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

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

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

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

const groupList = ref([
  { 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 = ref([
  { 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'), icon: '/static/icons/live-chat.png' },
  { name: t('mine.menu.activity'), url: '/pages/referEarn/referEarn', icon: '/static/icons/activity-group.png' },
])
function menuClick(item: any) {
  if (item.url) {
    toPage({ url: item.url })
  }
  else {
    openWhatsApp()
  }
}
// 跳转whatsapp
function openWhatsApp() {
  // 判断手机是否安装whatsapp
  // pname：Android 需要查询的包名  action：ios 需要查询的 URL Scheme
  // installed ture:安装  false:未安装
  const installed = plus.runtime.isApplicationExist({
    pname: 'com.whatsapp',
    action: 'whatsapp://',
  })
  // 电话号码
  const phoneNumber = '+8615058371889'
  // whatsapp 联系人聊天页面链接
  const whatsappUrl = `whatsapp://send?phone=${phoneNumber}`
  // whatsapp包名
  const pname = 'com.whatsapp'

  // 判断手机系统，走不同方法
  if (plus.os.name === 'Android') {
    if (installed) {
      // 手机已安装 直接跳转
      plus.runtime.openURL(whatsappUrl)
    }
    else {
      // 手机未安装，跳转到手机商城并搜索whatsapp （国内目前搜不到）
      plus.nativeUI.actionSheet(
        {
          title: '选择应用',
          cancel: '取消',
          buttons: [{ title: '应用市场' }],
        },
        ({ index }) => {
          switch (index) {
            case 1:
              plus.runtime.openURL(
                `market://details?id=${pname}`,
                () => {
                  // 手机没有应用市场
                  plus.nativeUI.alert('本机未安装指定的应用')
                },
              )
          }
        },
      )
    }
  }
}
const walletInfo = ref<any>({})
async function getWalletInfo() {
  // 获取钱包信息-查询余额
  const res = await getWalletAccountInfo()
  console.log(res)
  walletInfo.value = res?.data
}

const pendingRedDotsData = ref<any>({})
async function getPendingRedDots() {
  try {
    const res = await pendingRedDots()
    if (res.code === '200') {
      console.log(res)
      pendingRedDotsData.value = res?.data
    }
  }
  catch {}
}
onShow(() => {
  getWalletInfo()
  getPendingRedDots()
})
onLoad(() => {
  // 页面加载时的逻辑
  userStore.getUserInfo()
})
</script>

<template>
  <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 text-32rpx font-bold">
        {{ userInfo?.name || userInfo?.username || 'User' }}
      </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>
</template>
