瀏覽代碼

改善任务写websocket

jiangniuniu 4 年之前
父節點
當前提交
5b82d9ec3e
共有 4 個文件被更改,包括 292 次插入203 次删除
  1. 195 169
      pages/messages/messages.vue
  2. 62 2
      pages/mission/mission.vue
  3. 1 1
      utils/request.js
  4. 34 31
      utils/ws.js

+ 195 - 169
pages/messages/messages.vue

@@ -1,177 +1,203 @@
 <template>
-	<view class="messages-page">
-		<view class="contBody" @touchend="touchend" :style="MessList.length <= 8 ? {height:'calc(100% - 30rpx)'} : {}">
-			<view v-for="(item,index) in MessList" :key="index" class="messages-content" @click="toDetail(item)">
-				<view class="imgView">
-					<image :src="item.businessType == 1 ? (item.readStatus ? '/static/橙色已读.png' : '/static/橙色未读.png') : (item.readStatus ? '/static/绿色已读.png' : '/static/绿色未读.png')"></image>
-				</view>
-				<view class="contView">
-					<view class="contView-title">
-						{{item.title}}
-					</view>
-					<view class="contView-content">
-						{{item.content}}
-					</view>
-					<view class="contView-time">
-						{{item.effectTime}}
-					</view>
-				</view>
-			</view>
-			<view class="bottomPanDuan"></view>
-		</view>
-		
-		<view class="bottomTishi">
-			<view v-if="loading">
-				向上滑动加载更多!
-			</view>
-			<view v-else>
-				已经到底了~
-			</view>
-		</view>
-	</view>
+  <view class="messages-page">
+    <view
+      class="contBody"
+      @touchend="touchend"
+      :style="MessList.length <= 8 ? { height: 'calc(100% - 30rpx)' } : {}"
+    >
+      <view
+        v-for="(item, index) in MessList"
+        :key="index"
+        class="messages-content"
+        @click="toDetail(item)"
+      >
+        <view class="imgView">
+          <image
+            :src="
+              item.businessType == 1
+                ? item.readStatus
+                  ? '/static/橙色已读.png'
+                  : '/static/橙色未读.png'
+                : item.readStatus
+                ? '/static/绿色已读.png'
+                : '/static/绿色未读.png'
+            "
+          ></image>
+        </view>
+        <view class="contView">
+          <view class="contView-title">
+            {{ item.title }}
+          </view>
+          <view class="contView-content">
+            {{ item.content }}
+          </view>
+          <view class="contView-time">
+            {{ item.effectTime }}
+          </view>
+        </view>
+      </view>
+      <view class="bottomPanDuan"></view>
+    </view>
+
+    <view class="bottomTishi">
+      <view v-if="loading"> 向上滑动加载更多! </view>
+      <view v-else> 已经到底了~ </view>
+    </view>
+  </view>
 </template>
 
 <script>
-	import moment from 'moment';
-	export default {
-		data() {
-			return {
-				pageNum: 1,
-				pageSize: 10,
-				MessList: [],
-				loading: false,
-				currentPage: 0,
-				totalPage: 0,
-			}
-		},
-		mounted() {
-		  this.getMessList();
-		},
-		methods:{
-			getMessList(){
-				var currPage = this.currentPage + 1;
-				this.$store.dispatch({
-					type: "messages/commActions",
-					payload: {
-					  key: "messagesList",
-					  data: {
-						  pageNum: currPage,
-						  pageSize: this.pageSize,
-					  }
-					},
-				}).then(res=>{
-					this.totalPage = res.totalPage;
-					res.list.map((item)=>{
-						item.effectTime = moment(item.effectTime).format('MM-DD hh:mm')
-					})
-					//获取当前页码
-					this.currentPage = res.pageNum;
-					//当前页码与总页码进行比对
-					this.loading = this.currentPage < this.totalPage;
-					//将获得的数据拼接当前渲染数据中
-					this.MessList = this.MessList.concat(res.list);
-				})
-			},
-			touchend(){
-				if(this.currentPage < this.totalPage){
-					var box = document.getElementsByClassName('bottomPanDuan')[0];
-					var pos = box.getBoundingClientRect();
-					if(pos.bottom<=document.documentElement.clientHeight){
-						this.getMessList();
-					}
-				}
-				
-			},
-			toDetail(data){
-				this.$store.dispatch({
-					type: "messages/commActions",
-					payload: {
-					  key: "toRead",
-					  data: {
-						  id:data.id
-					  }
-					},
-				}).then(res=>{
-					uni.navigateTo({
-					  url: '/pages/mission-details/mission-details'
-					});
-					this.MessList = [];
-					for(let i = 0 ; i < this.currentPage; i++){
-						this.$store.dispatch({
-							type: "messages/commActions",
-							payload: {
-							  key: "messagesList",
-							  data: {
-								  pageNum: i,
-								  pageSize: this.pageSize,
-							  }
-							},
-						}).then(res=>{
-							this.MessList = this.MessList.concat(res.list);
-						})
-					}
-				})
-			}
-			
-		},
-		computed:{
-		}
-	}
+import moment from "moment";
+export default {
+  data() {
+    return {
+      pageNum: 1,
+      pageSize: 10,
+      MessList: [],
+      loading: false,
+      currentPage: 0,
+      totalPage: 0,
+    };
+  },
+  mounted() {
+    this.getMessList();
+  },
+  methods: {
+    getMessList() {
+      var currPage = this.currentPage + 1;
+      this.$store.dispatch({
+          type: "messages/commActions",
+          payload: {
+            key: "messagesList",
+            data: {
+              pageNum: currPage,
+              pageSize: this.pageSize,
+            },
+          },
+        })
+        .then((res) => {
+          this.totalPage = res.totalPage;
+          res.list.map((item) => {
+            item.effectTime = moment(item.effectTime).format("MM-DD hh:mm");
+          });
+          //获取当前页码
+          this.currentPage = res.pageNum;
+          //当前页码与总页码进行比对
+          this.loading = this.currentPage < this.totalPage;
+          //将获得的数据拼接当前渲染数据中
+          this.MessList = this.MessList.concat(res.list);
+        });
+    },
+    touchend() {
+      if (this.currentPage < this.totalPage) {
+        var box = document.getElementsByClassName("bottomPanDuan")[0];
+        var pos = box.getBoundingClientRect();
+        if (pos.bottom <= document.documentElement.clientHeight) {
+          this.getMessList();
+        }
+      }
+    },
+    toDetail(data) {
+      this.$store.dispatch({
+          type: "messages/commActions",
+          payload: {
+            key: "toRead",
+            data: {
+              id: data.id,
+            },
+          },
+        })
+        .then((res) => {
+          if (data.businessType == 1) {
+            uni.navigateTo({
+              url: `/pages/mission-details/mission-details?taskId=${data.businessId}`,
+            });
+          } else if (data.businessType == 2) {
+            uni.navigateTo({
+              url: `/pages/home/home`,
+            });
+          }
+          this.MessList = [];
+          for (let i = 1; i < this.currentPage + 1; i++) {
+            this.$store.dispatch({
+                type: "messages/commActions",
+                payload: {
+                  key: "messagesList",
+                  data: {
+                    pageNum: i,
+                    pageSize: this.pageSize,
+                  },
+                },
+              })
+              .then((res) => {
+                res.list.map((item) => {
+                  item.effectTime = moment(item.effectTime).format(
+                    "MM-DD hh:mm"
+                  );
+                });
+                this.MessList = this.MessList.concat(res.list);
+              });
+          }
+        });
+    },
+  },
+  computed: {},
+};
 </script>
 
 <style lang="less">
-	.messages-page{
-		padding-top: 15rpx;
-		height: 100%;
-		overflow-y: auto;
-		.messages-content{
-			display: flex;
-			background-color: #fff;
-			.imgView{
-				margin-top: 25rpx;
-				margin-left: 25rpx;
-				margin-right: 25rpx;
-				margin-bottom: 63.75rpx;
-				width: 56.25rpx;
-				height: 56.25rpx;
-				vertical-align: top;
-				.image-circle{
-					background-color: ;
-				}
-				image{
-					width: 56.25rpx;
-					height: 90px;
-				}
-			}
-			.contView{
-				flex: 1;
-				border-bottom: 0.62rpx solid #DADEE6;
-				.contView-title{
-					margin-top:25rpx ;
-					font-size: 22.5rpx;
-					font-weight: 500;
-					color: #292C33;
-				}
-				.contView-content{
-					margin:15rpx 0 20rpx;
-					font-size: 20rpx;
-					color: #525866;
-				}
-				.contView-time{
-					margin-bottom: 25rpx;
-					font-size: 17.5rpx;
-					color: #666E80;
-				}
-			}
-		}
-		.bottomTishi{
-			padding: 6.25rpx 0px;
-			width: 100%;
-			// position: absolute;
-			// bottom: 0rpx;
-			text-align: center;
-			font-size: 17.5rpx;
-			color: #525866;
-		}
-	}
+.messages-page {
+  padding-top: 15rpx;
+  height: 100%;
+  overflow-y: auto;
+  .messages-content {
+    display: flex;
+    background-color: #fff;
+    .imgView {
+      margin-top: 25rpx;
+      margin-left: 25rpx;
+      margin-right: 25rpx;
+      margin-bottom: 63.75rpx;
+      width: 56.25rpx;
+      height: 56.25rpx;
+      vertical-align: top;
+      .image-circle {
+        background-color: ;
+      }
+      image {
+        width: 56.25rpx;
+        height: 90px;
+      }
+    }
+    .contView {
+      flex: 1;
+      border-bottom: 0.62rpx solid #dadee6;
+      .contView-title {
+        margin-top: 25rpx;
+        font-size: 22.5rpx;
+        font-weight: 500;
+        color: #292c33;
+      }
+      .contView-content {
+        margin: 15rpx 0 20rpx;
+        font-size: 20rpx;
+        color: #525866;
+      }
+      .contView-time {
+        margin-bottom: 25rpx;
+        font-size: 17.5rpx;
+        color: #666e80;
+      }
+    }
+  }
+  .bottomTishi {
+    padding: 6.25rpx 0px;
+    width: 100%;
+    // position: absolute;
+    // bottom: 0rpx;
+    text-align: center;
+    font-size: 17.5rpx;
+    color: #525866;
+  }
+}
 </style>

+ 62 - 2
pages/mission/mission.vue

@@ -1,5 +1,8 @@
 <template>
 	<view class="mission-page">
+		<view class="message-remind" @click="toMessagePage">
+			<image :src="messageType?'/static/mission/消息中心未读.png':'/static/mission/消息中心已读.png'" mode=""></image>
+		</view>
 	 	<scroll-view class="scroll-y" scroll-y="true">
 			<list-item
 				v-for="(item, i) in improvingTaskList"
@@ -32,6 +35,7 @@
 <script>
 	// 任务列表
 	import listItem from './components/list-item.vue';
+	import websocket from '../../utils/ws.js';//引入websocket
 	export default {
 		data(){
 			return {
@@ -74,11 +78,24 @@
 				],
 				// 历史任务
 				completeTaskList: [],
+				refTimer: null,
+				isInitWs:null,
+				messageType:null,
 			}
 		},
 		created() {
-			this.getMissionList()
+			// this.getMissionList();
+			this.init(true);
+			this.refTimer = setInterval(() => {
+			    this.isInitWs = websocket.ws ? false : true;
+			    this.init(this.isInitWs);
+			}, 3 * 60 * 1000);
 		},
+		beforeDestroy() {
+		    // 关闭ws连接
+		    websocket.close();
+		    clearInterval(this.refTimer);
+		  },
 		methods: {
 			toggleBtn() {
 				let flag = !this.showCloseList;
@@ -88,6 +105,10 @@
 					name: flag ? '收起历史任务' : '展示历史任务'
 				}
 			},
+			init(isInitWs) {
+				this.isInitWs = isInitWs;
+			    this.getMissionList()
+			},
 			// 获取改善任务列表
 			getMissionList(data) {
 				this.$store.dispatch({
@@ -100,12 +121,36 @@
 					if(data) {
 						this.improvingTaskList = data.improvingTaskResponses || [];
 						this.completeTaskList = data.improveCompleteResponses || [];
+						let hiId = uni.getStorageSync('hiId');
+						let user = uni.getStorageSync('id');
+						let permission = uni.getStorageSync('nowPermission');
+						this.isInitWs && this.initWebsocket(hiId,user,permission);
 					}
 				});
 				/** 请求参数 data
 				 * situationId: 情境id 当管路员或者查核者通过情境进入任务列表时 必传
 				 * checkItemId 单位负责人通过 查核要点进入改善任务列表时 必传
 				 */
+			},
+			initWebsocket(hiId,user,permission) {
+			    websocket.url = `ws://192.168.1.45:8088/imed/pfm/websocket/${hiId}/${user}/${permission}`;
+			    websocket.createWebSocket(this.resolverWsData.bind(this));
+			},
+			// 解析websocket返回数据
+			resolverWsData(type) {
+			  switch (type) {
+			    case "TO_READ":
+			      this.messageType = true;
+			      break;
+			    default:
+				  this.messageType = false;
+			      break;
+			  }
+			},
+			toMessagePage(){
+				uni.navigateTo({
+				  url: `/pages/messages/messages`
+				});
 			}
 		},
 		components: {
@@ -118,7 +163,22 @@
  .mission-page {
    height: 100%;
    padding-top: 15rpx;
-
+	.message-remind{
+		width: 62.5rpx;
+		height: 62.5rpx;
+		position: fixed;
+		top: 25rpx;
+		right: 25rpx;
+		background: rgba(255, 255, 255, 0.95);
+		border-radius: 50%;
+		z-index: 2;
+		image{
+			margin-left: 17.5rpx;
+			margin-top: 16.87rpx;
+			width: 27.5rpx;
+			height: 28.75rpx;
+		}
+	}
    	.scroll-y {
 			height: calc(100% - 87.5rpx);
 

+ 1 - 1
utils/request.js

@@ -47,7 +47,7 @@ function request(url, options, additional) {
   openCloseLoading(additional, true);
   // 模拟token,做登录的同学将这行代码移到登录成功函数中.
 
-  uni.setStorageSync('token', 'gfkZlq36bBPefzvIoukl5exPJ5/jkil2gi9fNPTABSk=');
+  // uni.setStorageSync('token', 'gfkZlq36bBPefzvIoukl5exPJ5/jkil2gi9fNPTABSk=');
   const token = uni.getStorageSync('token');
   return uni.request({
     url: `${BASE_URL}${url}`,

+ 34 - 31
utils/ws.js

@@ -11,64 +11,67 @@ const heartCheck = {
       // 表示连接已经关闭或者连接不能打开。
       if (ws && ws.readyState === 3) return;
       //发送一个心跳,后端收到后,返回一个心跳消息,onmessage拿到返回的心跳就说明连接正常
-      ws && ws.send({data: "ping"});
+      ws && ws.send({ data: "ping" });
       self.serverTimeoutObj = setTimeout(() => {
         ws && ws.close();
-                websocket.reconnect();
+        websocket.reconnect();
       }, self.timeout + 3000);
     }, this.timeout);
   }
 };
- 
+
 const websocket = {
   ws: null,
   url: '',
   connected: false,
   connecting: false,
   reconnectTimeId: null,
-    callback: null, // 存放回调函数
-    reconnetCount: 0, // 重连次数
+  callback: null, // 存放回调函数
+  reconnetCount: 0, // 重连次数
   lockReconnect: false, // 避免ws重复连接
   createWebSocket(callback) {
+
     if (this.connected || this.connecting) { // 正在连接或者已经连接,请勿重复连接
       return false
     }
     try {
-            if (callback) websocket.callback = callback;
+      if (callback) websocket.callback = callback;
       this.connecting = true;
       // 创建
       this.ws = uni.connectSocket({
         url: this.url,
         success(data) {
-          // console.log("websocket连接成功!");
+          console.log("websocket连接成功!");
         }
       });
       // 监听 Ws 连接打开
       this.ws.onOpen((res) => {
         this.connecting = false;
         this.connected = true;
-        // console.log("websocket连接打开正常!");
+        console.log("websocket连接打开正常!");
         //心跳检测重置
         heartCheck.start(this.ws);
-                this.reconnetCount && (this.reconnetCount = 0);
+        this.reconnetCount && (this.reconnetCount = 0);
       });
       this.ws.onError((res) => {
         this.connecting = false;
         this.connected = false;
-        // console.log("ws连接错误!", res);
+        console.log("ws连接错误!", res);
         this.reconnect();
       });
       this.ws.onMessage((res) => {
-            if (res.data === 'ping') {
-              heartCheck.start(this.ws); //获取到消息,心跳检测重置
-              this.reconnetCount && (this.reconnetCount = 0);
-            } else {
-          const { type, data } = JSON.parse(res.data);
-          // console.log("ws 收到消息啦:" + type);
+        if (res.data === 'ping') {
+          heartCheck.start(this.ws); //获取到消息,心跳检测重置
+          console.log("ws 没有收到消息");
+          this.reconnetCount && (this.reconnetCount = 0);
+        } else {
+          // const { type, data } = JSON.parse(res.data);
+          const { data } = res;
+          console.log("ws 收到消息啦:" + data);
           if (callback) {
-            callback(type, data);
+            callback(data);
           } else if (websocket.callback) {
-            websocket.callback(type, data);
+            websocket.callback(data);
           }
         }
       });
@@ -86,12 +89,12 @@ const websocket = {
   },
   reconnect() { // 重连
     if (this.lockReconnect) return;
-        if (this.reconnetCount === 6) {
-          this.close();
-          return
-        }
+    if (this.reconnetCount === 6) {
+      this.close();
+      return
+    }
     this.lockReconnect = true;
-        this.reconnetCount++;
+    this.reconnetCount++;
     this.reconnectTimeId && clearTimeout(this.reconnectTimeId);
     this.reconnectTimeId = setTimeout(() => {//没连接上会一直重连,设置延迟避免请求过多
       this.createWebSocket(websocket.callback);
@@ -103,14 +106,14 @@ const websocket = {
       this.ws.close && this.ws.close();
       this.ws = null;
     }
-        this.connected = false;
-        this.connecting = false;
-        this.lockReconnect = false;
-        this.reconnetCount = 0;
-        this.reconnectTimeId && clearTimeout(this.reconnectTimeId);
-        heartCheck.timeoutObj && clearTimeout(heartCheck.timeoutObj);
-        heartCheck.serverTimeoutObj && clearTimeout(heartCheck.serverTimeoutObj);
+    this.connected = false;
+    this.connecting = false;
+    this.lockReconnect = false;
+    this.reconnetCount = 0;
+    this.reconnectTimeId && clearTimeout(this.reconnectTimeId);
+    heartCheck.timeoutObj && clearTimeout(heartCheck.timeoutObj);
+    heartCheck.serverTimeoutObj && clearTimeout(heartCheck.serverTimeoutObj);
   }
 }
- 
+
 export default websocket;