<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="关闭"
    @closed="onClosed">
    <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="messageList.length > 1">
      <span :class="{ disabled: message.index === 0 }" @click="changeMessage(-1)">上一条</span>
      <span :class="{ disabled: message.index === (messageList.length - 1) }" @click="changeMessage(1)">下一条</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 { userLogout } = useLogin()
const { backHome } = useNavigation()

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

// 消息弹窗
const message = reactive({
  show: false,
  index: 0
})

// 获取用户阅读状态
const getUserReadStatus = () => ({
  key: 'read_' + loginStore.loginId,
  value: formatDate(new Date().toISOString(), 'YYYY-MM-DD')
})

// 消息列表
const messageList = computed(() => {
  const { key, value } = getUserReadStatus()
  const localValue = localStorage.getItem(key)
  const showUnread = props.showUnread && localValue !== value // 未读消息一天内只会弹框一次

  return noticeStore.noticeList.filter((e) => (showUnread && !e.readed) || e.isforcedisplay)
})

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

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

// 关闭消息弹窗
const onClosed = () => {
  messageList.value.forEach((e) => noticeStore.updateNoticeReaded(e.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: '确定'
    })
  }
})

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

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

// 当前语言
const language = i18n.global.locale

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

watch(() => noticeStore.isInitialized, () => {
  const [firstMessage] = messageList.value

  if (firstMessage) {
    const { key, value } = getUserReadStatus()
    localStorage.setItem(key, value) // 记录用户已读状态
    message.index = 0
    message.show = true
  }
})

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