gongdecai %!s(int64=3) %!d(string=hai) anos
pai
achega
b956a4d732
Modificáronse 14 ficheiros con 2051 adicións e 66 borrados
  1. 105 2
      App.vue
  2. 80 0
      PacketCodeC.js
  3. 1 8
      README.md
  4. 347 0
      components/APPPush/app_push.js
  5. 14 0
      components/APPPush/index.js
  6. 0 3
      config/index.js
  7. 4 0
      main.js
  8. 3 32
      pages/index/index.vue
  9. 18 19
      pages/public/login.vue
  10. 77 0
      util/dbUtil.js
  11. 1 2
      util/request.js
  12. 16 0
      util/util.js
  13. 965 0
      webim.js
  14. 420 0
      websocket_sdk.js

+ 105 - 2
App.vue

@@ -3,16 +3,119 @@
 	@import "@/uni_modules/uview-ui/index.scss";
 </style>
 <script>
+	import {
+		mapMutations
+	} from 'vuex';
+	import * as config from '@/config'
+	import appUpdate from 'common/appUpdate.js'
+	import app_push from './components/APPPush/app_push.js'
 	export default {
+		methods: {
+			...mapMutations(['login']),
+		},
 		onLaunch: function() {
-			console.log('App Launch')
+			// #ifdef APP-PLUS
+
+			let type = uni.getSystemInfoSync().platform
+			console.log(type)
+			if (type == "android") {
+				appUpdate()
+			}
+			var that = this
+			plus.push.getClientInfoAsync((info) => {
+				var name = 'clientId'
+				var value = info.clientid
+				that.$store.commit('$uStore', {
+					name,
+					value
+				});
+				uni.setStorageSync("clientId", info.clientid)
+				console.log("info.clientid", info.clientid)
+			}, err => {});
+			// 监听在线消息事件  
+			plus.push.addEventListener("receive", function(msg) {
+				var title = msg.content.split(':')[0]
+				var content = msg.content.split(':')[1]
+
+				let params = {
+					inApp: true, // app内横幅提醒
+					voice: true, // 声音提醒
+					vibration: true, // 振动提醒
+					messageType: "",
+					messageTitle: title,
+					messageContent: content,
+					messageImage: 'https://taohaoliang.oss-cn-beijing.aliyuncs.com/app/logo.png'
+				}
+				console.log("msg", msg)
+				new app_push({
+					...params
+				}).show();
+				var userInfo = uni.getStorageSync("userInfo")
+				var that = this
+				that.$request.baseRequest('get', '/notice/query/noticeNumber').then(res => {
+					if (res.data.data) {
+						let name = 'myTip';
+						let value = res.data.data.task;
+						that.$store.commit('$uStore', {
+							name,
+							value
+						});
+						if (value != 0 && value) {
+							uni.setTabBarBadge({
+								index: 4,
+								text: value + ""
+							})
+						}
+						name = 'taskTip';
+						value = res.data.data.task;
+						that.$store.commit('$uStore', {
+							name,
+							value
+						});
+						// name = 'contractTip';
+						// value = res.data.data.contractTip;
+						// that.$store.commit('$uStore', {
+						// 	name,
+						// 	value
+						// });
+					}
+				})
+				//其它逻辑  
+			}, false);
+			//监听系统通知栏消息点击事件  
+			plus.push.addEventListener('click', function(msg) {
+				//处理点击消息的业务逻辑代码  
+				if (msg.content && msg.content.contains("任务")) {
+					uni.navigateTo({
+						url: '/pages/task/my_task'
+					})
+				} else if (msg.content && (msg.content.contains("合同") || msg.content.contains("交易"))) {
+					uni.navigateTo({
+						url: '/pageB/contract/contract'
+					})
+				}
+
+			}, false);
+			// #endif
+			this.$socket.initWebIM(this.$ws, true, true)
+			let userInfo = uni.getStorageSync('userInfo') || '';
+			if (userInfo.id) {
+				//更新登陆状态
+				uni.getStorage({
+					key: 'userInfo',
+					success: (res) => {
+						this.login(res.data);
+					}
+				});
+			}
+
 		},
 		onShow: function() {
 			console.log('App Show')
 		},
 		onHide: function() {
 			console.log('App Hide')
-		}
+		},
 	}
 </script>
 

+ 80 - 0
PacketCodeC.js

@@ -0,0 +1,80 @@
+const PacketCodeC = {
+  encode (packet) {
+    let bytes = stringToBytes(JSON.stringify(packet))
+    let buffer = new ArrayBuffer(11 + bytes.length)
+    if (buffer.byteLength !== 11 + bytes.length) {
+      return null
+    }
+    let dataView = new DataView(buffer)
+
+    dataView.setInt32(0, 0x12345678)
+    dataView.setInt8(4, packet.version)
+    dataView.setInt8(5, 1) // 写死1表示json序列化
+    dataView.setInt8(6, packet.command)
+    dataView.setInt32(7, bytes.length)
+    for (let i = 11; i < bytes.length + 11; i++) {
+      dataView.setUint8(i, bytes[i - 11])
+    }
+    return dataView.buffer
+  },
+  decode (buffer) {
+    let dataView = new DataView(buffer)
+    let lenght = dataView.getInt32(7)
+    let bytes = []
+    for (let i = 11; i < lenght + 11; i++) {
+      bytes[i - 11] = dataView.getUint8(i)
+    }
+    let json = bytesToString(bytes)
+    return JSON.parse(json)
+  }
+}
+
+var stringToBytes = (str) => {
+  let bytes = []
+  let len, c
+  len = str.length
+  for (let i = 0; i < len; i++) {
+    c = str.charCodeAt(i)
+    if (c >= 0x010000 && c <= 0x10FFFF) {
+      bytes.push(((c >> 18) & 0x07) | 0xF0)
+      bytes.push(((c >> 12) & 0x3F) | 0x80)
+      bytes.push(((c >> 6) & 0x3F) | 0x80)
+      bytes.push((c & 0x3F) | 0x80)
+    } else if (c >= 0x000800 && c <= 0x00FFFF) {
+      bytes.push(((c >> 12) & 0x0F) | 0xE0)
+      bytes.push(((c >> 6) & 0x3F) | 0x80)
+      bytes.push((c & 0x3F) | 0x80)
+    } else if (c >= 0x000080 && c <= 0x0007FF) {
+      bytes.push(((c >> 6) & 0x1F) | 0xC0)
+      bytes.push((c & 0x3F) | 0x80)
+    } else {
+      bytes.push(c & 0xFF)
+    }
+  }
+  return bytes
+}
+
+var bytesToString = (bytes) => {
+  if (typeof bytes === 'string') {
+    return bytes
+  }
+  let str = ''
+  let _arr = bytes
+  for (let i = 0; i < _arr.length; i++) {
+    let one = _arr[i].toString(2)
+    let v = one.match(/^1+?(?=0)/)
+    if (v && one.length === 8) {
+      let bytesLength = v[0].length
+      let store = _arr[i].toString(2).slice(7 - bytesLength)
+      for (let st = 1; st < bytesLength; st++) {
+        store += _arr[st + i].toString(2).slice(2)
+      }
+      str += String.fromCharCode(parseInt(store, 2))
+      i += bytesLength - 1
+    } else {
+      str += String.fromCharCode(_arr[i])
+    }
+  }
+  return str
+}
+export default PacketCodeC

+ 1 - 8
README.md

@@ -1,12 +1,5 @@
 # uniapp开发模板
 
 #### 介绍
-uni-app项目开发模板,集成了u-view 2.0、基于uni-request封装、token验证
-
-
-#### 使用说明
-
-1.  xxxx
-2.  xxxx
-3.  xxxx
+uni-app项目开发模板,集成了u-view 2.0、基于uni-request封装、token验证、websocket、页面权限、按钮权限、mescoll上拉加载、下拉刷新、热更新、推送
 

+ 347 - 0
components/APPPush/app_push.js

@@ -0,0 +1,347 @@
+export class appPush{
+	constructor(option = {}) {
+		console.log("appPush",option)
+		// app内横幅提醒
+		this.inApp = option.inApp;
+		// 声音提醒
+		this.voice = option.voice;
+		// 振动提醒
+		this.vibration = option.vibration;
+		// 消息分类
+		this.messageType = option.messageType || '';
+		// 通知标题
+		this.messageTitle = option.messageTitle || '';
+		// 时间
+		this.messageTime = option.messageTime || '现在';
+		// 通知文案
+		this.messageContent = option.messageContent || '';
+		// 缩略图
+		this.messageImage = option.messageImage || '';	
+		
+		
+	    this.screenWidth = plus.screen.resolutionWidth;
+	    this.screenHeight = plus.screen.resolutionHeight;
+	    // 比例
+	    this.propotation = this.screenWidth / 750
+	    //弹窗容器宽度
+	    this.popupViewWidth = this.propotation * 710;
+	    // 弹窗容器高度
+	    this.popupViewHeight = this.propotation * 152;
+	    // 弹窗容器的Padding
+	    this.viewContentPadding = this.propotation * 30;
+		// 弹框容器的宽度
+		this.viewContentWidth = parseInt(this.popupViewWidth - (this.viewContentPadding * 2))
+		// 弹框到顶部的距离
+		this.system = uni.getSystemInfoSync()
+		// 过度时间
+		this.duration = 200
+		// 关闭时间
+		this.closeTime = 10000
+		
+		console.log(this.inApp, this.voice, this.vibration)
+		
+		this.top = (this.propotation * 20) + this.system.statusBarHeight;
+		this.initTop = -this.system.statusBarHeight
+		
+		this.body = null;
+		this.bodyBg = null;
+		this.timer = null;
+		
+		this.flag = false
+		this.cur = {
+			x: 0,
+			y: 0,
+			pageX: 0,
+			pageY: 0
+		}
+		
+	}
+	
+	// 生成弹框主体
+	createView() {
+		console.log((this.propotation * 20) + this.system.statusBarHeight+ '--------------')
+		let view = new plus.nativeObj.View('popupView', {
+			// tag: 'rect',
+			top: (this.propotation * 20) + this.system.statusBarHeight,
+			left: this.propotation * 20,
+			height: this.popupViewHeight,
+			width: this.popupViewWidth
+		})
+		// 绘制白色背景
+		view.drawRect({
+			color:"#626262",
+			radius:"10px"
+		})
+		let viewContentList = [
+			// {
+			// 	src: '/static/push/message-icon.png',
+			// 	id: 'icon',
+			// 	tag: 'img',
+			// 	position: {
+			// 		top: this.viewContentPadding + "px",
+			// 		left: this.viewContentPadding + "px",
+			// 		width: (this.propotation * 24) + 'px',
+			// 		height: (this.propotation * 24) + 'px',
+			// 	}
+			// },
+			// {
+			// 	tag: 'font',
+			// 	id: 'pop-title',
+			// 	text: this.messageType,
+			// 	textStyles: {
+			// 		size: (this.propotation * 24) + 'px',
+			// 		align: "left",
+			// 		color: "#4F555B"
+			// 	},
+			// 	position: {
+			// 		top: this.viewContentPadding + "px",
+			// 		left: (this.propotation * 64) + 'px',
+			// 		height: (this.propotation * 24) + 'px',
+			// 		width: this.viewContentWidth + "px",
+			// 	}
+			// },
+			// {
+			// 	tag: 'font',
+			// 	id: 'time',
+			// 	text: this.messageTime,
+			// 	textStyles: {
+			// 		size: (this.propotation * 24) + 'px',
+			// 		align: "right",
+			// 		color: "#4F555B"
+			// 	},
+			// 	position: {
+			// 		top: this.viewContentPadding + "px",
+			// 		left: this.viewContentPadding + "px",
+			// 		height: (this.propotation * 24) + 'px',
+			// 		width: this.viewContentWidth + "px",
+			// 	}
+			// },
+			{
+				tag: 'font',
+				id: 'push-title',
+				text: this.messageTitle,
+				textStyles: {
+					size: (this.propotation * 35) + 'px',
+					align: "left",
+					color: "#f7f7f7",
+					overflow: "ellipsis"
+				},
+				position: {
+					top: this.viewContentPadding + 'px',
+					left: (this.propotation * 30) + 'px',
+					height: (this.propotation * 35) + 'px',
+					width: (this.propotation * 505) + 'px',
+				}
+			},
+			{
+				tag: 'font',
+				id: 'push-content',
+				text: this.messageContent,
+				textStyles: {
+					size: (this.propotation * 28) + 'px',
+					align: "left",
+					color: "#f7f7f7",
+					overflow: "ellipsis"
+				},
+				position: {
+					top: (this.propotation * 90) + 'px',
+					left: (this.propotation * 30) + 'px',
+					height: (this.propotation * 28) + 'px',
+					width: (this.propotation * 655) + 'px',
+				}
+			},
+			// {
+			// 	src: this.messageImage,
+			// 	id: 'image',
+			// 	tag: 'img',
+			// 	position: {
+			// 		top: (this.propotation * 68) + 'px',
+			// 		// right: "0px",
+			// 		left: (this.propotation * 586) + 'px',
+			// 		width: (this.propotation * 100) + 'px',
+			// 		height: (this.propotation * 100) + 'px',
+			// 	}
+			// },
+			// {
+			// 	src: '/static/push/img-bg.png',
+			// 	id: 'img-bg',
+			// 	tag: 'img',
+			// 	position: {
+			// 		top: (this.propotation * 68) + 'px',
+			// 		// right: "0px",
+			// 		left: (this.propotation * 586) + 'px',
+			// 		width: (this.propotation * 100) + 'px',
+			// 		height: (this.propotation * 100) + 'px',
+			// 	}
+			// },
+		]
+		view.draw(viewContentList)
+		// view.addEventListener("click",(e)=>{
+		// 	console.log('---------------------')
+		// });
+		view.addEventListener("touchstart", (event) => {
+			// console.log(event)
+			this.flag = true;  
+			var touch;  
+			if (event.touches) {  
+				touch = event.touches[0];  
+			} else {  
+				touch = event;  
+			}  
+			this.cur.x = touch.clientX;  
+			this.cur.y = touch.clientY;
+			this.cur.pageX = touch.pageX;
+			this.cur.pageY = touch.pageY;  
+		})
+		view.addEventListener("touchmove", (event) => {
+			// console.log(e)
+			var touch;  
+			if (event.touches) {  
+				touch = event.touches[0];  
+			} else {  
+				touch = event;
+			}  
+			let moveX = touch.pageX - this.cur.x;   
+			let moveY = touch.pageY - this.cur.y;   
+			let x = moveX;  
+			let y = moveY;
+			// console.log(x, y)
+			// console.log(this.cur, touch)
+			if (x < 0) {  
+				// x = 0;  
+			} else if (x > (this.popupViewWidth - this.popupViewWidth)) {  
+				// x = this.screenWidth - 40;  
+			}  
+			if (y < 0) {  
+				// y = 0;  
+			} else if (y >= ((this.propotation * 20) + this.system.statusBarHeight)) {  
+				y = ((this.propotation * 20) + this.system.statusBarHeight);  
+			}  
+			this.body.setStyle({  
+				top: y + 'px',  
+				left: x + 'px'  
+			});
+		})
+		/**
+		 * 这里有一个bug暂时无法解决,当用户快速往左滑时,滑动区域超出屏幕会监听不到touchend事件😂,很难被发现我就不解决了
+		 */
+		view.addEventListener("touchend", (event) => {
+			// console.log(this.cur, event)
+			var touch;
+			if (event.touches) {  
+				touch = event.touches[0];  
+			} else {  
+				touch = event;  
+			}
+			let differX = Math.abs(this.cur.pageX) - Math.abs(touch.pageX)
+			let differY = Math.abs(this.cur.pageY) - Math.abs(touch.pageY)
+			this.flag = false
+			// console.log(differX, differY)
+			if(Math.abs(differX) > 5 || Math.abs(differY) > 5) {	// 上下移动或左右移动超过5px则关闭弹窗
+				this.hide()
+			} else {	// 否则当作单击事件
+				console.log('-------------------')
+				this.hide()
+			}
+		})
+		this.body = view;
+		
+	// 	let bodyBg = new plus.nativeObj.View('bodyBg',{
+	// 		top: (this.propotation * 20) + this.system.statusBarHeight,
+	// 		left: this.propotation * 20,
+	// 		height: this.popupViewHeight,
+	// 		width: this.popupViewWidth,
+	// 		backgroundColor:'rgba(0, 0, 0, 1)',
+	// 	});
+	// 	bodyBg.draw([
+	// 	  {tag:'font',id:'confirm',text:'关闭关闭',textStyles:{color:'red',size:'16px'}},
+	// 	]);
+	
+	// 	bodyBg.addEventListener("click",(e)=>{
+	// 		console.log('---------------------')
+	// 	});
+	// 	this.bodyBg = bodyBg
+	}
+	// 显示/关闭弹框动画
+	modelAnimationOpenOrClose(type) {
+		var options = {type:type,duration:this.duration};
+		plus.nativeObj.View.startAnimation(options,this.body, () => {
+			// 关闭原生动画
+			plus.nativeObj.View.clearAnimation();
+		});
+	}
+	bgAnimationOpenOrClose(type) {
+		var options = {type:type,duration:this.duration};
+		plus.nativeObj.View.startAnimation(options,this.bodyBg, () => {
+			// 关闭原生动画
+			plus.nativeObj.View.clearAnimation();
+		});
+	}
+	// closeAnimation() {
+	// 	// push弹框距离最顶部的距离
+	// 	let top = (this.propotation * 20) + this.system.statusBarHeight
+	// 	// 完全隐藏时的顶部距离
+	// 	let hideTop = -this.system.statusBarHeight
+	// 	this.timer = setInterval(() => {
+	// 		this.top = this.top - 2
+	// 		if(this.top < hideTop * 2) {
+	// 			clearInterval(this.timer)
+	// 			this.timer = null
+	// 		}
+	// 		this.body.setStyle({
+	// 			top:this.top
+	// 		})
+	// 	}, 1)
+	// }
+	// 显示弹框
+	show() {
+		this.tips()
+		if(this.inApp) {
+			this.createView()
+			// this.modelAnimationOpenOrClose('slide-in-right')
+			this.body.show()
+			// this.bodyBg.show()
+			setTimeout(() => {
+				if(this.body) {
+					this.hide()
+				}
+			}, this.closeTime)
+		}
+	}
+	// 关闭弹框
+	hide() {
+		this.modelAnimationOpenOrClose('slide-out-right')
+		this.body.hide()
+		setTimeout(() => {
+			plus.nativeObj.View.clearAnimation();
+			this.body = null
+		}, this.duration)
+		// this.bgAnimationOpenOrClose('slide-out-right')
+		// this.bodyBg.hide()
+	}
+	// 调用系统提示音和振动
+	tips() {
+		if(this.voice) {
+			let system = uni.getSystemInfoSync().platform
+			if(system == 'ios') {
+				let player = plus.audio.createPlayer( "/static/audio/ios.mp3" );
+				player.play()
+			} else {
+				let main = plus.android.runtimeMainActivity();
+				let RingtoneManager = plus.android.importClass("android.media.RingtoneManager");
+				let uri = RingtoneManager.getActualDefaultRingtoneUri(main, RingtoneManager.TYPE_NOTIFICATION);
+				console.log(uri)
+				let MediaPlayer = plus.android.importClass("android.media.MediaPlayer");  
+				let player = MediaPlayer.create(main, uri);  
+				player.setLooping(false);  
+				player.prepare();  
+				player.start();
+			}
+		}
+		if(this.vibration) {
+			plus.device.vibrate()
+		}
+	}
+}
+
+export default appPush

+ 14 - 0
components/APPPush/index.js

@@ -0,0 +1,14 @@
+import app_push from './app_push.js'
+
+const appPush = {
+	install: function(Vue) {
+		Vue.prototype.$appPush = function(op = {}) {
+			console.log("进入appPush")
+			new app_push({
+				...op
+			}).show();
+		}
+	}
+}
+
+export default appPush

+ 0 - 3
config/index.js

@@ -1,8 +1,5 @@
 const dev = {
-	baseUrl: 'https://www.zthymaoyi.com',
-	// baseUrlNew: 'http://192.168.1.119:9100/',
 	baseUrlNew: 'http://192.168.1.117:8090',
-	// baseUrlNew: 'http://api1.eliangeyun.com/',
 	h5Appid: 'wxb66b599f7f61b46f',
 	debug: false
 }

+ 4 - 0
main.js

@@ -9,8 +9,12 @@ import uView from '@/uni_modules/uview-ui'
 
 import baseApi from '@/util/base.js'
 import request from '@/util/request.js'
+import utils from '@/util/util.js'
+import webim from 'webim.js';
 Vue.prototype.$api = baseApi
 Vue.prototype.$request = request
+Vue.prototype.$utils = utils
+Vue.prototype.$socket = webim;
 
 Vue.prototype.$store = store
 

+ 3 - 32
pages/index/index.vue

@@ -14,40 +14,11 @@
 			}
 		},
 		onLoad() {
-
+			let _isHave = this.$utils.getRoles('aaa')
+			console.log(_isHave)
 		},
 		methods: {
-			// get/post请求
-			// test(){
-			// 	// 发出post,假设需要带上token
-			// 	postMenu({ custom: { auth: true }}).then(() => {
-					
-			// 	}).catch(() =>{
-					
-			// 	})
-				
-			// 	// await等待,注意与async结合使用
-			// 	await postMenu({ custom: { auth: true }})
-				
-			// 	// 假设不需要在响应拦截器中自动弹出的toast,以及不想写catch(如果promise中进行reject,但是却没有catch的话会报错)
-			// 	postMenu({ custom: { auth: true, toast: false, catch: false }}).then(() => {
-					
-			// 	})
-				
-			// 	// get请求
-			// 	getMenu({ custom: { auth: true }}).then(() => {
-					
-			// 	}).catch(() =>{
-					
-			// 	})
-				
-			// 	// 也可以直接通过uni.$u.post发出请求,注意此处需要写上接口地址
-			// 	uni.$u.http.post('/common/menu', { custom: { auth: true }}).then(() => {
-					
-			// 	}).catch(() =>{
-					
-			// 	})
-			// }
+		
 		}
 	}
 </script>

+ 18 - 19
pages/public/login.vue

@@ -14,7 +14,7 @@
 			</u-code>
 		</u--form>
 		<u-button type="primary" text="提交" customStyle="margin-top: 50px" @click="submit"></u-button>
-
+		<u-loading-page :loading="isLoading" bg-color="#e8e8e8"></u-loading-page>
 	</view>
 </template>
 
@@ -23,7 +23,7 @@
 	export default {
 		data() {
 			return {
-
+				isLoading: false,
 				disabled1: false,
 				tips: '',
 				showCalendar: false,
@@ -75,27 +75,26 @@
 				// 如果有错误,会在catch中返回报错信息数组,校验通过则在then中返回true
 				this.$refs.form1.validate().then(res => {
 					uni.$u.toast('校验通过')
-					debugger
+					this.isLoading = true
 					that.$request.baseRequest('get', '/commonUser/loginVerifyCode', {
 							phone: that.model1.phone,
 							verifyCode: that.model1.code
 						}).then(res => {
-								that.$request.TokenRequest('post', '/commonUser/api/loginQuickly', {
-									mobilePhone:that.model1.phone,
-									veriCode: that.model1.code
-								}).then(res1 => {
-									debugger
-										uni.setStorageSync('pcUserInfo', res1.data)
-										uni.setStorageSync('userInfo', res.data)
-										helper.getListByUserId()
-										that.$store.commit('login', res.data)
-										// that.liangxinLogin()
-										uni.switchTab({
-											url: '/pages/index/index'
-										});
-										uni.hideLoading()
-								})
-							 
+							that.$request.TokenRequest('post', '/commonUser/api/loginQuickly', {
+								mobilePhone: that.model1.phone,
+								veriCode: that.model1.code
+							}).then(res1 => {
+								uni.setStorageSync('pcUserInfo', res1.data)
+								uni.setStorageSync('userInfo', res.data)
+								helper.getListByUserId()
+								that.$store.commit('login', res.data)
+								// that.liangxinLogin()
+								uni.switchTab({
+									url: '/pages/index/index'
+								});
+								this.isLoading = false
+							})
+
 						})
 						.catch(res => {
 							uni.showToast({

+ 77 - 0
util/dbUtil.js

@@ -0,0 +1,77 @@
+/** auther: mmm  desc: 缓存最近的消息记录  */
+function queryData(gid) {
+   let list = uni.getStorageSync('msgItem_'+ gid);
+   return new Promise((resolve,reject) =>{
+	   try{
+		    if(list==""){
+				resolve([]);
+				return;
+			}
+	   	    list = JSON.parse(list);
+			list.sort((a, b) => { return a.id - b.id });
+	   }catch(e){
+	   	   reject(e)
+	   }
+	   resolve(list);
+   })
+}
+function initData(list, gid){
+	uni.setStorageSync('msgItem_' + gid, JSON.stringify(list));
+}
+
+function upCanceData(id,gid,obj){
+	let list = uni.getStorageSync('msgItem_'+ gid);
+	if(list==""){
+		let tempItem = [];
+		tempItem.push(JSON.parse(JSON.stringify(obj)));
+		uni.setStorageSync('msgItem_' + gid, JSON.stringify(tempItem));
+		return;
+	}
+	list = JSON.parse(list);
+	for(var i in list){
+		if(list[i].id===id){
+			list.splice(i,1);
+		}
+	}
+	uni.setStorageSync('msgItem_' + gid, JSON.stringify(list));
+}
+
+function upRedData(id,gid,msgContext){
+	let list = uni.getStorageSync('msgItem_'+ gid);
+	if(list==""){
+		let tempItem = [];
+		tempItem.push(JSON.parse(JSON.stringify(obj)));
+		uni.setStorageSync('msgItem_' + gid, JSON.stringify(tempItem));
+		return;
+	}
+	list = JSON.parse(list);
+	for(var i in list){
+		if(list[i].id===id){
+			list[i].msgContext = msgContext;
+		}
+	}
+	uni.setStorageSync('msgItem_' + gid, JSON.stringify(list));
+}
+
+function upData(obj, gid){
+	let list = uni.getStorageSync('msgItem_'+ gid);
+	if(list==""){
+		let tempItem = [];
+		tempItem.push(JSON.parse(JSON.stringify(obj)));
+		uni.setStorageSync('msgItem_' + gid, JSON.stringify(tempItem));
+		return;
+	}
+	list = JSON.parse(list);
+	if(list.length>=10){
+		list.splice(0,1);
+	}
+    list.push(JSON.parse(JSON.stringify(obj)));
+	uni.setStorageSync('msgItem_' + gid, JSON.stringify(list));
+}
+export {
+	initData,
+    queryData,
+    upData,
+	upRedData,
+	upCanceData
+}

+ 1 - 2
util/request.js

@@ -19,7 +19,7 @@ const baseRequest = (method, url, data,header) => {
 		}
 		let promise = new Promise(function(resolve, reject) {
 			uni.request(baseDefaultOpts).then(
-				(res) => {debugger
+				(res) => {
 					console.log(JSON.stringify(res[1].data))
 					if(res[1].data.code == '200' || res[1].data.code == 200){
 						// 后端返回的状态码100为成功状态,成功则返回请求结果,在app调试时可以通过console.log(JSON.stringify(res[1].data))来查看返回值(以项目实际情况为准)
@@ -51,7 +51,6 @@ const TokenRequest = (method, url, data,header) => {
 	if (header) {
 		contentheader = header
 	}
-	debugger
 	let ac_token = "";
 	uni.getStorage({
 		key: 'userInfo',

+ 16 - 0
util/util.js

@@ -0,0 +1,16 @@
+const utils = {
+		getRoles: function(role) {
+				let _roles = uni.getStorageSync('rolesList')
+				for (let i = 0; i < _roles.length; i++) {
+					if (_roles[i] == role) {
+						return true
+					}
+				}
+				return false
+			},
+}
+
+module.exports = {
+	getRoles: utils.getRoles,
+	
+}

+ 965 - 0
webim.js

@@ -0,0 +1,965 @@
+import packetCode from './PacketCodeC.js'
+import store from './store/index.js'
+import SKIMSDK from './websocket_sdk.js'
+import { queryData, upData, initData } from './util/dbUtil.js'
+const EventDispatcher = function() {
+	this.listeners = {}
+}
+let eventDispatcher
+const WEBIM = {
+	resource: "web",
+	/*单聊标识*/
+	CHAT: "chat",
+	/*群聊标识*/
+	GROUPCHAT: "groupchat",
+	token: null,
+	userId: null,
+	nickName: "",
+	isReadDel: 0,
+	/*用户 jid 10004541/web */
+	userIdStr: null,
+	/*服务器连接地址 ws://localhost:5260 */
+	serverUrl: null,
+	server: null,
+	/*消息超时 时间 默认 15 秒*/
+	sendTimeOut: 15,
+	/*等待消息回执的 消息Id 数组*/
+	waitReceiptMessageIds: {},
+	heartCheck: false,
+	isReconnection: false,
+	options: null,
+	showLoginDialog:false,
+	/*初始化*/
+	initWebIM: function(serverUrl, heartCheck, isReconnection) {
+		console.log('【initWebIM】初始化')
+		WEBIM.heartCheck = heartCheck;
+		WEBIM.isReconnection = isReconnection;
+		WEBIM.serverUrl = serverUrl;
+		WEBIM.options = {
+			url: serverUrl,
+			success(res) {},
+			fail() {}
+		}
+		eventDispatcher = new EventDispatcher();
+
+		WEBIM.server = new SKIMSDK({
+			heartCheck: heartCheck,
+			isReconnection: isReconnection,
+		});
+		WEBIM.server.initWebSocket(WEBIM.options);
+
+		WEBIM.server.onReceivedMsg(event => {
+			let packet = packetCode.decode(event.data);
+			let command = packet.command;
+			eventDispatcher.dispatchEvent(command, toJSON(packet))
+			eventDispatcher.removeListener(command, toJSON(packet))
+			let name = 'pushRes';
+			let value = packet;
+			if (command === -10) {
+				store.commit('$uStore', {
+					name,
+					value
+				});
+			}
+			if(packet&&!packet.success){
+				// this.liangxinLogin()
+			}
+		});
+		WEBIM.server.onNetworkChange(WEBIM.options);
+		WEBIM.server.onSocketClosed(WEBIM.options)
+	},
+	liangxinLogin(){
+		const that = this
+		var userInfoTmp = uni.getStorageSync("userInfo")
+		if(userInfoTmp.phone){
+			that.login(userInfoTmp.phone, "123456", null, res=>{
+				console.log('粮信登录',res)
+				if (res.success) {
+					that.showLoginDialog = false
+					// 缓存用户
+					that.userData = res.response.data
+					console.log('userData',that.userData)
+					let name = 'userData';
+					let value = that.userData;
+					store.commit('$uStore', {
+						name,
+						value
+					});
+					// 	缓存通讯录
+					that.listGuests(that.userData.user.operId, res => {						
+						// #ifdef APP-PLUS
+						createFSQL(that.userData.user.operId).then();
+						let contact = res.response.data;
+						contact.forEach(c=>{
+							c.members.forEach(m=>{
+								m.name = c.name;
+								addFSQL(m, that.userData.user.operId).then();
+							})
+						})
+						// #endif
+						let name = 'firendItem';
+						let value = res.response.data;
+						store.commit('$uStore', {
+							name,
+							value
+						});
+					});
+					
+					// 缓存消息列表
+					that.queryOnlineMessage(that.userData.user.operId,q =>{
+						let data = q.response.data;
+						for(var i in data){
+							initData(data[i].groupMsg.list, data[i].groupInfo.chatId);
+						}
+					})
+					
+					//	缓存链接
+					that.getLinks(that.userData.user.operId, res=>{
+						let name = 'linkItem';
+						let value = res.response.data;
+						store.commit('$uStore', {
+							name,
+							value
+						});
+					});
+					
+					
+					// // 跳转到消息列表
+					// that.$u.route({
+					// 	url: 'pages/home/home',
+					// 	type: 'switchTab'
+					// });
+				} else {
+				  uni.showModal({
+					title:res.reason + ",请稍后再试",
+					showCancel:false
+				  })
+				}
+			});
+		}
+		else if(!WEBIM.showLoginDialog){
+			let pages = getCurrentPages();
+			let curPage = pages[pages.length-1];
+			if(curPage.$page.fullPath != '/pages/public/login'
+			&& curPage.$page.fullPath != '/pages/public/login_account_number'
+			&& curPage.$page.fullPath != '/pages/public/register'
+			&& curPage.$page.fullPath != '/pages/public/code'
+			 && curPage.$page.fullPath != '/pages/public/reset'
+			 && curPage.$page.fullPath != '/pages/index/index'
+			 && curPage.$page.fullPath != '/pages/sale/index'
+			 && curPage.$page.fullPath != '/pages/sale/information'
+			 && curPage.$page.fullPath.indexOf('/pages/sale/webview') == -1  )
+			{
+				uni.clearStorageSync();
+				let name = 'hasLogin';
+				let value = false;
+				store.commit('$uStore', {
+					name,
+					value
+				});
+				WEBIM.showLoginDialog = true
+				uni.navigateTo({
+					url:'/pages/public/login'
+				})
+			}
+		}
+		
+	},
+	disconnect: function(e) {
+		WEBIM.server.closeWebSocket()
+	},
+	isConnect: function() {
+		return WEBIM.server._isLogin;
+	},
+	login: (username, password, code, func) => {
+		let requestPacket = {
+			username,
+			password,
+			code: null,
+			version: 1,
+			command: 1
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('2', func)
+	},
+	register: (phone, password, nickname, func) => {
+		let p = {
+			phone,
+			password,
+			nickname,
+			version:1,
+			command:49
+		}
+		send(p)
+		eventDispatcher.addListener('50', func)
+	},
+
+	heartTest: (userId, func) => {
+		let packet = {
+			userId,
+			version: 1,
+			command: 17
+		}
+		send(packet)
+		eventDispatcher.addListener('18', func)
+	},
+
+	send2Group: (toGroupId, userId, message, msgType, func) => {
+		let requestPacket = {
+			toGroupId,
+			userId,
+			msgType,
+			message,
+			version: 1,
+			command: 15
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('16', func)
+	},
+	send2Friend: (toUserId, userId, message, msgType, func) => {
+		let requestPacket = {
+			userId,
+			toUserId,
+			msgType,
+			message,
+			version: 1,
+			command: 3
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('4', func)
+	},
+	logout: (userId, func) => {
+		let requestPacket = {
+			userId,
+			version: 1,
+			command: 5
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('6', func)
+	},
+
+	createGroup: (userIdList, defaultGroupName, userId, func) => {
+		let requestPacket = {
+			userId,
+			userIdList,
+			defaultGroupName,
+			version: 1,
+			command: 7
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('8', func)
+	},
+
+	queryMembers: (groupId, userId, func) => {
+		let requestPacket = {
+			groupId,
+			userId,
+			version: 1,
+			command: 9
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('10', func)
+	},
+
+	getLastMessage: (id, chatId, userId, chatType, func) => {
+		let requestPacket = {
+			id: id,
+			chatId,
+			userId,
+			chatType,
+			version: 1,
+			command: 45
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('46', func)
+	},
+
+	joinGroup: (groupId, ids, userName, func) => {
+		let requestPacket = {
+			groupId,
+			userIds: ids,
+			currentUsername: userName,
+			version: 1,
+			command: 11
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('12', func)
+	},
+	delGroupMember: (groupId, ids, func) => {
+		let requestPacket = {
+			groupId,
+			userIds: ids,
+			version: 1,
+			command: 13
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('14', func)
+	},
+	transferGroup: (groupId, userId, func) => {
+		let requestPacket = {
+			groupId,
+			userId,
+			version: 1,
+			command: 53
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('54', func)
+	},
+	getGroups: (condition, userId, func) => {
+		let requestPacket = {
+			condition,
+			userId,
+			version: 1,
+			command: 25
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('26', func)
+	},
+
+	listGuests: (userId, func) => {
+		let packet = {
+			userId,
+			version: 1,
+			command: 47
+		}
+		send(packet)
+		eventDispatcher.addListener('48', func)
+	},
+
+	queryFriendMessages: (toUserId, userId, pageNum, func) => {
+		let requestPacket = {
+			userId,
+			pageNum,
+			toUserId,
+			pageSize: 10,
+			version: 1,
+			command: 27
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('28', func)
+	},
+	
+	getFriendMessageByCondition: (toUserId, userId, pageNum, condition, func) => {
+		let requestPacket = {
+			userId,
+			condition,
+			pageNum,
+			toUserId,
+			pageSize: 5,
+			version: 1,
+			command: 27
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('28', func)
+	},
+	queryGroupMessages: (toGroupId, userId, pageNum, func) => {
+		let requestPacket = {
+			toGroupId,
+			pageNum,
+			pageSize: 10,
+			userId,
+			version: 1,
+			command: 23
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('24', func)
+	},
+	getGroupMessageByCondition: (toGroupId, userId, pageNum, condition, func) => {
+		let requestPacket = {
+			toGroupId,
+			pageNum,
+			condition,
+			pageSize: 5,
+			userId,
+			version: 1,
+			command: 23
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('24', func)
+	},
+
+	queryChats: (condition, userId, func) => {
+		let requestPacket = {
+			condition,
+			userId,
+			pageNum: -1,
+			pageSize: -1,
+			version: 1,
+			command: 19
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('20', func)
+	},
+	updateNickName: (userId, nickName, func) => {
+		let requestPacket = {
+			userId,
+			nickName,
+			version: 1,
+			command: 79
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('80', func)
+	},
+	getBusinessCard: (userId, func) => {
+		let requestPacket = {
+			userId,
+			version: 1,
+			command: 65
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('66', func)
+	},
+	createChatList: (userId, groupId, message, msgType, func) => {
+		let requestPacket = {
+			userId,
+			groupId,
+			msgType,
+			message,
+			version: 1,
+			command: 61
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('62', func)
+	},
+	randomSmsCode: (phone, func) => {
+		let req = {
+			userId: '5f6d9d98',
+			phone,
+			version: 1,
+			command: 63
+		}
+		send(req)
+		eventDispatcher.addListener('64', func)
+	},
+	getCustomerServiceList: (userId, func) => {
+		let requestPacket = {
+			userId,
+			version: 1,
+			command: 93
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('94', func)
+	},
+	deleteEmontion: (userId, motionId, func) => {
+		let requestPacket = {
+			userId,
+			motionId,
+			version: 1,
+			command: 95
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('96', func)
+	},
+	stopAudio: (userId, chatId, chatType, func) => {
+		let requestPacket = {
+			userId,
+			chatId,
+			chatType,
+			method: 21,
+			version: 1,
+			command: 21
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('22', func)
+	},
+	queryGroupUser: (userId, groupId, func) => {
+		let requestPacket = {
+			userId,
+			groupId,
+			method: 17,
+			version: 1,
+			command: 21
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('22', func)
+	},
+	getUserRemark: (userId, friendUserId, func) => {
+		let requestPacket = {
+			friendUserId,
+			userId,
+			method: 10,
+			version: 1,
+			command: 21
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('22', func)
+	},
+	updateAvatar: (userId, avatar, func) => {
+		let requestPacket = {
+			userId,
+			avatar,
+			version: 1,
+			command: 97
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('98', func)
+	},
+	getUserById: (userId, func) => {
+		let requestPacket = {
+			userId,
+			version: 1,
+			command: 65
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('66', func)
+	},
+	deleteGroupMsg: (userId, msgId, groupId, func) => {
+		let requestPacket = {
+			userId,
+			msgId,
+			groupId,
+			method: 5,
+			version: 1,
+			command: 81
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('82', func)
+	},
+	deleteFriendMsg: (userId, msgId, friendId, func) => {
+		let requestPacket = {
+			userId,
+			msgId,
+			friendId,
+			version: 1,
+			command: 73
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('74', func)
+	},
+	updateRemarkName: (userId, friendUserId, remarkName, func) => {
+		let requestPacket = {
+			userId,
+			friendUserId,
+			remarkName,
+			method: 7,
+			version: 1,
+			command: 21
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('22', func)
+	},
+	updatePassword: (userId, username, password, func) => {
+		let requestPacket = {
+			userId,
+			username,
+			password,
+			version: 1,
+			command: 77
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('78', func)
+	},
+	uploadContact: (name, phone, userId, func) => {
+		let requestPacket = {
+			name,
+			phone,
+			userId,
+			method: 9,
+			version: 1,
+			command: 21
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('22', func)
+	},
+	freshCode: (func) => {
+		let requestPacket = {
+			method: 4,
+			version: 1,
+			command: 21
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('22', func)
+	},
+	delChat: (userId, chatId, func) => {
+		let requestPacket = {
+			userId,
+			chatId,
+			version: 1,
+			command: 83
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('84', func)
+	},
+	updateGroupNick: (userId, groupId, nickName, func) => {
+		let requestPacket = {
+			userId,
+			groupId,
+			nickName,
+			version: 1,
+			command: 79
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('80', func)
+	},
+	attend: (chat, userId, func) => {
+		let requestPacket = {
+			userId,
+			chat,
+			version: 1,
+			command: 75
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('76', func)
+	},
+	queryMsgByChatId: (msgId, groupId, userId, func) => {
+		let requestPacket = {
+			userId,
+			msgId,
+			groupId,
+			version: 1,
+			command: 69
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('70', func)
+	},
+	addEmoticon(userId, avatar, func) {
+		let requestPacket = {
+			userId,
+			avatar,
+			version: 1,
+			command: 71
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('72', func)
+	},
+	getEmoticons(userId, func) {
+		let requestPacket = {
+			userId,
+			version: 1,
+			command: 85
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('86', func)
+	},
+	updateGroupName: (userId, groupId, groupName, func) => {
+		let requestPacket = {
+			userId,
+			groupId,
+			groupName,
+			version: 1,
+			command: 91
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('92', func)
+	},
+	clearGroupMsg: (userId, groupId, func) => {
+		let requestPacket = {
+			userId,
+			groupId,
+			version: 1,
+			command: 87
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('88', func)
+	},
+	openChat: (chatId, userId, chatType, func) => {
+		let requestPacket = {
+			userId,
+			chatId,
+			chatType,
+			version: 1,
+			command: 39
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('40', func)
+	},
+	getMoneys(userId, pageNum, func) {
+		let requestPacket = {
+			pageNum,
+			pageSiz: 5,
+			userId,
+			version: 1,
+			command: 41
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('42', func)
+	},
+	queryNotice(userId, groupId, func) {
+		let requestPacket = {
+			userId,
+			groupId,
+			action: 'query',
+			version: 1,
+			command: 43
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('44', func)
+	},
+	updateNotice(userId, groupId, context, func) {
+		let requestPacket = {
+			userId,
+			groupId,
+			action: 'update',
+			context,
+			version: 1,
+			command: 43
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('44', func)
+	},
+	removeGroupUser(userIds, groupId, func) {
+		let requestPacket = {
+			userIds,
+			groupId,
+			version: 1,
+			command: 51
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('52', func)
+	},
+	
+	insertFriend(userId, friendId, func) {
+		let requestPacket = {
+			userId,
+			friendId,
+			version: 1,
+			command: 55
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('56', func)
+	},
+	// 查找用户
+	findFriendRequestList: (nickName, func) => {
+		let requestPacket = {
+			nickName,
+			version: 1,
+			command: 89
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('90', func)
+	},
+	// 查看新朋友列表
+	queryFriendRequestList(userId, func) {
+		let requestPacket = {
+			userId,
+			version: 1,
+			command: 57
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('58', func)
+	},
+	// 同意好友请求
+	AcceptFriendRequest(friendId, userId, func) {
+		let requestPacket = {
+			friendId,
+			userId,
+			version: 1,
+			command: 59
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('60', func)
+	},
+	
+	queryPostsReq: (userId, pageNum, func) => {
+		let requestPacket = {
+			pageNum,
+			pageSize: 10,
+			userId,
+			version: 1,
+			command: 106
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('107', func)
+	},
+	
+	createPostReq: (userId, postContext, urls, func) => {
+		let requestPacket = {
+			postContext,
+			urls,
+			pageSize: 10,
+			userId,
+			version: 1,
+			command: 102
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('103', func)
+	},
+	
+	toFabulousRes: (id, userId, postId, func) => {
+		let requestPacket = {
+			id,
+			postId,
+			pageSize: 10,
+			userId,
+			version: 1,
+			command: 108
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('109', func)
+	},
+	
+	toCommentReqPacket: (id, userId, postId, comment, func) => {
+		let requestPacket = {
+			id,
+			postId,
+			comment,
+			pageSize: 10,
+			userId,
+			version: 1,
+			command: 104
+		}
+		send(requestPacket)
+		eventDispatcher.addListener('105', func)
+	},
+	getLinks: (userId, func) => {
+		let packet = {
+			userId,
+			link: {
+				title:'看一看'
+			},
+			version: 1,
+			command: 110
+		}
+		send(packet)
+		eventDispatcher.addListener('111', func)
+	},
+	createMessage: (message, msgType, toGroupId, func) => {
+		let p ={
+			toGroupId,
+			msgType,
+			message,
+			version: 1,
+			command: 120
+		}
+		send(p)
+		eventDispatcher.addListener('121', func)
+	},
+	robRedPacket: (func) =>{
+		let p = {
+			version: 1,
+			command:118
+		}
+		send(p)
+		eventDispatcher.addListener('119', func)
+	},
+	createRedPacket: (func) =>{
+		let p ={
+			version: 1,
+			command:116
+		}
+		send(p)
+		eventDispatcher.addListener('117', func)
+	},
+	addFaceUser: (userId, faceId, func)=> {
+		let p = {
+			userId,
+			faceId,
+			version: 1,
+			command: 121
+		}
+		send(p)
+		eventDispatcher.addListener('122', func)
+	},
+	listFaces: (keyword, func)=> {
+		let p = {
+			keyword,
+			version: 1,
+			command: 123
+		}
+		send(p)
+		eventDispatcher.addListener('124', func)
+	},
+	listBanner:(func)=>{
+		let p = {
+			version: 1,
+			command: 125
+		}
+		send(p)
+		eventDispatcher.addListener('126', func)
+	},
+	joinRoom:(groupIds, func) =>{
+		let p={
+			groupIds,
+			version: 1,
+			command: -1
+		}
+		send(p)
+		eventDispatcher.addListener('-2', func)
+	},
+	quitRoom:(groupIds, func) =>{
+		let p={
+			groupIds,
+			version: 1,
+			command: -3
+		}
+		send(p)
+		eventDispatcher.addListener('-4', func)
+	},
+	queryOnlineMessage(userId, func){
+		let p={
+			userId,
+			version: 1,
+			command: -7
+		}
+		send(p)
+		eventDispatcher.addListener('-6', func)
+	}
+}
+
+function toJSON(packet) {
+	return JSON.parse(JSON.stringify(packet))
+}
+
+EventDispatcher.prototype.addListener = function(eventKey, fun, context) {
+	let list = []
+	this.listeners[eventKey] = list
+	let listener = {
+		func: fun,
+		context: context
+	}
+	list.push(listener)
+	return listener
+}
+
+EventDispatcher.prototype.removeListener = function(eventKey, fun, context) {
+	let list = this.listeners[eventKey]
+	if (list !== undefined) {
+		let size = list.length
+		for (let i = 0; i < size; i++) {
+			let listener = list[i]
+			if (listener.func === fun && listener.context === context) {
+				list.splice(i, 1)
+				return
+			}
+		}
+	}
+}
+
+EventDispatcher.prototype.dispatchEvent = function(eventKey, event) {
+	let list = this.listeners[eventKey]
+	if (list !== undefined) {
+		let size = list.length
+		for (let i = 0; i < size; i++) {
+			let listener = list[i]
+			let fun = listener.func
+			let context = listener.context
+			if (context != null) {
+				fun.call(context, event)
+			} else {
+				fun(event)
+			}
+		}
+	}
+}
+
+let send = (p) => {
+	p.token = store.state.userData.token;
+	console.log('【websocket】send  ' + p.token)
+	console.log(p)
+	WEBIM.server.sendWebSocketMsg({
+		data: p,
+		success(res) {
+			console.log('【websocket】发送成功')
+			
+			uni.hideLoading()
+		},
+		fail(err) {
+			console.log('【websocket】发送失败')
+			console.log(err)
+			
+			uni.hideLoading()
+		}
+	});
+}
+
+export default WEBIM

+ 420 - 0
websocket_sdk.js

@@ -0,0 +1,420 @@
+import packetCode from './PacketCodeC.js'
+import store from './store/index.js'
+import * as config from './config'
+import helper from '@/common/helper.js'; 
+export default class Websocket {
+    constructor({
+        heartCheck,
+        isReconnection
+    }) {
+        // 是否连接
+        this._isLogin = false;
+        // 当前网络状态
+        this._netWork = true;
+        // 是否人为退出
+        this._isClosed = false;
+        // 心跳检测频率
+        this._timeout = 3000;
+        this._timeoutObj = null;
+        this._timeoutObj1 = null;
+        // 当前重连次数
+        this._connectNum = 0;
+        // 心跳检测和断线重连开关,true为启用,false为关闭
+        this._heartCheck = heartCheck;
+        this._isReconnection = isReconnection;
+		this._showLoginDialog = true
+        // this._onSocketOpened();
+    }
+    // 心跳重置
+    _reset() {
+        clearTimeout(this._timeoutObj);
+        clearTimeout(this._timeoutObj1);
+        return this;
+    }
+    // 心跳开始
+    _start(options) {
+        let _this = this;
+        this._timeoutObj = setInterval(() => {
+            //发送心跳
+            _this.sendHeartbeatData(options);
+			_this.getInfo()
+        }, this._timeout);
+		this._timeoutObj1 = setInterval(() => {
+			_this.getTips()
+		}, 1000*60);
+    }
+    // 监听websocket连接关闭
+    onSocketClosed(options) {
+		uni.onSocketError(err => {
+			console.log('当前websocket连接已关闭,错误信息为:' + JSON.stringify(err));
+			// 停止心跳连接
+			if (this._heartCheck) {
+			    this._reset();
+			}
+			// 关闭已登录开关
+			this._isLogin = false;
+			// 检测是否是用户自己退出小程序
+			console.log('------------------开启重连--------------------------------')
+			if (!this._isClosed) {
+			    // 进行重连
+			    if (this._isReconnection) {
+			        this._reConnect(options)
+			    }
+			}
+			
+		})
+        uni.onSocketClose(err => {
+        })
+    }
+    // 检测网络变化
+    onNetworkChange(options) {
+        uni.onNetworkStatusChange(res => {
+            console.log('当前网络状态:' + res.isConnected);
+            if (!this._netWork) {
+                this._isLogin = false;
+                // 进行重连
+                if (this._isReconnection) {
+                    this._reConnect(options)
+                }
+            }
+        })
+    }
+    _onSocketOpened(options) {
+        uni.onSocketOpen(res => {
+            console.log('【websocket】已打开');
+            // 打开已登录开关
+            this._isLogin = true;
+            // 发送心跳
+            if (this._heartCheck) {
+                this._reset()._start(options);
+            }
+            // 发送登录信息
+            this.sendLoginData();
+            // 打开网络开关
+            this._netWork = true;
+        })
+    }
+    // 接收服务器返回的消息
+    onReceivedMsg(callBack) {
+        uni.onSocketMessage(event => {
+            if (typeof callBack == "function") {
+                callBack(event)
+            } else {
+                console.log('参数的类型必须为函数')
+            }
+        })
+    }
+
+    // 建立websocket连接
+    initWebSocket(options) {
+        let _this = this;
+        if (this._isLogin) {
+            console.log("您已经登录了");
+        } else {
+            // 检查网络
+            uni.getNetworkType({
+                success(result) {
+                    if (result.networkType != 'none') {
+                        // 开始建立连接
+                        console.log('建立websocket连接' + options.url);
+                        uni.connectSocket({
+                            url: options.url,
+                            success(res) {
+                                if (typeof options.success == "function") {
+                                    options.success(res)
+                                    _this._onSocketOpened(options);
+                                } else {
+                                    console.log('参数的类型必须为函数')
+                                }
+                            },
+                            fail(err) {
+                                if (typeof options.fail == "function") {
+                                    options.fail(err)
+                                } else {
+                                    console.log('参数的类型必须为函数')
+                                }
+                            }
+                        })
+                    } else {
+                        console.log('网络已断开');
+                        _this._netWork = false;
+                        // 网络断开后显示model
+                        // uni.showModal({
+                        //     title: '网络错误',
+                        //     content: '请重新打开网络',
+                        //     success: function(res) {
+                        //         if (res.confirm) {
+                        //             console.log('用户点击确定')
+                        //         }
+                        //     }
+                        // })
+						uni.showToast({
+							title: "网络错误 请重新打开网络",
+							icon: 'none'
+						})
+                    }
+                }
+            })
+        }
+    }
+    // 发送websocket消息
+    sendWebSocketMsg(options) {
+        this.sendBinary(1,options);
+    }
+
+    //发送心跳连接
+    sendHeartbeatData(options) {
+		var that = this
+		let packet = {
+		  version: 1,
+		  command: 17,
+		  token: store.state.userData.token
+		}
+		this.sendBinary(99, {
+		    data: packet,
+		    success(res) {
+		      // console.log('【websocket】心跳连接成功');
+			  if(!that._showLoginDialog){
+				  that._showLoginDialog= true
+			  }
+		    },
+		    fail(err) {
+		        console.log('【websocket】心跳连接失败');
+		        console.log(err)
+		        console.log('this._showLoginDialog',that._showLoginDialog )
+				uni.hideLoading()
+				that._isLogin = false
+				that._reConnect(options)
+		    }
+		});
+		
+		
+    }
+	//发送第一次连接数据
+    sendLoginData() {
+        this.sendBinary(99, {
+            data: {},
+            success(res) {
+                console.log('【websocket】第一次连接成功')
+            },
+            fail(err) {
+                console.log('【websocket】第一次连接失败')
+                console.log(err)
+            }
+        });
+        // this.sendBinary(99, {});
+        // socket.sendSocketMessage({
+        //  // 这里是第一次建立连接所发送的信息,应由前后端商量后决定
+        //  data: JSON.stringify({
+        //      "key": 'value'
+        //  })
+        // })
+    }
+
+    // 重连方法,会根据时间频率越来越慢
+    _reConnect(options) {
+        let timer, _this = this;
+        if (this._connectNum < 20) {
+            timer = setTimeout(() => {
+                this.initWebSocket(options)
+            }, 500)
+            this._connectNum += 1;
+        } else if (this._connectNum < 50) {
+            timer = setTimeout(() => {
+                this.initWebSocket(options)
+            }, 1000)
+            this._connectNum += 1;
+        } else {
+            timer = setTimeout(() => {
+                this.initWebSocket(options)
+            }, 3000)
+            this._connectNum += 1;
+        }
+    }
+    // 关闭websocket连接
+    closeWebSocket() {
+        uni.closeSocket();
+        this._isClosed = true;
+    }
+
+    //发送二进制
+    sendBinary(commendType, options) {
+        uni.sendSocketMessage({
+            data: packetCode.encode(options.data),
+            success(res) {
+                if (typeof options.success == "function") {
+                    options.success(res)
+                } else {
+                    console.log('参数的类型必须为函数')
+                }
+            },
+            fail(err) {
+                if (typeof options.fail == "function") {
+                    options.fail(err)
+                } else {
+                    console.log('参数的类型必须为函数')
+                }
+            }
+        });
+    }
+	getTips(){
+		return new Promise(resolve => {
+			let baseUrl = config.def().baseUrl
+			let baseUrlNew = config.def().baseUrlNew
+			var userInfo
+			if (!userInfo || !userInfo.accessToken) {
+				userInfo = uni.getStorageSync('userInfo')
+			}
+			var pcUserInfo=uni.getStorageSync('pcUserInfo')
+			if(!pcUserInfo && userInfo){
+				uni.request({
+					url: baseUrlNew + '/commonUser/api/loginQuickly',
+					data: {
+						mobilePhone: userInfo.phone,
+						veriCode: "123456",
+					},
+					method: 'POST',
+					success: (res) => {						
+						if (res.statusCode === 200) {
+							uni.setStorageSync('pcUserInfo', res.data)
+							helper.getListByUserId()
+						}
+						else{
+							uni.request({
+								url: baseUrlNew + '/commonUser/api/loginQuickly',
+								data: {
+									mobilePhone: "13333333333",
+									veriCode: "123456",
+								},
+								method: 'POST',
+								success: (res) => {						
+									if (res.statusCode === 200) {
+										uni.setStorageSync('pcUserInfo', res.data)
+										helper.getListByUserId()
+									}
+								}
+							})
+						}
+					}
+				})
+			}
+			uni.request({
+			    url: baseUrlNew + '/notice/query/noticeNumber',
+			    data: {
+			    	
+			    },
+			    method: 'GET',
+			    success: (res) => {			
+					if (res.data.data) {
+			    		let name = 'myTip';
+			    		let value = res.data.data.task;
+			    		store.commit('$uStore', {
+			    			name,
+			    			value
+			    		});
+						if(value != 0&&value){
+							uni.setTabBarBadge({
+								index:4,
+								text:value+""
+							})
+						}
+			    		name = 'taskTip';
+			    		value = res.data.data.task;
+			    		store.commit('$uStore', {
+			    			name,
+			    			value
+			    		});
+			    		// name = 'contractTip';
+			    		// value = res.data.data.contractTip;
+			    		// store.commit('$uStore', {
+			    		// 	name,
+			    		// 	value
+			    		// });
+			    	}
+			    }
+			})
+			
+			// let accessToken = userInfo ? userInfo.accessToken : ''
+			// var data = {}
+			// var _mt = 'getTips'
+			// var _gp = 'integral'
+			// uni.request({
+			// 	url: baseUrl + '/m.api',
+			// 	data: {
+			// 		...data,
+			// 		_gp,
+			// 		_mt
+			// 	},
+			// 	method: 'POST',
+			// 	header: {
+			// 		'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
+			// 		'ACCESSTOKEN': accessToken
+			// 	},
+			// 	success: (res) => {						
+			// 		if (res.statusCode === 200) {
+			// 			let name = 'myTip';
+			// 			let value = res.data.data.myTips;
+			// 			store.commit('$uStore', {
+			// 				name,
+			// 				value
+			// 			});
+			// 			name = 'taskTip';
+			// 			value = res.data.data.task;
+			// 			store.commit('$uStore', {
+			// 				name,
+			// 				value
+			// 			});
+			// 			name = 'contractTip';
+			// 			value = res.data.data.contract;
+			// 			store.commit('$uStore', {
+			// 				name,
+			// 				value
+			// 			});
+			// 		}
+			// 	}
+			// })
+		})
+	}
+	getInfo(){
+		return new Promise(resolve => {
+			var hour = new Date().getHours();
+			if((hour >= 9 && hour < 12) ||(hour >= 13 && hour < 15)){
+				var infoList = [];
+				uni.request({
+				    url: "https://hq.sinajs.cn/list=C0,C2109,C2111,C2201,C2203,C2205,C2207,A0,A2109,A2111,A2201,A2203,A2205,A2207",
+				    // url: "https://hq.sinajs.cn/list=C2109",
+				    header: {
+				        'content-type': 'application/x-www-form-urlencoded'
+				    },
+				    success: function(result) {
+				        // resolve调用后,即可传递到调用方使用then或者async+await同步方式进行处理逻辑
+						var tmp = result.data.split('"')
+						for(var i = 1; i<tmp.length;i=i+2){
+							var list = tmp[i].split(",")
+							var data = {
+								goodsName:list[0],
+								newPrice:list[6],
+								openPrice:list[2]
+							}
+							if(data.goodsName){
+								infoList.push(data)
+							}
+						}
+						let name = 'infoList';
+						let value = infoList;
+						store.commit('$uStore', {
+							name,
+							value
+						});
+						// console.log("infoList",infoList)
+				    },
+				    fail: function(e) {
+				        console.log('error in...')
+				        // reject调用后,即可传递到调用方使用catch或者async+await同步方式进行处理逻辑
+				        reject(e)
+				    },
+				})
+			}
+		})
+	}
+}