App.vue 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <script lang="ts" setup>
  2. import { h, ref, computed, onMounted, onUnmounted } from 'vue'
  3. import { isDark } from '@/utils/is'
  4. import { useAppStore } from '@/store/modules/app'
  5. import { useDesign } from '@/hooks/web/useDesign'
  6. import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
  7. import routerSearch from '@/components/RouterSearch/index.vue'
  8. import { useWatermark } from '@/hooks/web/useWatermark'
  9. import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
  10. import { Warning } from '@element-plus/icons-vue'
  11. import { useWebSocket } from '@/utils/useWebSocket'
  12. import { amapReverseGeocode } from '@/utils/amapService'
  13. import { getAccessToken } from '@/utils/auth'
  14. import GlobalStatsNotification from '@/components/GlobalStatsNotification/index.vue'
  15. defineOptions({ name: 'APP' })
  16. // 使用响应式ref来存储token,并通过storage事件监听变化
  17. const getToken = ref(getAccessToken())
  18. const { getPrefixCls } = useDesign()
  19. const prefixCls = getPrefixCls('app')
  20. const appStore = useAppStore()
  21. const currentSize = computed(() => appStore.getCurrentSize)
  22. const greyMode = computed(() => appStore.getGreyMode)
  23. const { wsCache } = useCache()
  24. const { setWatermark } = useWatermark()
  25. // 监听sessionStorage的变化(包括同页面设置的情况)
  26. const handleStorageChange = (e: StorageEvent | null) => {
  27. if (!e || e.key === 'ACCESS_TOKEN') {
  28. getToken.value = getAccessToken()
  29. }
  30. }
  31. // 监听storage事件(跨标签页)
  32. window.addEventListener('storage', handleStorageChange)
  33. // 由于storage事件只在跨标签页时触发,同页面需要手动触发
  34. // 重写setItem方法以监听同页面的变化
  35. const originalSetItem = sessionStorage.setItem.bind(sessionStorage)
  36. sessionStorage.setItem = function(key: string, value: string) {
  37. originalSetItem(key, value)
  38. if (key === 'ACCESS_TOKEN') {
  39. // 手动触发更新
  40. getToken.value = getAccessToken()
  41. }
  42. }
  43. // 重写removeItem方法
  44. const originalRemoveItem = sessionStorage.removeItem.bind(sessionStorage)
  45. sessionStorage.removeItem = function(key: string) {
  46. originalRemoveItem(key)
  47. if (key === 'ACCESS_TOKEN') {
  48. getToken.value = getAccessToken()
  49. }
  50. }
  51. // 根据浏览器当前主题设置系统主题色
  52. const setDefaultTheme = () => {
  53. let isDarkTheme = wsCache.get(CACHE_KEY.IS_DARK)
  54. if (isDarkTheme === null) {
  55. isDarkTheme = isDark()
  56. }
  57. appStore.setIsDark(isDarkTheme)
  58. }
  59. setDefaultTheme()
  60. // 根据浏览器当前是否有设置水印
  61. const seMask = () => {
  62. if(appStore.getWaterMask){
  63. setWatermark(appStore.getWaterMask)
  64. }
  65. }
  66. seMask()
  67. // 全局统计信息弹窗
  68. const statsNotificationVisible = ref(false)
  69. const statsData = ref({
  70. successCount: 0,
  71. failureCount: 0,
  72. failureReasons: []
  73. })
  74. // 显示统计信息弹窗
  75. const showStatsNotification = (data: any) => {
  76. statsData.value = data
  77. statsNotificationVisible.value = true
  78. }
  79. // 关闭统计信息弹窗
  80. const closeStatsNotification = () => {
  81. statsNotificationVisible.value = false
  82. }
  83. // WebSocket 连接
  84. const wsUrl = import.meta.env.VITE_API_WSS_URL
  85. const { connect, disconnect, sendMessage } = useWebSocket({
  86. wsUrl,
  87. onSOSAlert: (alertData: any) => handleSOSAlert(alertData),
  88. onOrderAlert: (alertData: any) => showStatsNotification(alertData)
  89. })
  90. // 全局合同过期通知
  91. const contractNotificationVisible = ref(false)
  92. const contractNotificationData = ref<ContractNotificationData>({
  93. title: '合同过期提醒',
  94. message: '',
  95. contracts: []
  96. })
  97. // 显示合同过期通知
  98. const showContractNotification = (data: ContractNotificationData) => {
  99. contractNotificationData.value = {
  100. title: data.title || '合同过期提醒',
  101. message: data.message || '有合同已经过期,请进行处理',
  102. contracts: data.contracts || []
  103. }
  104. contractNotificationVisible.value = true
  105. }
  106. // 关闭合同过期通知
  107. const closeContractNotification = () => {
  108. contractNotificationVisible.value = false
  109. }
  110. // 处理查看合同详情
  111. const handleContractDetail = () => {
  112. closeContractNotification()
  113. // 跳转到合同管理页面
  114. window.location.href = '/elderly/contract'
  115. }
  116. // 将通知方法挂载到全局,供其他页面调用
  117. (window as any).$showContractNotification = showContractNotification;
  118. const handleSOSAlert = async (alertData: any) => {
  119. const alert = alertData.data || alertData
  120. sendMessage({
  121. type: 'SOS_ACK',
  122. alertId: alertData.timestamp,
  123. timestamp: Date.now()
  124. })
  125. // 获取地址信息
  126. let addressInfo = '位置信息获取中...'
  127. if (alert.longitude && alert.latitude) {
  128. addressInfo = await amapReverseGeocode(alert.longitude, alert.latitude)
  129. }
  130. ElNotification({
  131. title: '🚨🚨 SOS紧急预警 🚨🚨',
  132. customClass: 'my-warning-notification',
  133. message: h('div', {
  134. style: { color: '#fff' },
  135. innerHTML: `
  136. <div>院区名称: ${alert.organizationName || '未知'}</div>
  137. <div>长者姓名: ${alert.elderName || '未知'}</div>
  138. <div>长者房间: ${alert.roomName || '未知'}</div>
  139. <div>设备类型: ${alert.deviceType || '未知'}</div>
  140. <div>设备电量: ${alert.batteryLevel || '0%'}</div>
  141. <div>位置信息: ${addressInfo || ''}</div>
  142. <div>时间: ${new Date(alertData.timestamp).toLocaleString()}</div>
  143. `
  144. }),
  145. type: 'warning',
  146. duration: 10000
  147. })
  148. }
  149. onMounted(() => {
  150. // 检查今天是否已经执行过刷新
  151. const checkIfRefreshedToday = () => {
  152. const today = new Date().toDateString()
  153. const lastRefreshDate = localStorage.getItem('lastRefreshDate')
  154. return lastRefreshDate === today
  155. }
  156. // 标记今天已刷新
  157. const markRefreshedToday = () => {
  158. const today = new Date().toDateString()
  159. localStorage.setItem('lastRefreshDate', today)
  160. }
  161. // 计算到下一个15:52的时间间隔
  162. const calculateNextExecutionTime = () => {
  163. const now = new Date()
  164. const nextExecution = new Date()
  165. nextExecution.setHours(4, 0, 0, 0) //
  166. console.log('当前时间:', now.toLocaleString())
  167. console.log('初始执行时间:', nextExecution.toLocaleString())
  168. // 如果当前时间已经超过今天的15:52,则设置为明天的15:52
  169. if (now.getHours() > 4 || (now.getHours() === 4 && now.getMinutes() > 0) || (now.getHours() === 4 && now.getMinutes() === 0 && now.getSeconds() > 0)) {
  170. nextExecution.setDate(nextExecution.getDate() + 1)
  171. console.log('当前时间已过04:00,设置为明天执行')
  172. } else {
  173. console.log('设置为今天执行')
  174. }
  175. const timeDiff = nextExecution.getTime() - now.getTime()
  176. console.log('时间差(毫秒):', timeDiff)
  177. return timeDiff
  178. }
  179. // 设置定时器
  180. const scheduleRefresh = () => {
  181. const timeUntilNextExecution = calculateNextExecutionTime()
  182. const nextExecution = new Date(Date.now() + timeUntilNextExecution)
  183. console.log('定时器已设置,将在以下时间执行刷新:', nextExecution.toLocaleString())
  184. console.log('距离执行还有毫秒数:', timeUntilNextExecution)
  185. setTimeout(() => {
  186. console.log('定时任务触发,准备刷新页面')
  187. // 标记今天已刷新
  188. markRefreshedToday()
  189. // 执行页面刷新
  190. location.reload()
  191. // 递归调用,设置下一次执行
  192. scheduleRefresh()
  193. }, timeUntilNextExecution)
  194. }
  195. // 检查日期变化并重新设置定时器
  196. const checkDateChangeAndReschedule = () => {
  197. const now = new Date()
  198. console.log('当前时间:', now.toLocaleString())
  199. console.log('今天是否已刷新:', checkIfRefreshedToday())
  200. console.log('localStorage中的日期:', localStorage.getItem('lastRefreshDate'))
  201. // 如果localStorage中没有记录或者记录的日期不是今天,则需要重新设置定时器
  202. if (!checkIfRefreshedToday()) {
  203. console.log('设置新的定时器')
  204. scheduleRefresh()
  205. } else {
  206. console.log('今天已刷新,不设置定时器')
  207. }
  208. }
  209. // 初始检查和设置
  210. checkDateChangeAndReschedule()
  211. // 每小时检查一次日期变化,确保即使页面一直打开也能在第二天重新设置定时器
  212. setInterval(checkDateChangeAndReschedule, 120 * 60 * 1000) // 每小时检查一次
  213. })
  214. // 监听token变化
  215. // watch(
  216. // getToken,
  217. // (val) => {
  218. // console.log('getToken', val)
  219. // if(val){
  220. // setTimeout(() => {
  221. // console.log('开始连接WebSocket')
  222. // connect()
  223. // }, 1000)
  224. // }else {
  225. // console.log('断开WebSocket')
  226. // disconnect()
  227. // }
  228. // },
  229. // { immediate: true }
  230. // )
  231. onUnmounted(() => {
  232. // disconnect()
  233. // 清理storage事件监听器
  234. window.removeEventListener('storage', handleStorageChange)
  235. })
  236. </script>
  237. <template>
  238. <ConfigGlobal :size="currentSize">
  239. <RouterView :class="greyMode ? `${prefixCls}-grey-mode` : ''" />
  240. <routerSearch />
  241. <GlobalStatsNotification
  242. :visible="statsNotificationVisible"
  243. :stats="statsData"
  244. @close="closeStatsNotification"
  245. />
  246. <!-- 合同过期通知弹窗 -->
  247. <GlobalWindowConcat
  248. :visible="contractNotificationVisible"
  249. :data="contractNotificationData"
  250. @close="closeContractNotification"
  251. @detail="handleContractDetail"
  252. />
  253. </ConfigGlobal>
  254. </template>
  255. <style lang="scss">
  256. $prefix-cls: #{$namespace}-app;
  257. .size {
  258. width: 100%;
  259. height: 100%;
  260. }
  261. html{
  262. font-size: 14px;
  263. }
  264. html,
  265. body {
  266. @extend .size;
  267. padding: 0 !important;
  268. margin: 0;
  269. overflow: hidden;
  270. #app {
  271. @extend .size;
  272. }
  273. }
  274. .#{$prefix-cls}-grey-mode {
  275. filter: grayscale(100%);
  276. }
  277. </style>