<script lang="ts" setup>
import { isDark } from '@/utils/is'
import { useAppStore } from '@/store/modules/app'
import { useDesign } from '@/hooks/web/useDesign'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import routerSearch from '@/components/RouterSearch/index.vue'
import { useWatermark } from '@/hooks/web/useWatermark'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { useWebSocket } from '@/utils/useWebSocket'
import { amapReverseGeocode } from '@/utils/amapService'
import { getAccessToken } from '@/utils/auth'
import GlobalStatsNotification from '@/components/GlobalStatsNotification/index.vue'

defineOptions({ name: 'APP' })

// 使用响应式ref来存储token，并通过storage事件监听变化
const getToken = ref(getAccessToken())
const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('app')
const appStore = useAppStore()
const currentSize = computed(() => appStore.getCurrentSize)
const greyMode = computed(() => appStore.getGreyMode)
const { wsCache } = useCache()
const { setWatermark } = useWatermark()

// 监听sessionStorage的变化（包括同页面设置的情况）
const handleStorageChange = (e: StorageEvent | null) => {
  if (!e || e.key === 'ACCESS_TOKEN') {
    getToken.value = getAccessToken()
  }
}

// 监听storage事件（跨标签页）
window.addEventListener('storage', handleStorageChange)

// 由于storage事件只在跨标签页时触发，同页面需要手动触发
// 重写setItem方法以监听同页面的变化
const originalSetItem = sessionStorage.setItem.bind(sessionStorage)
sessionStorage.setItem = function(key: string, value: string) {
  originalSetItem(key, value)
  if (key === 'ACCESS_TOKEN') {
    // 手动触发更新
    getToken.value = getAccessToken()
  }
}

// 重写removeItem方法
const originalRemoveItem = sessionStorage.removeItem.bind(sessionStorage)
sessionStorage.removeItem = function(key: string) {
  originalRemoveItem(key)
  if (key === 'ACCESS_TOKEN') {
    getToken.value = getAccessToken()
  }
}
// 根据浏览器当前主题设置系统主题色
const setDefaultTheme = () => {
  let isDarkTheme = wsCache.get(CACHE_KEY.IS_DARK)
  if (isDarkTheme === null) {
    isDarkTheme = isDark()
  }
  appStore.setIsDark(isDarkTheme)
}
setDefaultTheme()

// 根据浏览器当前是否有设置水印
const seMask = () => {
  if(appStore.getWaterMask){
    setWatermark(appStore.getWaterMask)
  }
}
seMask()


// 全局统计信息弹窗
const statsNotificationVisible = ref(false)
const statsData = ref({
  successCount: 0,
  failureCount: 0,
  failureReasons: []
})

// 显示统计信息弹窗
const showStatsNotification = (data: any) => {
  statsData.value = data
  statsNotificationVisible.value = true
}

// 关闭统计信息弹窗
const closeStatsNotification = () => {
  statsNotificationVisible.value = false
}

// WebSocket 连接
const wsUrl = import.meta.env.VITE_API_WSS_URL
const { connect, disconnect, sendMessage } = useWebSocket({
  wsUrl,
  onSOSAlert: (alertData: any) => handleSOSAlert(alertData),
  onOrderAlert: (alertData: any) => showStatsNotification(alertData)
})



const handleSOSAlert = async (alertData: any) => {
  const alert = alertData.data || alertData
  sendMessage({
    type: 'SOS_ACK',
    alertId: alertData.timestamp,
    timestamp: Date.now()
  })

  // 获取地址信息
  let addressInfo = '位置信息获取中...'
  if (alert.longitude && alert.latitude) {
    addressInfo = await amapReverseGeocode(alert.longitude, alert.latitude)
  }

  ElNotification({
    title: '🚨🚨 SOS紧急预警 🚨🚨',
    customClass: 'my-warning-notification',
    message: h('div', {
      style: { color: '#fff' },
      innerHTML: `
        <div>院区名称: ${alert.organizationName || '未知'}</div>
        <div>长者姓名: ${alert.elderName || '未知'}</div>
        <div>长者房间: ${alert.roomName || '未知'}</div>
        <div>设备类型: ${alert.deviceType || '未知'}</div>
        <div>设备电量: ${alert.batteryLevel || '0%'}</div>
        <div>位置信息: ${addressInfo || ''}</div>
        <div>时间: ${new Date(alertData.timestamp).toLocaleString()}</div>
      `
    }),
    type: 'warning',
    duration: 10000
  })
}

onMounted(() => {
  // 检查今天是否已经执行过刷新
  const checkIfRefreshedToday = () => {
    const today = new Date().toDateString()
    const lastRefreshDate = localStorage.getItem('lastRefreshDate')
    return lastRefreshDate === today
  }

  // 标记今天已刷新
  const markRefreshedToday = () => {
    const today = new Date().toDateString()
    localStorage.setItem('lastRefreshDate', today)
  }

  // 计算到下一个15:52的时间间隔
  const calculateNextExecutionTime = () => {
    const now = new Date()
    const nextExecution = new Date()
    nextExecution.setHours(4, 0, 0, 0) //

    console.log('当前时间:', now.toLocaleString())
    console.log('初始执行时间:', nextExecution.toLocaleString())

    // 如果当前时间已经超过今天的15:52，则设置为明天的15:52
    if (now.getHours() > 4 || (now.getHours() === 4 && now.getMinutes() > 0) || (now.getHours() === 4 && now.getMinutes() === 0 && now.getSeconds() > 0)) {
      nextExecution.setDate(nextExecution.getDate() + 1)
      console.log('当前时间已过04:00，设置为明天执行')
    } else {
      console.log('设置为今天执行')
    }

    const timeDiff = nextExecution.getTime() - now.getTime()
    console.log('时间差(毫秒):', timeDiff)
    return timeDiff
  }

  // 设置定时器
  const scheduleRefresh = () => {
    const timeUntilNextExecution = calculateNextExecutionTime()
    const nextExecution = new Date(Date.now() + timeUntilNextExecution)
    console.log('定时器已设置，将在以下时间执行刷新:', nextExecution.toLocaleString())
    console.log('距离执行还有毫秒数:', timeUntilNextExecution)

    setTimeout(() => {
      console.log('定时任务触发，准备刷新页面')
      // 标记今天已刷新
      markRefreshedToday()
      // 执行页面刷新
      location.reload()
      // 递归调用，设置下一次执行
      scheduleRefresh()
    }, timeUntilNextExecution)
  }

  // 检查日期变化并重新设置定时器
  const checkDateChangeAndReschedule = () => {
    const now = new Date()
    console.log('当前时间:', now.toLocaleString())
    console.log('今天是否已刷新:', checkIfRefreshedToday())
    console.log('localStorage中的日期:', localStorage.getItem('lastRefreshDate'))

    // 如果localStorage中没有记录或者记录的日期不是今天，则需要重新设置定时器
    if (!checkIfRefreshedToday()) {
      console.log('设置新的定时器')
      scheduleRefresh()
    } else {
      console.log('今天已刷新，不设置定时器')
    }
  }

  // 初始检查和设置
  checkDateChangeAndReschedule()

  // 每小时检查一次日期变化，确保即使页面一直打开也能在第二天重新设置定时器
  setInterval(checkDateChangeAndReschedule, 120 * 60 * 1000) // 每小时检查一次
})
// 监听token变化
// watch(
//   getToken,
//   (val) => {
//     console.log('getToken', val)
//     if(val){
//       setTimeout(() => {
//         console.log('开始连接WebSocket')
//         connect()
//       }, 1000)
//     }else {
//       console.log('断开WebSocket')
//       disconnect()
//     }
//   },
//   { immediate: true }
// )

onUnmounted(() => {
  // disconnect()
  // 清理storage事件监听器
  window.removeEventListener('storage', handleStorageChange)
})



</script>


<template>
  <ConfigGlobal :size="currentSize">
    <RouterView :class="greyMode ? `${prefixCls}-grey-mode` : ''" />
    <routerSearch />
    <GlobalStatsNotification
      :visible="statsNotificationVisible"
      :stats="statsData"
      @close="closeStatsNotification"
    />
  </ConfigGlobal>
</template>



<style lang="scss">
$prefix-cls: #{$namespace}-app;

.size {
  width: 100%;
  height: 100%;
}

html{
  font-size: 14px;
}
html,
body {
  @extend .size;

  padding: 0 !important;
  margin: 0;
  overflow: hidden;

  #app {
    @extend .size;
  }
}

.#{$prefix-cls}-grey-mode {
  filter: grayscale(100%);
}
</style>
