<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '%helpCenter.detail.title%',
    navigationBarBackgroundColor: '#fff',
  },
}
</route>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'

import { qaInfo } from '@/api/qa'
import i18n from '@/locale/index'

defineOptions({
  name: 'HelpCenterDetail',
})

interface QaItem {
  id: number
  bnTitle?: string
  enTitle?: string
  bnContent?: string
  enContent?: string
  groupId: number
}

const locale = computed(() => i18n.global.locale)
const shouldUseEn = computed(() => locale.value === 'en' || locale.value === 'zh-Hans')

const detail = ref<QaItem | null>(null)
const contentHtml = ref<string>('')

function formatTextToHtml(text: string) {
  if (!text)
    return ''
  return text.replace(/\n/g, '<br>')
}

function getQaTitle(item: QaItem | null) {
  if (!item)
    return ''
  return shouldUseEn.value ? (item.enTitle || item.bnTitle || '') : (item.bnTitle || item.enTitle || '')
}

async function loadDetail(id: number) {
  const res = await qaInfo(id)
  if (res.code === '200') {
    detail.value = res.data as QaItem
    const content = shouldUseEn.value
      ? (detail.value.enContent || detail.value.bnContent || '')
      : (detail.value.bnContent || detail.value.enContent || '')
    contentHtml.value = formatTextToHtml(content)
  }
}

watch(locale, () => {
  if (!detail.value)
    return
  const content = shouldUseEn.value
    ? (detail.value.enContent || detail.value.bnContent || '')
    : (detail.value.bnContent || detail.value.enContent || '')
  contentHtml.value = formatTextToHtml(content)
})

onLoad(async (options: any) => {
  const id = Number(options?.id)
  if (!Number.isFinite(id) || id <= 0)
    return
  await loadDetail(id)
})
</script>

<template>
  <view class="rounded-12rpx bg-white px-22rpx py-40rpx">
    <view class="mb-18rpx text-30rpx font-bold">
      {{ getQaTitle(detail) }}
    </view>
    <rich-text :nodes="contentHtml" />
  </view>
</template>

<style lang="scss" scoped>
page {
  background-color: #fff;
}
</style>
