<script lang="ts" setup>
import { getConfigByCode } from '@/api/common'
import { toPage } from '@/utils/page'
import { openH5WhatsApp } from '@/utils/social'
import { toast } from '@/utils/toast'

const props = defineProps<{
  bottomOffset?: number
}>()

const active = ref<boolean>(false)

const TABBAR_PAGES = [
  'pages/index/index',
  'pages/income/income',
  'pages/mine/mine',
]

function rpxToPx(rpx: number) {
  const sys = uni.getSystemInfoSync()
  const windowWidth = sys.windowWidth || 375
  return (rpx * windowWidth) / 750
}

function getCurrentRoutePath() {
  const pages = getCurrentPages() as any[]
  const last = pages?.[pages.length - 1]
  const route = String(last?.route || '')
  return route.replace(/^\//, '')
}

function isTabbarPage() {
  const route = getCurrentRoutePath()
  return TABBAR_PAGES.includes(route)
}

function getBottomOffsetPx() {
  const sys = uni.getSystemInfoSync() as any
  const extraOffsetPx = rpxToPx(props.bottomOffset ?? 0)
  const safeBottomPx = Number(sys?.safeAreaInsets?.bottom) || 0
  const tabbarHeightPx = isTabbarPage() ? 50 : 0
  return extraOffsetPx + safeBottomPx + tabbarHeightPx
}

const fabCustomStyle = computed(() => {
  const bottomPx = getBottomOffsetPx()
  return `bottom: ${bottomPx}px;`
})

async function openCustomerService() {
  active.value = false
  try {
    const res = await getConfigByCode({ code: 'live_chat' })
    const value = res?.data?.valueInfo
    if (!value) {
      toast.info('客服暂不可用')
      return
    }
    openH5WhatsApp('live_chat', value)
  }
  catch {
    toast.info('客服暂不可用')
  }
}

function openHelpCenter() {
  active.value = false
  toPage({ url: '/pages/mine/helpCenter' })
}
</script>

<template>
  <wd-fab v-model:active="active" position="right-bottom" :z-index="999" direction="top" :custom-style="fabCustomStyle" :expandable="false" :draggable="true">
    <template #trigger>
      <view class="w-68rpx">
        <image src="/static/icons/whatsapp-fb.png" class="customer-fab-action__icon mb-12rpx" mode="heightFix" @click="openCustomerService" />
        <image src="/static/icons/help-fb.png" class="customer-fab-action__icon" mode="heightFix" @click="openHelpCenter" />
      </view>
    </template>
  </wd-fab>
</template>

<style lang="scss" scoped>
.customer-fab-action__icon {
  width: 68rpx;
  height: 68rpx;
  box-sizing: border-box;
  border-radius: 50%;
  background-color: #fff;
}
</style>
