<template>
  <router-view />
  <Notify v-model:show="notify.show" :title="notify.title" :content="notify.content" />
  <Dialog class="g-dialog-message" v-model:show="message.show" theme="round-button" :confirm-button-text="$t('app.close')">
    <template #title>
      <div class="g-dialog-message__header">
        <h4>{{ currentMessage?.title }}</h4>
        <span>{{ formatDate(currentMessage?.createtime) }}</span>
      </div>
    </template>
    <div class="g-dialog-message__content" v-html="currentMessage?.content"></div>
    <div class="g-dialog-message__footer" v-if="message.dataList.length > 1">
      <span :class="{ disabled: message.index === 0 }" @click="changeMessage(-1)">{{ $t('app.pervious')  }}</span>
      <span :class="{ disabled: message.index === (message.dataList.length - 1) }" @click="changeMessage(1)">{{ $t('app.next')  }}</span>
    </div>
  </Dialog>
</template>

<script lang="ts" setup>
import { reactive, computed, onMounted, PropType, watch } from 'vue'
import { Locale, Dialog } from 'vant'
import { dialog } from '@/utils/vant'
import { formatDate } from '@/filters'
import { useLogin } from '@/business/login'
import { Language } from '@/constants/language'
import { useNavigation } from './router/navigation'
import { i18n, useNoticeStore, useLoginStore } from '@/stores'
import eventBus from '@/services/bus'
import plus from '@/utils/h5plus'
import Notify from '@mobile/components/base/notify/index.vue'
import enUS from 'vant/es/locale/lang/en-US'
import zhCN from 'vant/es/locale/lang/zh-CN'
import thTH from 'vant/es/locale/lang/th-TH'
import zhTW from 'vant/es/locale/lang/zh-TW'
import viVN from 'vant/es/locale/lang/vi-VN'

const props = defineProps({
  statusBarStyle: {
    type: String as PropType<'dark' | 'light'>,
    default: 'light'
  },
  // 是否弹出未读消息
  showUnread: {
    type: Boolean,
    default: true
  }
})

const { t, locale } = i18n.global

// 多语言列表
const languageMap = {
  [Language.Simplified]: zhCN,
  [Language.English]: enUS,
  [Language.Traditional]: zhTW,
  [Language.Thai]: thTH,
  [Language.Vietnamese]: viVN
}

if (locale in languageMap) {
  Locale.use(locale, languageMap[locale])
} else {
  Locale.use('en-US', enUS)
}

const { userLogout } = useLogin()
const { backHome } = useNavigation()

const loginStore = useLoginStore()
const noticeStore = useNoticeStore()

// 消息弹窗
const message = reactive({
  show: false,
  dataList: [] as Model.NoticeRsp[],
  index: 0
})

// 当前消息
const currentMessage = computed(() => message.dataList[message.index])

// 切换消息
const changeMessage = (value: number) => {
  const i = message.index + value
  if (i > -1 && i < message.dataList.length) {
    message.index = i
    noticeStore.updateNoticeReaded(currentMessage.value.autoid)
  }
}

// 浮动通知
const notify = reactive({
  show: false,
  title: '',
  content: ''
})

// 接收风控通知
eventBus.$on('RiskToWebNtf', (msg, type) => {
  const res = msg as { title: string, content: string }
  if (type === 1) {
    notify.title = res.title
    notify.content = res.content
    notify.show = true
  } else {
    dialog({
      title: res.title,
      message: res.content,
      confirmButtonText: t('operation.confirm')
    })
  }
})

// 接收用户登出通知
eventBus.$on('LogoutNotify', (msg) => {
  userLogout(() => {
    if (msg) {
      dialog({
        message: msg as string,
        confirmButtonText: t('operation.confirm')
      }).then(() => {
        backHome()
      })
    } else {
      backHome()
    }
  })
})

watch(() => noticeStore.isInitialized, () => {
  const readKey = 'read_' + loginStore.loginId
  const readValue = formatDate(new Date().toISOString(), 'YYYY-MM-DD')

  const localValue = localStorage.getItem(readKey)
  const showUnread = props.showUnread && localValue !== readValue // 未读消息一天内只会弹框一次

  // 过滤数据
  const filteredData = noticeStore.noticeList.filter((e) => (showUnread && !e.readed) || e.isforcedisplay)
  // 浅拷贝，防止数据引用
  message.dataList = filteredData.map((e) => ({ ...e }))

  if (message.dataList.length) {
    localStorage.setItem(readKey, readValue) // 记录用户已读日期
    message.index = 0
    message.show = true
    noticeStore.updateNoticeReaded(message.dataList[0].autoid)
  }
})

onMounted(() => plus.setStatusBarStyle(props.statusBarStyle))
</script>