1
wwl
5 小时以前 0000e935d6c7f74cb6682aea1bbf24d8deade390
1
4个文件已修改
1个文件已添加
537 ■■■■ 已修改文件
src/assets/styles/index.scss 38 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main copy.js 142 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main.js 55 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/utils/websocket.js 104 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/views/index.vue 198 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/assets/styles/index.scss
@@ -1,3 +1,4 @@
/* src/assets/styles/index.scss */
@import './variables.scss';
@import './mixin.scss';
@import './transition.scss';
@@ -119,7 +120,7 @@
  }
}
//main-container全局样式
// main-container全局样式
.app-container {
  padding: 20px;
  width: 100%;
@@ -135,7 +136,7 @@
}
.text-center {
  text-align: center
  text-align: center;
}
.sub-navbar {
@@ -182,7 +183,7 @@
  }
}
//refine vue-multiselect plugin
// refine vue-multiselect plugin
.multiselect {
  line-height: 16px;
}
@@ -190,3 +191,34 @@
.multiselect--active {
  z-index: 1000 !important;
}
/* 自定义 Element UI 通知样式 */
.el-notification {
  min-width: 300px !important;
  background-color: #f0f9eb !important;
  border-color: #e1f3d8 !important;
  color: #67c23a !important;
  font-size: 16px !important;
  padding: 15px 20px !important;
  z-index: 10000 !important; /* 提高 z-index,超过 Layout 的 drawer-bg */
  position: fixed !important;
  top: 50px !important;
  right: 20px !important;
}
.el-notification.global-notification {
  z-index: 10000 !important; /* 调试用,确保不被遮挡 */
}
.el-notification__title {
  font-weight: bold !important;
}
.el-notification__content {
  font-size: 14px !important;
  color: #333 !important;
}
.el-notification__closeBtn {
  color: #999 !important;
}
src/main copy.js
New file
@@ -0,0 +1,142 @@
// src/main.js
import Vue from "vue";
import Cookies from "js-cookie";
import "babel-polyfill";
import Element from "element-ui";
import "./assets/styles/element-variables.scss";
import "@/assets/styles/index.scss";
import "@/assets/styles/ruoyi.scss";
import App from "./App";
import store from "./store";
import router from "./router";
import directive from "./directive";
import plugins from "./plugins";
import { download } from "@/utils/request";
import Print from "vue-print-nb";
import JsonExcel from "vue-json-excel";
import "./assets/icons";
import "./permission";
import { getDicts } from "@/api/system/dict/data";
import { getConfigKey } from "@/api/system/config";
import {
  parseTime,
  resetForm,
  addDateRange,
  selectDictLabel,
  selectDictLabels,
  handleTree,
} from "@/utils/ruoyi";
import Pagination from "@/components/Pagination";
import Editor from "@/components/Editor";
import FileUpload from "@/components/FileUpload";
import ImageUpload from "@/components/ImageUpload";
import ImagePreview from "@/components/ImagePreview";
import DictTag from "@/components/DictTag";
import VueMeta from "vue-meta";
import DictData from "@/components/DictData";
import * as echarts from "echarts";
import VueBarcode from "vue-barcode";
import { initWebSocket, closeWebSocket } from "@/utils/websocket";
Vue.component("downloadExcel", JsonExcel);
Vue.component("barcode", VueBarcode);
Vue.component("DictTag", DictTag);
Vue.component("Pagination", Pagination);
Vue.component("Editor", Editor);
Vue.component("FileUpload", FileUpload);
Vue.component("ImageUpload", ImageUpload);
Vue.component("ImagePreview", ImagePreview);
Vue.prototype.getDicts = getDicts;
Vue.prototype.getConfigKey = getConfigKey;
Vue.prototype.parseTime = parseTime;
Vue.prototype.resetForm = resetForm;
Vue.prototype.addDateRange = addDateRange;
Vue.prototype.selectDictLabel = selectDictLabel;
Vue.prototype.selectDictLabels = selectDictLabels;
Vue.prototype.download = download;
Vue.prototype.handleTree = handleTree;
Vue.prototype.$echarts = echarts;
Vue.prototype.$showNotification = function (type, title, message, onClick) {
  console.log('触发通知:', { type, title, message });
  Vue.prototype.$notify({
    title,
    message,
    type,
    duration: 5000,
    position: 'top-right',
    offset: 50,
    onClick,
    customClass: 'global-notification',
    appendTo: document.body
  });
};
// 监听路由变化
router.afterEach(() => {
  console.log('路由切换完成,当前路径:', router.currentRoute.path);
});
const app = new Vue({
  el: "#app",
  router,
  store,
  render: (h) => h(App),
  mounted() {
    const token = store.state.user.token || Cookies.get('token') || '';
    if (token) {
      console.log('Token:', token);
      initWebSocket(token, (type, data) => {
        if (type === 'error') {
          Vue.prototype.$showNotification('error', '错误', data);
          return;
        }
        try {
          const message = JSON.parse(data);
          console.log('WebSocket 解析后消息:', message);
          if (message.noticeId && message.noticeTitle) {
            const noticeTypeLabel = message.noticeType === '1' ? '通知' : '公告';
            const contentPreview = message.noticeContent
              ? message.noticeContent.replace(/<[^>]+>/g, '').substring(0, 20) + '...'
              : '无内容';
            Vue.prototype.$showNotification(
              'success',
              `新${noticeTypeLabel}`,
              `${message.noticeTitle} - ${contentPreview}`,
              () => {
                router.push({
                  path: '/redirect/notice',
                  query: { noticeId: message.noticeId }
                });
              }
            );
          } else {
            console.log('未知消息类型:', message);
            Vue.prototype.$showNotification('info', '消息', '收到未知格式的消息');
          }
        } catch (error) {
          console.error('消息解析失败:', error, '原始数据:', data);
          Vue.prototype.$showNotification('info', '消息', `服务器回应字符串: ${data}`);
        }
      });
    } else {
      console.error('未找到 token,无法初始化 WebSocket');
    }
  },
  beforeDestroy() {
    closeWebSocket(); // 清理 WebSocket
  }
});
Vue.use(directive);
Vue.use(plugins);
Vue.use(VueMeta);
Vue.use(Print);
Vue.use(Element, {
  size: Cookies.get("size") || "medium",
});
DictData.install();
Vue.config.productionTip = false;
src/main.js
@@ -1,20 +1,21 @@
// src/main.js
import Vue from "vue";
import Cookies from "js-cookie";
import "babel-polyfill";
import Element from "element-ui";
import "./assets/styles/element-variables.scss";
import "@/assets/styles/index.scss"; // global css
import "@/assets/styles/ruoyi.scss"; // ruoyi css
import "@/assets/styles/index.scss";
import "@/assets/styles/ruoyi.scss";
import App from "./App";
import store from "./store";
import router from "./router";
import directive from "./directive"; // directive
import plugins from "./plugins"; // plugins
import directive from "./directive";
import plugins from "./plugins";
import { download } from "@/utils/request";
import Print from "vue-print-nb";
import JsonExcel from "vue-json-excel";
import "./assets/icons"; // icon
import "./permission"; // permission control
import "./assets/icons";
import "./permission";
import { getDicts } from "@/api/system/dict/data";
import { getConfigKey } from "@/api/system/config";
import {
@@ -26,7 +27,6 @@
  handleTree,
} from "@/utils/ruoyi";
import Pagination from "@/components/Pagination";
import RightToolbar from "@/components/RightToolbar";
import Editor from "@/components/Editor";
import FileUpload from "@/components/FileUpload";
import ImageUpload from "@/components/ImageUpload";
@@ -41,13 +41,11 @@
Vue.component("barcode", VueBarcode);
Vue.component("DictTag", DictTag);
Vue.component("Pagination", Pagination);
Vue.component("RightToolbar", RightToolbar);
Vue.component("Editor", Editor);
Vue.component("FileUpload", FileUpload);
Vue.component("ImageUpload", ImageUpload);
Vue.component("ImagePreview", ImagePreview);
// 全局方法挂载
Vue.prototype.getDicts = getDicts;
Vue.prototype.getConfigKey = getConfigKey;
Vue.prototype.parseTime = parseTime;
@@ -59,20 +57,41 @@
Vue.prototype.handleTree = handleTree;
Vue.prototype.$echarts = echarts;
// 保留 $showNotification,支持手动触发通知
Vue.prototype.$showNotification = function (type, title, message, onClick) {
  console.log('触发通知:', { type, title, message }, new Date().toLocaleString());
  Vue.prototype.$notify({
    title,
    message,
    type,
    duration: 5000,
    position: 'top-right',
    offset: 50,
    onClick,
    customClass: 'global-notification',
    appendTo: document.body
  });
};
// 监听路由变化
router.afterEach(() => {
  console.log('路由切换完成,当前路径:', router.currentRoute.path);
});
const app = new Vue({
  el: "#app",
  router,
  store,
  render: (h) => h(App)
});
Vue.use(directive);
Vue.use(plugins);
Vue.use(VueMeta);
Vue.use(Print);
Vue.use(Element, {
  size: Cookies.get("size") || "medium", // set element-ui default size
  size: Cookies.get("size") || "medium",
});
DictData.install();
Vue.config.productionTip = false;
new Vue({
  el: "#app",
  router,
  store,
  render: (h) => h(App),
});
Vue.config.productionTip = false;
src/utils/websocket.js
@@ -1,80 +1,78 @@
// src/utils/websocket.js
let socket = null;
let ws = null;
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;
const reconnectInterval = 5000;
let messageCallback = null;
const reconnectInterval = 5000; // 5秒重连间隔
const pingInterval = 5000; // 5秒发送ping
const initWebSocket = (token, callback) => {
  if (socket && socket.readyState === WebSocket.OPEN) {
    console.log('WebSocket 已连接,无需重复初始化');
    return;
  }
export function initWebSocket(token, onMessage) {
  if (!token) {
    console.error('未提供 token,无法建立 WebSocket 连接');
    callback('error', '未找到 token,无法建立 WebSocket 连接');
    console.error('WebSocket 初始化失败:缺少 token');
    return;
  }
  const wsUrl = `ws://192.168.1.2:5011/ws?token=${encodeURIComponent(token)}`;
  console.log('尝试连接 WebSocket:', wsUrl);
  const wsUrl = `ws://192.168.1.2:5011/ws?token=${token}`;
  ws = new WebSocket(wsUrl);
  try {
    socket = new WebSocket(wsUrl);
  } catch (error) {
    console.error('WebSocket 初始化失败:', error);
    callback('error', '无法初始化 WebSocket 连接');
    return;
  }
  messageCallback = callback;
  socket.onopen = () => {
  ws.onopen = () => {
    console.log('WebSocket 连接成功');
    reconnectAttempts = 0;
    // 启动心跳机制
    const pingTimer = setInterval(() => {
      if (ws.readyState === WebSocket.OPEN) {
        console.log('发送 ping 消息');
        ws.send('ping');
      } else {
        console.warn('WebSocket 未连接,停止 ping');
        clearInterval(pingTimer);
      }
    }, pingInterval);
  };
  socket.onmessage = (event) => {
    console.log('WebSocket 收到原始消息:', event.data);
    if (messageCallback) {
      messageCallback('message', event.data);
  ws.onmessage = (event) => {
    const data = event.data;
    console.log('WebSocket 收到原始消息:', data);
    if (data === 'pong') {
      console.log('收到 pong 响应,连接活跃');
      return;
    }
    onMessage('message', data);
  };
  socket.onerror = (error) => {
  ws.onerror = (error) => {
    console.error('WebSocket 错误:', error);
    if (messageCallback) {
      messageCallback('error', 'WebSocket 连接错误');
    }
    onMessage('error', 'WebSocket 连接错误');
  };
  socket.onclose = (event) => {
    console.log('WebSocket 连接关闭,代码:', event.code, '原因:', event.reason);
  ws.onclose = () => {
    console.warn('WebSocket 连接关闭');
    if (reconnectAttempts < maxReconnectAttempts) {
      reconnectAttempts++;
      console.log(`尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})...`);
      setTimeout(() => {
        console.log(`尝试重连 (${reconnectAttempts + 1}/${maxReconnectAttempts})`);
        reconnectAttempts++;
        initWebSocket(token, callback);
        initWebSocket(token, onMessage);
      }, reconnectInterval);
    } else {
      if (messageCallback) {
        messageCallback('error', 'WebSocket 重连失败,请检查网络或服务器');
      }
      console.error('达到最大重连次数,停止重连');
      onMessage('error', 'WebSocket 连接失败,已达最大重连次数');
    }
  };
};
const closeWebSocket = () => {
  if (socket) {
    socket.close(1000, '浏览器关闭,正常断开');
    socket = null;
    console.log('WebSocket 连接已关闭');
  // 清理 WebSocket
  window.addEventListener('beforeunload', () => {
    if (ws) {
      ws.close();
      ws = null;
      console.log('WebSocket 已清理');
    }
  });
}
export function closeWebSocket() {
  if (ws) {
    ws.close();
    ws = null;
    console.log('WebSocket 已关闭');
  }
};
window.addEventListener('beforeunload', () => {
  closeWebSocket();
});
export { initWebSocket, closeWebSocket };
}
src/views/index.vue
@@ -1,5 +1,28 @@
<template>
  <div class="centre">
    <!-- 今日通知 -->
    <div style="display: flex; justify-content: center; align-items: center;">
      <h4>今日通知</h4>
    </div>
    <div class="notice-area">
      <el-carousel :interval="2000" direction="vertical" :autoplay="true" :loop="true" height="120px"
        v-if="groupedNoticeList.length > 0" class="carousel">
        <el-carousel-item v-for="(group, index) in groupedNoticeList" :key="index">
          <div class="notice-group">
            <div class="notice-item" v-for="notice in group" :key="notice.noticeId"
              @click="goToNotice(notice.noticeId)">
              <el-tag size="small" :type="notice.noticeType === '1' ? 'info' : 'warning'">
                {{ notice.noticeType === '1' ? '通知' : '公告' }}
              </el-tag>
              <span class="notice-title">{{ notice.noticeTitle || '无标题' }}</span>
              <span class="notice-time">{{ parseTime(notice.createTime, '{y}-{m}-{d}') || '无时间' }}</span>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
      <div v-else class="no-notice">暂无通知</div>
    </div>
    <!-- 今日统计 -->
    <div style="display: flex; justify-content: center; align-items: center;">
      <h4>今日统计</h4>
@@ -56,7 +79,6 @@
<script>
import { getCustomer, getOrder, getReportToday, getTobeToday, getPieChart, getChart } from "@/api/home";
import { noticeToday } from "@/api/system/notice";
import { initWebSocket } from "@/utils/websocket";
const echarts = require('echarts/lib/echarts');
require('echarts/lib/component/title');
require('echarts/lib/component/tooltip');
@@ -79,18 +101,27 @@
      teamYYNum: [],
      PieChart: [],
      PieChart2: [],
      noticeList: [],
      groupedNoticeList: [], // 分组后的通知列表
      loading: false
    };
  },
  created() {
    this.getList();
    this.initWebSocket();
  },
  watch: {
    $route(to, from) {
      window.location.reload();
    },
    noticeList: {
      handler(newList) {
        // 将通知按每组三条分组
        this.groupedNoticeList = this.chunkArray(newList, 3);
        console.log('groupedNoticeList:', this.groupedNoticeList); // 调试
      },
      deep: true
    }
  },
@@ -101,91 +132,49 @@
        query: { noticeId }
      });
    },
    // 初始化 WebSocket 连接
    initWebSocket() {
      const token = this.$store.state.user.token || '';
      initWebSocket(token, (type, data) => {
        if (type === 'error') {
          this.$notify.error({
            title: '错误',
            message: data,
            duration: 5000,
            position: 'top-right'
          });
          return;
        }
        try {
          const message = JSON.parse(data);
          console.log('WebSocket 解析后消息:', message);
          if (message.noticeId && message.noticeTitle) {
            const noticeTypeLabel = message.noticeType === '1' ? '通知' : '公告';
            this.$notify({
              title: `新${noticeTypeLabel}`,
              message: message.noticeTitle || '无标题',
              type: 'success',
              duration: 5000, // 悬停 5 秒
              position: 'top-right',
              offset: 50,
              onClick: () => {
                this.goToNotice(message.noticeId);
              }
            });
          } else {
            console.log('未知消息类型:', message);
          }
        } catch (error) {
          console.error('消息解析失败:', error, '原始数据:', data);
          this.$notify.info({
            title: '消息',
            message: `服务器回应字符串: ${data}`,
            duration: 5000,
            position: 'top-right',
            offset: 50
          });
        }
      });
    },
    getList() {
      this.loading = true;
      // 查询所有公告(仅用于初始化数据,可根据需要保留或移除)
      // 查询所有公告
      noticeToday().then(response => {
        console.log('Notice API response:', response);
        this.noticeList = response.rows || response.data || [];
        console.log('noticeList:', this.noticeList);
        this.loading = false;
        this.$nextTick(() => {
          console.log('Carousel updated');
        });
      }).catch(error => {
        console.error('Notice API error:', error);
        this.$notify.error({
          title: '错误',
          message: `获取通知失败:${error.message}`,
          duration: 5000,
          position: 'top-right'
        });
        this.$message.error("获取通知失败:" + error.message);
        this.loading = false;
      });
      // 查询今日登记
      getCustomer().then(response => {
        this.Customer = response.data || response;
        this.loading = false;
      });
      // 查询今日已检
      getOrder().then(response => {
        this.Order = response.data || response;
        this.loading = false;
      });
      // 查询今日报告
      getReportToday().then(response => {
        this.ReportToday = response.data || response;
        this.loading = false;
      });
      // 查询今日待检
      getTobeToday().then(response => {
        this.TobeToday = response.data || response;
        this.loading = false;
      });
      // 折线图
      getChart().then(response => {
        response.data.forEach(item => {
          this.LineChart.push(item.date);
@@ -222,6 +211,7 @@
        this.loading = false;
      });
      // 饼状图
      getPieChart().then(response => {
        if (response.data) {
          if (response.data.tjdj == 0 || !response.data.tjdj?.length) {
@@ -291,6 +281,23 @@
      });
    },
    // 数组分组方法
    chunkArray(array, size) {
      if (!array || array.length === 0) return [];
      const result = [];
      for (let i = 0; i < array.length; i += size) {
        result.push(array.slice(i, i + size));
      }
      // 确保循环滚动平滑,若不足 size 条,补齐
      if (array.length % size !== 0 && array.length > size) {
        const lastGroup = result[result.length - 1];
        while (lastGroup.length < size) {
          lastGroup.push(array[lastGroup.length % array.length]);
        }
      }
      return result;
    },
    parseTime(time, cFormat) {
      if (!time) return '';
      try {
@@ -320,6 +327,62 @@
  margin: 15px;
  background-color: #f3f3f3;
  padding: 10px;
}
.notice-area {
  width: 100%;
  min-height: 120px;
  /* 调整为三条通知高度 */
  background-color: #fff;
  margin: 10px 0;
  padding: 0 20px;
}
.carousel {
  width: 100% !important;
}
.notice-group {
  display: flex;
  flex-direction: column;
  height: 120px;
  /* 确保包含三条通知 */
}
.notice-item {
  display: flex;
  align-items: center;
  width: 100%;
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  cursor: pointer;
}
.notice-title {
  margin-left: 10px;
  font-size: 14px;
  color: #333;
  flex-grow: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.notice-time {
  font-size: 12px;
  color: #999;
  margin-left: 20px;
}
.no-notice {
  width: 100%;
  height: 120px;
  /* 与轮播高度一致 */
  line-height: 120px;
  text-align: center;
  color: #999;
  font-size: 14px;
}
.top {
@@ -384,28 +447,5 @@
  height: 350px;
  background-color: #fff;
  margin-right: 20px;
}
/* 自定义 Element UI 通知样式 */
.el-notification {
  min-width: 300px;
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
  font-size: 16px;
  padding: 15px 20px;
}
.el-notification__title {
  font-weight: bold;
}
.el-notification__content {
  font-size: 14px;
  color: #333;
}
.el-notification__closeBtn {
  color: #999;
}
</style>