<route lang="json5">
{
  layout: 'default',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '%mine.pages.share.title%'
  }
}
</route>

<script setup lang="ts">
import tkiQrcode from 'tki-qrcode'
import { getUserInfoHook } from '@/hooks/usePageAuth'
import { t } from '@/locale'
import { useUserStore } from '@/store'
import { goBack } from '@/utils/page'
import { toast } from '@/utils/toast'

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

const userStore = useUserStore()
const baseUrl = import.meta.env.VITE_H5_BASE_URL

// 推荐码
const userInfo = computed(() => getUserInfoHook())
const qrcodeConfig = ref<any>({
  val: `${baseUrl}?referrer=${userInfo.value.invitedCode}`, // 推荐链接
  size: 500,
  background: '#ffffff',
  foreground: '#000000',
  pdground: '#000000',
  icon: '/static/icons/logo.png', // 中间logo
  iconsize: 60, // logo占比
  onval: true,
  loadMake: true,
  showLoading: false,
})
// 社交平台配置
const socialPlatforms = ref([
  {
    name: 'facebook',
    label: 'Facebook',
    icon: '/static/icons/facebook.png', // 占位图片路径
  },
  {
    name: 'whatsapp',
    label: 'Whatsapp',
    icon: '/static/icons/whatsapp.png', // 占位图片路径
  },
  {
    name: 'instagram',
    label: 'Instagram',
    icon: '/static/icons/instagram.png', // 占位图片路径
  },
  {
    name: 'twitter',
    label: 'Twitter',
    icon: '/static/icons/twitter.png', // 占位图片路径
  },
])

// 复制推荐码
function copyReferrerCode() {
  uni.setClipboardData({
    data: userInfo.value.invitedCode,
    success: () => {},
  })
}
// 生成邀请注册分享链接
function generateInviteShareLink() {
  // 邀请注册链接
  const inviteUrl = `${baseUrl}?referrer=${userInfo.value.invitedCode}`

  // 分享文案格式：[BandhuBuy] + 邀请注册链接 + 邀请文案
  const shareText = `[BandhuBuy] ${inviteUrl} Your friend invited you to register`

  return {
    url: inviteUrl,
    text: shareText,
  }
}

// 检查APP是否安装
function checkAppInstalled(platform: string): boolean {
  const appSchemes = {
    facebook: { pname: 'com.facebook.katana', scheme: 'fb://' },
    whatsapp: { pname: 'com.whatsapp', scheme: 'whatsapp://' },
    instagram: { pname: 'com.instagram.android', scheme: 'instagram://' },
    twitter: { pname: 'com.twitter.android', scheme: 'twitter://' },
  }

  const appInfo = appSchemes[platform]
  if (!appInfo)
    return false

  return plus.runtime.isApplicationExist({
    pname: appInfo.pname,
    action: appInfo.scheme,
  })
}

// 打开社交媒体APP分享
function openSocialApp(platform: string) {
  const { url, text } = generateInviteShareLink()

  // 先复制分享内容到剪贴板
  uni.setClipboardData({
    data: text,
    success: () => {
      console.log('分享内容已复制到剪贴板')
    },
  })

  const shareUrls = {
    facebook: `fb://facewebmodal/f?href=${encodeURIComponent(url)}`,
    whatsapp: `whatsapp://send?text=${encodeURIComponent(text)}`,
    instagram: 'instagram://camera', // Instagram不支持直接分享链接，打开相机
    twitter: `twitter://post?message=${encodeURIComponent(text)}`,
  }

  const shareUrl = shareUrls[platform]
  if (shareUrl) {
    plus.runtime.openURL(shareUrl, (error) => {
      console.error('打开APP失败:', error)
      toast.info(t('share.appNotInstalled'))
    })
  }
}

// 统一分享处理方法
function handleShare(platform: string) {
  // 检查APP是否安装
  if (!checkAppInstalled(platform)) {
    toast.info(t('share.appNotInstalled'))
    return
  }

  // 打开对应的社交媒体APP
  openSocialApp(platform)
}
onLoad(() => {
  // 页面加载时的逻辑
  userStore.getUserInfo()
})
</script>

<template>
  <view class="share-page min-h-screen bg-white">
    <!-- 背景图片区域 -->
    <view class="auth-bg-section relative">
      <!-- 自定义导航栏 -->
      <view :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
        <view class="h-88rpx flex items-center px-24rpx">
          <wd-icon name="thin-arrow-left" size="32rpx" @click="() => goBack()" />
        </view>
      </view>

      <!-- Logo和标语 -->
      <view class="pb-40rpx pt-134rpx text-center">
        <view class="mb-20rpx flex flex-col items-center justify-center">
          <image src="/static/login-logo.png" class="mb-18rpx h-56rpx w-350.48rpx" />
          <view>{{ $t('login.slogan') }}</view>
        </view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="flex flex-col px-24rpx">
      <!-- 推荐码标题 -->
      <view class="mb-10rpx mt-40rpx text-center">
        <text class="text-28rpx text-#333 font-medium">
          {{ $t('mine.pages.share.referrerCode') }}
        </text>
      </view>

      <!-- 推荐码显示 -->
      <view class="mb-44rpx flex items-center justify-center">
        <text class="mr-20rpx text-64rpx font-bold tracking-wider">
          {{ userInfo.invitedCode }}
        </text>
        <wd-icon name="file-copy" size="30rpx" color="#757575" @click="copyReferrerCode" />
      </view>

      <!-- 二维码区域 -->
      <view class="mb-60rpx flex justify-center">
        <!-- 二维码占位图 -->
        <view
          style="box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.1);"
          class="h-500rpx w-500rpx flex items-center justify-center border-#e5e5e5 rounded-12rpx bg-#f8f8f8"
        >
          <view class="text-center">
            <tki-qrcode
              ref="qrcode"
              :val="qrcodeConfig.val"
              :size="qrcodeConfig.size"
              :unit="qrcodeConfig.unit"
              :background="qrcodeConfig.background"
              :foreground="qrcodeConfig.foreground"
              :pdground="qrcodeConfig.pdground"
              :icon="qrcodeConfig.icon"
              :icon-size="qrcodeConfig.iconsize"
              :onval="qrcodeConfig.onval"
              :load-make="qrcodeConfig.loadMake"
              :show-loading="qrcodeConfig.showLoading"
            />
          </view>
        </view>
      </view>

      <!-- 分享说明 -->
      <view class="mb-60rpx text-center">
        <text class="text-28rpx text-#797979 leading-relaxed">
          {{ $t('mine.pages.share.description') }}
        </text>
      </view>

      <!-- 社交分享按钮 -->
      <view class="flex justify-center gap-50rpx">
        <view
          v-for="item in socialPlatforms"
          :key="item.name"
          class="flex flex-col items-center"
          @click="handleShare(item.name)"
        >
          <view class="mb-20rpx">
            <image
              :src="item.icon"
              class="h-80rpx w-80rpx"
              mode="aspectFit"
            />
          </view>
          <text class="text-24rpx text-#666 font-medium">
            {{ item.label }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
// 分享页面特有样式
.auth-bg-section {
  background-image: url('/static/login-bg.png');
  background-size: cover;
  background-position: top;
  background-repeat: no-repeat;
  min-height: 28vh;
}
</style>
