<script>

import { mapGetters, mapActions } from 'vuex';
import IMSDK, { IMMethods, MessageReceiveOptType, MessageType, SessionType } from 'openim-uniapp-polyfill';
import { config } from '@/pages_im/common/config';
import { getDbDir, Igexin, toastWithCallback } from '@/pages_im/util/common.js';

import { conversationSort, secFormat, callingModule, meetingModule, parseMessageByType, prepareConversationState } from '@/pages_im/util/imCommon';
import { PageEvents, UpdateMessageTypes, CustomType, ContactChooseTypes } from '@/pages_im/constant';

import { openImLoginApi } from '@/pages_im/api/imBll';
import NotificationUtil from '@/pages_im/util/notification';
import newMessage from '@/pages_im/static/audio/newMessage.wav';

import { getTlsSig } from '@/api/common.js'
import { checkLogin } from '@/api/user.js'

let cacheConversationList = [];
let updateDownloadTask = null;
let notificationIntance = null;
let pausing = false;
let innerAudioContext;
let notification;
let uPushPlugin;

export default {
	globalData: {
		wsUrl: '',
		appId: 'wx1e6d61497bba00ef'
	},
  onLaunch: function () {
		this.checkUpdate()
		this.initOpenIm();
		
		var that=this;
		uni.$on('refreshIM', () => {
			this.checkLogin();
		});
		var urls="https://17010831189.cdwjyyh.com;https://16946746017.cdwjyyh.com;https://13708196565.cdwjyyh.com;https://1700206673.cdwjyyh.com;https://17233317680.cdwjyyh.com;https://1700575323.cdwjyyh.com;https://17069749252.cdwjyyh.com;https://16973148962.cdwjyyh.com;https://1722131630.cdwjyyh.com;https://17146969562.cdwjyyh.com;https://1695072024.cdwjyyh.com;https://17203639647.cdwjyyh.com;https://16954404159.cdwjyyh.com;https://1707741400.cdwjyyh.com;https://17408937934.cdwjyyh.com;https://17180847536.cdwjyyh.com;https://17244394814.cdwjyyh.com;https://1703101076.cdwjyyh.com;https://17124251670.cdwjyyh.com;https://17017634981.cdwjyyh.com;https://1709430520.cdwjyyh.com;https://17163564434.cdwjyyh.com;https://17168038011.cdwjyyh.com;https://1710609621.cdwjyyh.com;https://1705257092.cdwjyyh.com;https://17211347588.cdwjyyh.com;https://17035647784.cdwjyyh.com;https://1721509816.cdwjyyh.com;https://1720396718.cdwjyyh.com;https://17214936263.cdwjyyh.com;https://1716050799.cdwjyyh.com;https://1713109810.cdwjyyh.com;https://172542243167.cdwjyyh.com;https://172240149208.cdwjyyh.com;https://1702848339.cdwjyyh.com;https://1707911907.cdwjyyh.com;https://1717849419.cdwjyyh.com;https://17038049724.cdwjyyh.com;https://1724650239.cdwjyyh.com;https://1707113459.cdwjyyh.com;https://1715669104.cdwjyyh.com;https://1710051545.cdwjyyh.com;https://1722269330.cdwjyyh.com;https://1710003925.cdwjyyh.com;https://17145545145.cdwjyyh.com;https://1720634288.cdwjyyh.com;https://1696593184.cdwjyyh.com;https://1704962208.cdwjyyh.com;https://1703146177.cdwjyyh.com;https://1704346325.cdwjyyh.com;https://1697387624.cdwjyyh.com;https://1702551094.cdwjyyh.com;https://1720523201.cdwjyyh.com;https://1714391651.cdwjyyh.com;https://16989457834.cdwjyyh.com;https://1710582715.cdwjyyh.com;https://1696073814.cdwjyyh.com;https://1701427000.cdwjyyh.com;https://1703620825.cdwjyyh.com;https://1716954881.cdwjyyh.com;https://1709258681.cdwjyyh.com;https://1702178349.cdwjyyh.com;https://1696037454.cdwjyyh.com;https://1707163288.cdwjyyh.com;https://1698272613.cdwjyyh.com;https://1695736399.cdwjyyh.com;https://1707979666.cdwjyyh.com;https://1699631662.cdwjyyh.com;https://1725584568.cdwjyyh.com;https://1709711499.cdwjyyh.com;https://1707988905.cdwjyyh.com;https://1709289861.cdwjyyh.com;https://1720027873.cdwjyyh.com;https://1723979172.cdwjyyh.com;https://1711804525.cdwjyyh.com;https://1702653210.cdwjyyh.com;https://1711075739.cdwjyyh.com;https://1710979987.cdwjyyh.com;https://1724292527.cdwjyyh.com;https://1704964596.cdwjyyh.com;https://1703840482.cdwjyyh.com;https://1709061808.cdwjyyh.com;https://1718492957.cdwjyyh.com;https://1708829102.cdwjyyh.com;https://1716362553.cdwjyyh.com;https://1710541443.cdwjyyh.com;https://1715811900.cdwjyyh.com;https://1718208786.cdwjyyh.com;https://1704651745.cdwjyyh.com;https://1699759405.cdwjyyh.com;https://1713080422.cdwjyyh.com;https://1715403843.cdwjyyh.com;https://1696900518.cdwjyyh.com;https://1707770189.cdwjyyh.com;https://1700034515.cdwjyyh.com;https://1715466167.cdwjyyh.com;https://1709976677.cdwjyyh.com;https://1712370330.cdwjyyh.com;https://1706087997.cdwjyyh.com;https://1703496196.cdwjyyh.com;https://17122663469.cdwjyyh.com;https://1712318592.cdwjyyh.com;https://1712812440.cdwjyyh.com;https://1715678161.cdwjyyh.com;https://1702028001.cdwjyyh.com;https://17216467850.cdwjyyh.com;https://1696462985.cdwjyyh.com;https://1707192149.cdwjyyh.com;https://17048421512.cdwjyyh.com;https://1723797034.cdwjyyh.com;https://1704429569.cdwjyyh.com;https://17092443255.cdwjyyh.com;https://1722028860.cdwjyyh.com;https://17129467809.cdwjyyh.com;https://1705848887.cdwjyyh.com;https://16945675535.cdwjyyh.com;https://17257464755.cdwjyyh.com;https://1723025937.cdwjyyh.com;https://17234848798.cdwjyyh.com;https://1700104177.cdwjyyh.com;https://17242943219.cdwjyyh.com;https://17262404998.cdwjyyh.com;https://17140341757.cdwjyyh.com;https://17134130421.cdwjyyh.com;https://1723148318.cdwjyyh.com;https://17257455505.cdwjyyh.com;https://17207640127.cdwjyyh.com;https://1709058929.cdwjyyh.com;https://17069353822.cdwjyyh.com;https://1698429582.cdwjyyh.com;https://17253124611.cdwjyyh.com;https://1709158760.cdwjyyh.com;https://17124964042.cdwjyyh.com;https://1707326074.cdwjyyh.com;https://17046524832.cdwjyyh.com;https://1722471447.cdwjyyh.com;https://1715081607.cdwjyyh.com;https://1722709008.cdwjyyh.com;https://1705411096.cdwjyyh.com;https://17221412356.cdwjyyh.com;https://173131762485.cdwjyyh.com;https://17106348388.cdwjyyh.com;https://1703201862.cdwjyyh.com;https://171645204084.cdwjyyh.com;https://17316201102.cdwjyyh.com;https://1714278120.cdwjyyh.com;https://169458141036.cdwjyyh.com;https://16966142587.cdwjyyh.com;https://1720738395.cdwjyyh.com;https://1722208363.cdwjyyh.com;https://169714438661.cdwjyyh.com;https://1717887413.cdwjyyh.com;https://1715113705.cdwjyyh.com;https://16960448580.cdwjyyh.com;https://16961466861.cdwjyyh.com;https://1707853597.cdwjyyh.com;https://1709274679.cdwjyyh.com;https://1722858089.cdwjyyh.com;https://1715419874.cdwjyyh.com;https://17151136007.cdwjyyh.com;https://1722314568.cdwjyyh.com;https://1724746541.cdwjyyh.com;https://1718762128.cdwjyyh.com;https://1720163684.cdwjyyh.com;https://17247470857.cdwjyyh.com;https://1708580403.cdwjyyh.com;https://1705948747.cdwjyyh.com;https://1700682425.cdwjyyh.com;https://170284458903.cdwjyyh.com;https://1725605169.cdwjyyh.com;https://16990645003.cdwjyyh.com;https://16946786637.cdwjyyh.com;https://17083564387.cdwjyyh.com;https://16994525562.cdwjyyh.com;https://1720968292.cdwjyyh.com;https://1710909698.cdwjyyh.com;https://1700467361.cdwjyyh.com;https://16953683561.cdwjyyh.com;https://17258458080.cdwjyyh.com;https://1702911871.cdwjyyh.com";
		var urlList=urls.split(";");
		console.log(this.getRandomInt(0,urlList.length-1))
		var path = urlList[this.getRandomInt(0,urlList.length-1)];
		//path="https://api.cdwjyyh.com";
		//path="https://test.userapp.his.cdwjyyh.com";
		uni.setStorageSync('requestPath',path)
  },
  onUnload() {
  	 
  },
  onShow() {
	uni.getSystemInfo({
	  	success: (result) => {
	  		// 获取手机系统的状态栏高度（不同手机的状态栏高度不同）
	  		// console.log('当前手机的状态栏高度',result.statusBarHeight)
	  		let statusBarHeight = result.statusBarHeight + 'px'
	  		// 获取右侧胶囊的信息 单位px
	  		//#ifndef H5 || APP-PLUS
	  		const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
	  		
	  		//bottom: 胶囊底部距离屏幕顶部的距离
	  		//height: 胶囊高度
	  		//left:   胶囊左侧距离屏幕左侧的距离
	  		//right:  胶囊右侧距离屏幕左侧的距离
	  		//top:    胶囊顶部距离屏幕顶部的距离
	  		//width:  胶囊宽度
	  		// console.log(menuButtonInfo.width, menuButtonInfo.height, menuButtonInfo.top)
	  		// console.log('计算胶囊右侧距离屏幕右边距离', result.screenWidth - menuButtonInfo.right)
	  		let menuWidth = menuButtonInfo.width + 'px'
	  		let menuHeight = menuButtonInfo.height + 'px'
	  		let menuBorderRadius = menuButtonInfo.height / 2 + 'px'
	  		let menuRight = result.screenWidth - menuButtonInfo.right + 'px'
	  		let menuTop = menuButtonInfo.top + 'px'
	  		let contentTop = result.statusBarHeight + 44 + 'px'
	  		let menuInfo = {
	  			statusBarHeight: statusBarHeight,//状态栏高度----用来给自定义导航条页面的顶部导航条设计padding-top使用：目的留出系统的状态栏区域
	  			menuWidth: menuWidth,//右侧的胶囊宽度--用来给自定义导航条页面的左侧胶囊设置使用
	  			menuHeight: menuHeight,//右侧的胶囊高度--用来给自定义导航条页面的左侧胶囊设置使用
	  			menuBorderRadius: menuBorderRadius,//一半的圆角--用来给自定义导航条页面的左侧胶囊设置使用
	  			menuRight: menuRight,//右侧的胶囊距离右侧屏幕距离--用来给自定义导航条页面的左侧胶囊设置使用
	  			menuTop: menuTop,//右侧的胶囊顶部距离屏幕顶部的距离--用来给自定义导航条页面的左侧胶囊设置使用
	  			contentTop: contentTop,//内容区距离页面最上方的高度--用来给自定义导航条页面的内容区定位距离使用
	  		}
	  		uni.setStorageSync('menuInfo', menuInfo)
	  		//#endif
	  	},
	  	fail: (error) => {
	  		console.log(error)
	  	}
	})
  	
  },
  onHide() {
      
  },
  computed: {
  	...mapGetters([
  		'storeConversationList',
  		'storeCurrentConversation',
  		'storeCurrentUserID',
  		'storeSelfInfo',
  		'storeRecvFriendApplications',
  		'storeRecvGroupApplications',
  		'storeHistoryMessageList',
  		'storeIsSyncing',
  		'storeGroupList'
  	]),
  	contactBadgeRely() {
  		return {
  			recvFriendApplications: this.storeRecvFriendApplications,
  			recvGroupApplications: this.storeRecvGroupApplications,
  			userKey: this.storeCurrentUserID
  		};
  	}
  },
  methods: {
	...mapActions('message', ['pushNewMessage', 'updateOneMessage', 'updateQuoteMessageRevoke', 'updateMessageNicknameAndFaceUrl']),
	...mapActions('conversation', ['updateCurrentMemberInGroup']),
	...mapActions('contact', [
		'updateFriendInfo',
		'pushNewFriend',
		'updateBlackInfo',
		'pushNewBlack',
		'pushNewGroup',
		'updateGroupInfo',
		'pushNewRecvFriendApplition',
		'updateRecvFriendApplition',
		'pushNewSentFriendApplition',
		'updateSentFriendApplition',
		'pushNewRecvGroupApplition',
		'updateRecvGroupApplition',
		'pushNewSentGroupApplition',
		'updateSentGroupApplition'
	]),  
	getRandomInt(min, max) {
	    const minCeiled = Math.ceil(min);
	    const maxFloored = Math.floor(max);
	    return Math.floor(Math.random() * (maxFloored - minCeiled + 1) + minCeiled); // 包含最小值和最大值
	},
	checkLogin(){
		var data={};
		checkLogin(data).then(
			res => {
				if(res.code==200){
					this.openImLogin();
				} 
			},
			rej => {}
		);
	},
	checkUpdate() {
		const updateManager = uni.getUpdateManager();
		updateManager.onCheckForUpdate(function(res) {
			// 请求完新版本信息的回调
			console.log('是否有新版本：', res.hasUpdate);
		});

		updateManager.onUpdateReady(function() {
			uni.showModal({
				title: '更新提示',
				content: '新版本已经准备好，是否重启小程序？',
				confirmText: '立即重启',
				confirmColor: '#2179f5',
				success(res) {
					if (res.confirm) {
						// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
						updateManager.applyUpdate();
					}
				}
			});
		});

		updateManager.onUpdateFailed(function() {
			// 新的版本下载失败
			uni.showModal({
				title: '更新提示',
				content: '新版本下载失败，请检查网络后重试。',
				showCancel: false
			});
		});
	},
	initOpenIm() {
		innerAudioContext = uni.createInnerAudioContext();
		innerAudioContext.autoplay = false;
		innerAudioContext.src = newMessage;
		this.setGlobalIMlistener();
		this.tryLogin();
	},
	setGlobalIMlistener() {
		// init
		const kickHander = (message) => {
			toastWithCallback(message, () => {
				uni.setStorageSync('AppToken',null);
				uni.removeStorage({key: "IMToken",});
				uni.removeStorage({key: "IMUserID",});
				uni.removeStorage({key: "IMHasLogin"}); 
				uni.$emit('loginOut');
				//callingModule?.endCall();
				//meetingModule?.endCall();
			});
		};
		
	    let that=this;
		IMSDK.subscribe(IMSDK.IMEvents.OnKickedOffline, (data) => {
			kickHander('您的账号在其他设备登录，请重新登陆！');
			//that.removeImData();
		    //that.openImLogin();
		});
		
		IMSDK.subscribe(IMSDK.IMEvents.OnUserTokenExpired, (data) => {
			//kickHander('您的登录已过期，请重新登陆！');
			that.removeImData();
			that.openImLogin();
		});
		
		IMSDK.subscribe(IMSDK.IMEvents.OnUserTokenInvalid, (data) => {
			//kickHander('您的登录已无效，请重新登陆！');
			that.removeImData();
			that.openImLogin();
		});
	
		// sync
		const syncStartHandler = ({ data }) => {
			this.$store.commit('user/SET_IS_SYNCING', true);
			this.$store.commit('user/SET_REINSTALL', data);
		};
		const syncProgressHandler = ({ data }) => {
			this.$store.commit('user/SET_PROGRESS', data);
		};
		const syncFinishHandler = () => {
			this.$store.dispatch('conversation/getConversationList');
			this.$store.dispatch('contact/getFriendList');
			this.$store.dispatch('contact/getGrouplist');
			this.$store.dispatch('conversation/getUnReadCount');
			this.$store.commit('user/SET_IS_SYNCING', false);
			uni.hideLoading();
		};
		const syncFailedHandler = () => {
			uni.hideLoading();
			uni.$u.toast('同步消息失败');
			this.$store.dispatch('conversation/getConversationList');
			this.$store.dispatch('conversation/getUnReadCount');
			this.$store.commit('user/SET_IS_SYNCING', false);
		};
		IMSDK.subscribe(IMSDK.IMEvents.OnSyncServerStart, syncStartHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnSyncServerFinish, syncFinishHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnSyncServerFailed, syncFailedHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnSyncServerProgress, syncProgressHandler);
	
		// self
		const selfInfoUpdateHandler = ({ data }) => {
			this.$store.commit('user/SET_SELF_INFO', {
				...this.storeSelfInfo,
				...data
			});
			this.updateMessageNicknameAndFaceUrl({
				sendID: data.userID,
				senderNickname: data.nickname,
				senderFaceUrl: data.faceURL
			});
		};
	
		IMSDK.subscribe(IMSDK.IMEvents.OnSelfInfoUpdated, selfInfoUpdateHandler);
	
		// message
		const newMessagesHandler = ({ data }) => {
			if (this.storeIsSyncing) {
				return;
			}
			data.forEach(this.handleNewMessage);
			
		};
		const c2cReadReceiptHandler = ({ data: receiptList }) => {
			if (receiptList[0].userID !== this.storeCurrentConversation.userID) {
				return;
			}
			receiptList.forEach((item) => {
				item.msgIDList.forEach((msgID) => {
					this.updateOneMessage({
						message: {
							clientMsgID: msgID
						},
						type: UpdateMessageTypes.KeyWords,
						keyWords: {
							key: 'isRead',
							value: true
						}
					});
				});
			});
		};
		const groupReadReceiptHandler = ({ data }) => {
			if (data.conversationID !== this.storeCurrentConversation.conversationID) {
				return;
			}
			data.groupMessageReadInfo.map((receipt) => {
				const oldMessage = this.storeHistoryMessageList.find((msg) => msg.clientMsgID === receipt.clientMsgID);
				if (oldMessage) {
					uni.$emit(PageEvents.GroupMessageReceipt, receipt);
					const newMessage = {
						...oldMessage,
						isRead: true,
						attachedInfoElem: {
							...oldMessage.attachedInfoElem,
							groupHasReadInfo: {
								hasReadCount: receipt.hasReadCount,
								unreadCount: receipt.unreadCount
							}
						}
					};
					console.log(newMessage);
					this.updateOneMessage({ message: newMessage });
				}
			});
			console.log(data);
		};
		const newRecvMessageRevokedHandler = ({ data: revokedMessage }) => {
			if (!this.storeCurrentConversation.conversationID) {
				return;
			}
			this.updateOneMessage({
				message: { clientMsgID: revokedMessage.clientMsgID },
				type: UpdateMessageTypes.KeyWords,
				keyWords: [
					{
						key: 'contentType',
						value: MessageType.RevokeMessage
					},
					{
						key: 'notificationElem',
						value: {
							detail: JSON.stringify(revokedMessage)
						}
					}
				]
			});
			this.updateQuoteMessageRevoke({
				clientMsgID: revokedMessage.clientMsgID
			});
		};
		const inputStatusChanged = ({ data }) => {
			if (data.userID === this.storeCurrentConversation.userID && data.conversationID === this.storeCurrentConversation.conversationID) {
				if (data.platformIDs.length > 0) {
					uni.$emit(PageEvents.TypingUpdate);
				}
			}
		};
	
		IMSDK.subscribe(IMSDK.IMEvents.OnRecvNewMessages, newMessagesHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnInputStatusChanged, inputStatusChanged);
		IMSDK.subscribe(IMSDK.IMEvents.OnRecvC2CReadReceipt, c2cReadReceiptHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnRecvGroupReadReceipt, groupReadReceiptHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnNewRecvMessageRevoked, newRecvMessageRevokedHandler);
	
		// friend
		const friendInfoChangeHandler = ({ data }) => {
			uni.$emit(IMSDK.IMEvents.OnFriendInfoChanged, { data });
			if (data.userID === this.storeCurrentConversation?.userID) {
				this.updateMessageNicknameAndFaceUrl({
					sendID: data.userID,
					senderNickname: data.remark || data.nickname,
					senderFaceUrl: data.faceURL
				});
				this.$store.commit('conversation/SET_CURRENT_CONVERSATION', { ...this.storeCurrentConversation, showName: data.remark || data.nickname });
			}
			console.log(this.storeConversationList);
			this.updateFriendInfo({friendInfo: data});
		};
		const friendAddedHandler = ({ data }) => {
			this.pushNewFriend(data);
		};
		const friendDeletedHander = ({ data }) => {
			this.updateFriendInfo({
				friendInfo: data,
				isRemove: true
			});
		};
	
		IMSDK.subscribe(IMSDK.IMEvents.OnFriendInfoChanged, friendInfoChangeHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnFriendAdded, friendAddedHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnFriendDeleted, friendDeletedHander);
	
		// blacklist
		const blackAddedHandler = ({ data }) => {
			this.pushNewBlack(data);
		};
		const blackDeletedHandler = ({ data }) => {
			this.updateBlackInfo({
				blackInfo: data,
				isRemove: true
			});
		};
	
		IMSDK.subscribe(IMSDK.IMEvents.OnBlackAdded, blackAddedHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnBlackDeleted, blackDeletedHandler);
	
		// group
		const joinedGroupAddedHandler = ({ data }) => {
			uni.$emit(IMSDK.IMEvents.OnJoinedGroupAdded, { data });
			this.pushNewGroup(data);
		};
		const joinedGroupDeletedHandler = ({ data }) => {
			uni.$emit(IMSDK.IMEvents.OnJoinedGroupDeleted, { data });
			this.updateGroupInfo({
				groupInfo: data,
				isRemove: true
			});
		};
		const groupInfoChangedHandler = ({ data }) => {
			this.updateGroupInfo({
				groupInfo: data
			});
		};
		const groupMemberInfoChangedHandler = ({ data }) => {
			uni.$emit(IMSDK.IMEvents.OnGroupMemberInfoChanged, { data });
			if (data.groupID === this.storeCurrentConversation?.groupID) {
				this.updateMessageNicknameAndFaceUrl({
					sendID: data.userID,
					senderNickname: data.nickname,
					senderFaceUrl: data.faceURL
				});
				this.updateCurrentMemberInGroup(data);
			}
		};
	
		IMSDK.subscribe(IMSDK.IMEvents.OnJoinedGroupAdded, joinedGroupAddedHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnJoinedGroupDeleted, joinedGroupDeletedHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnGroupInfoChanged, groupInfoChangedHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnGroupMemberInfoChanged, groupMemberInfoChangedHandler);
		// application
		const friendApplicationNumHandler = ({ data }) => {
			const isRecv = data.toUserID === this.storeCurrentUserID;
			if (isRecv) {
				this.pushNewRecvFriendApplition(data);
			} else {
				this.pushNewSentFriendApplition(data);
			}
		};
		const friendApplicationAccessHandler = ({ data }) => {
			const isRecv = data.toUserID === this.storeCurrentUserID;
			if (isRecv) {
				this.updateRecvFriendApplition({
					application: data
				});
			} else {
				this.updateSentFriendApplition({
					application: data
				});
			}
		};
		const groupApplicationNumHandler = ({ data }) => {
			const isRecv = data.userID !== this.storeCurrentUserID;
			if (isRecv) {
				this.pushNewRecvGroupApplition(data);
			} else {
				this.pushNewSentGroupApplition(data);
			}
		};
		const groupApplicationAccessHandler = ({ data }) => {
			const isRecv = data.userID !== this.storeCurrentUserID;
			if (isRecv) {
				this.updateRecvGroupApplition({
					application: data
				});
			} else {
				this.updateSentGroupApplition({
					application: data
				});
			}
		};
	
		IMSDK.subscribe(IMSDK.IMEvents.OnFriendApplicationAdded, friendApplicationNumHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnFriendApplicationAccepted, friendApplicationAccessHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnFriendApplicationRejected, friendApplicationAccessHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnGroupApplicationAdded, groupApplicationNumHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnGroupApplicationAccepted, groupApplicationAccessHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnGroupApplicationRejected, groupApplicationAccessHandler);
	
		// conversation
		const totalUnreadCountChangedHandler = ({ data }) => {
			if (this.storeIsSyncing) {
				return;
			}
			this.$store.commit('conversation/SET_UNREAD_COUNT', data);
		};
		const newConversationHandler = ({ data }) => {
			if (this.storeIsSyncing) {
				return;
			}
			const result = [...data, ...this.storeConversationList];
			this.$store.commit('conversation/SET_CONVERSATION_LIST', conversationSort(result));
		};
		const conversationChangedHandler = ({ data }) => {
			if (this.storeIsSyncing) {
				return;
			}
			let filterArr = [];
			console.log("qxj conversationChangedHandler:::");
			console.log(data);
			const chids = data.map((ch) => ch.conversationID);
			filterArr = this.storeConversationList.filter((tc) => !chids.includes(tc.conversationID));
			const idx = data.findIndex((c) => c.conversationID === this.storeCurrentConversation.conversationID);
			if (idx !== -1) this.$store.commit('conversation/SET_CURRENT_CONVERSATION', data[idx]);
			const result = [...data, ...filterArr];
			this.$store.commit('conversation/SET_CONVERSATION_LIST', conversationSort(result));
		};
	
		IMSDK.subscribe(IMSDK.IMEvents.OnTotalUnreadMessageCountChanged, totalUnreadCountChangedHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnNewConversation, newConversationHandler);
		IMSDK.subscribe(IMSDK.IMEvents.OnConversationChanged, conversationChangedHandler);
	
		const insertInCurrentConversation = (newServerMsg) => {
			return newServerMsg.sendID === this.$store.getters.storeCurrentConversation.userID || newServerMsg.recvID === this.$store.getters.storeCurrentConversation.userID;
		};
	
		const onNativeCallEndHandler = async ({ invitation, duration, status }) => {
			uni.$emit(PageEvents.NativeCallEnd);
			if (!status || invitation.groupID) {
				return;
			}
			const type = invitation.mediaType === 'video' ? CustomType.VideoCall : CustomType.VoiceCall;
			const customData = {
				customType: CustomType.Call,
				data: { type, duration: secFormat(duration), status }
			};
			// uni.clearStorageSync();
			const nativeCallList = uni.getStorageSync(`${this.$store.getters.storeCurrentUserID}_nativecall`) || [];
			const isSelf = invitation.inviterUserID === this.$store.getters.storeCurrentUserID;
			const data = { ...invitation, duration, isSelf, type, time: new Date().getTime() };
			uni.setStorage({
				key: `${this.$store.getters.storeCurrentUserID}_nativecall`,
				data: [...nativeCallList, data]
			});
			const message = await IMSDK.asyncApi(IMMethods.CreateCustomMessage, IMSDK.uuid(), {
				data: JSON.stringify(customData),
				extension: '',
				description: 'RTC'
			});
			const recvID = invitation.inviteeUserIDList[0];
			IMSDK.asyncApi(IMSDK.IMMethods.InsertSingleMessageToLocalStorage, IMSDK.uuid(), {
				message,
				recvID,
				sendID: invitation.inviterUserID
			}).then(({ data }) => {
					if (insertInCurrentConversation(data)) {
						this.$store.dispatch('message/pushNewMessage', data);
						setTimeout(() => uni.$emit(PageEvents.ScrollToBottom, true));
					}
				}).catch((err) => {
					console.log(err);
				});
		};
		const onNativeInviteHandler = async (data) => {
			// uni.$u.toast("onNativeInviteHandler")
			uni.$u.route('/pages_im/pages/common/contactChoose/index', {
				type: ContactChooseTypes.InviteMeeting,
				forwardMessage: encodeURIComponent(JSON.stringify(data.data))
			});
		};
		IMSDK.subscribe('onNativeCallEnd', onNativeCallEndHandler);
		IMSDK.subscribe('Native_InviteUser', onNativeInviteHandler);
	},
	openImLogin() {
		let that = this;
		var userId=uni.getStorageSync('userId');
		var avatar=uni.getStorageSync('avatar');
		var nickName=uni.getStorageSync('nickName');
		
		var uid = 'U' + userId;
		let IMToken = uni.getStorageSync('IMToken');
		let IMUserID = uid
		let reqData = { userID: uid, nickName: nickName, avatar: avatar };
		//if(!!IMToken){
		openImLoginApi(
			reqData,
			IMToken,
			IMUserID,
			function (token) {
				that.tryLogin();
			},
			function () {}
		);
		//}
	},
		
	async tryLogin() {
		const initStore = () => {
			
			uni.setStorageSync('IMHasLogin', 1);
	
			this.$store.dispatch('user/initCache');
			this.$store.dispatch('user/getSelfInfo');
	
			//this.$store.dispatch('conversation/getConversationList');
			this.$store.dispatch('conversation/getUnReadCount');
	
			// this.$store.dispatch("contact/getFriendList");
			// this.$store.dispatch("contact/getGrouplist");
	
			// this.$store.dispatch('contact/getBlacklist');
			// this.$store.dispatch('contact/getRecvFriendApplications');
			// this.$store.dispatch('contact/getSentFriendApplications');
			// this.$store.dispatch('contact/getRecvGroupApplications');
			// this.$store.dispatch('contact/getSentGroupApplications');
			
		};
		let IMToken = uni.getStorageSync('IMToken');
		let IMUserID = uni.getStorageSync('IMUserID');
		
		//1	未登录  2 登录中  3  已登录
		const loginStatus = await IMSDK.asyncApi(IMSDK.IMMethods.GetLoginStatus, IMSDK.uuid());
		console.log("qxj loginStatus:"+loginStatus);
		if (loginStatus === 3) {
			initStore();
			return;
		}
		//callingModule?.initModule();
		let platformID=5
		
		// #ifdef H5
		   platformID=5
		// #endif
		
		// #ifdef MP-WEIXIN
	    	platformID=6
		// #endif
	
		console.log("qxj platformID:"+platformID);
		
		if (IMToken && IMUserID) {
			    IMSDK.asyncApi(IMSDK.IMMethods.Login, IMSDK.uuid(), { 
				    userID: IMUserID, 
				    token: IMToken,
				    platformID:platformID,
			        apiAddr: config.getApiUrl(),
					wsAddr: config.getWsUrl(), 
					logLevel: 1,
				}).then(initStore).catch((err) => {
					console.log('qxj initStore error:' + JSON.stringify(err));
					uni.removeStorage({ key: 'IMToken' });
				});
		 } else{
			this.checkLogin()
		 }
	},
	async newMessageNotify(newServerMsg) {
		if (this.storeIsSyncing) {
			return;
		}
		const disableNotify = uni.getStorageSync(`${this.storeCurrentUserID}_DisableNotify`);
		if (disableNotify || this.storeSelfInfo.globalRecvMsgOpt !== MessageReceiveOptType.Nomal) {
			return;
		}
		let cveItem = [...this.storeConversationList, ...cacheConversationList].find((conversation) => {
			if (newServerMsg.sessionType === SessionType.WorkingGroup) {
				return newServerMsg.groupID === conversation.groupID;
			}
			return newServerMsg.sendID === conversation.userID;
		});
		if (!cveItem) {
			try {
				const { data } = await IMSDK.asyncApi(IMSDK.IMMethods.GetOneConversation, IMSDK.uuid(), {
					sourceID: newServerMsg.groupID || newServerMsg.sendID,
					sessionType: newServerMsg.sessionType
				});
				cveItem = data;
				cacheConversationList = [...cacheConversationList, data];
				
			} catch (e) {
				return;
			}
		}
	
		if (cveItem.recvMsgOpt !== MessageReceiveOptType.Nomal) {
			return;
		}
	
		// uni.createPushMessage({
		// 	content: `${newServerMsg.senderNickname}: ${parseMessageByType(newServerMsg)}`,
		// 	payload: {
		// 		sessionType: newServerMsg.sessionType,
		// 		sourceID: newServerMsg.groupID || newServerMsg.sendID,
		// 	}
		// });
	
		// const notificationFun = () => {
		// 	const isSelf = newServerMsg.sendID === this.$store.getters.storeCurrentUserID;
		// 	if (isSelf) return;
		// 	const isSingle = newServerMsg.groupID ? false : true;
		// 	console.log(this.storeGroupList, newServerMsg);
		// 	const group = this.storeGroupList.filter((group) => group.groupID === newServerMsg.groupID);
		// 	const title = isSingle ? newServerMsg.senderNickname : group[0].groupName;
		// 	const desc = parseMessageByType(newServerMsg);
		// 	console.log('notification', title, desc);
		// 	notification.showNotice(0, title, desc, () => {
		// 		prepareConversationState(cveItem);
		// 	});
		// };
		
		
		// notificationFun();
		// const platform = uni.getSystemInfoSync().platform;
		// if (platform == 'ios') {
		// 	if (this.storeSelfInfo.allowVibration === 1) {
		// 		plus.device.vibrate();
		// 	}
		// 	if (this.storeSelfInfo.allowBeep === 1) {
		// 		innerAudioContext.play();
		// 		// plus.device.beep();
		// 	}
		// } else if (platform == 'android') {
		// 	if (this.storeSelfInfo.allowVibration === 1) {
		// 		plus.device.vibrate(500);
		// 	}
		// 	if (this.storeSelfInfo.allowBeep === 1) {
		// 		let main = plus.android.runtimeMainActivity();
		// 		let RingtoneManager = plus.android.importClass('android.media.RingtoneManager');
		// 		let uri = RingtoneManager.getActualDefaultRingtoneUri(main, RingtoneManager.TYPE_NOTIFICATION);
		// 		let MediaPlayer = plus.android.importClass('android.media.MediaPlayer');
		// 		let player = MediaPlayer.create(main, uri);
		// 		player.setLooping(false);
		// 		player.prepare();
		// 		player.start();
		// 	}
		// }
	},
	handleNewMessage(newServerMsg) {
		console.log("---qxj newServerMsg");
		console.log(newServerMsg);
		if (this.inCurrentConversation(newServerMsg)) {
			const isSingleMessage = newServerMsg.sessionType === SessionType.Single;
			if (isSingleMessage) {
				 uni.$u.throttle(() => uni.$emit(PageEvents.OnlineStateCheck), 2000);
				 if(newServerMsg.ex!=null&&newServerMsg.ex!=''){
					 var json=JSON.parse(newServerMsg.ex);
					 this.$store.commit("timStore/setType",json.type);
					 this.$store.commit("timStore/setImType", json.imType);
					 this.$store.commit("timStore/setOrderId",json.orderId);
					 this.$store.commit("timStore/setOrderType",json.orderType);
					 this.$store.commit("timStore/setFollowId",json.followId);
					 if(json.type==="finishInquiry"){
					 	 this.$store.commit("timStore/setImType", 0);
					 	 uni.navigateTo({ url: "/pages_order/pingOrder?orderId="+json.orderId })
					 }
					 else if(json.type==="startInquiry"){
					 	
					 }
					 else if(json.type==="inquiry"){
					 	
					 }
					 else if(json.type==="startFollow"){
					 	
					 }
					 else if(json.type==="follow"){
					 	
					 }
					 else if(json.type==="finishFollow"){
					 	
					 }
					 else if(json.type==="startDrugReport"){
					 	
					 }
					 else if(json.type==="finishDrugReport"){
					 	
					 }
					 else if(json.type==="drugReport"){
					 	
					 }
				 }
			}
			if (newServerMsg.contentType === MessageType.TypingMessage) {
				if (isSingleMessage) {
					uni.$emit(PageEvents.TypingUpdate);
				}
			} 
			else {
				if (newServerMsg.contentType === MessageType.RevokeMessage) {
					
				} 
				else {
					newServerMsg.isAppend = true;
					this.pushNewMessage(newServerMsg);
					setTimeout(() => uni.$emit(PageEvents.ScrollToBottom, true));
				}
				uni.$u.debounce(this.markConversationAsRead, 2000);
			}
		} 
		else {
			if (newServerMsg.contentType !== MessageType.TypingMessage) {
				console.log("---qxj not inCurrentConversation");
				uni.$u.throttle(() => this.newMessageNotify(newServerMsg), 500);
				setTimeout(() => {
					this.$store.dispatch('conversation/getUnReadCount');
				},500);
			}
		}
	},
	inCurrentConversation(newServerMsg) {
		switch (newServerMsg.sessionType) {
			case SessionType.Single:
				return (
					newServerMsg.sendID === this.storeCurrentConversation.userID ||
					(newServerMsg.sendID === this.storeCurrentUserID && newServerMsg.recvID === this.storeCurrentConversation.userID)
				);
			case SessionType.WorkingGroup:
				return newServerMsg.groupID === this.storeCurrentConversation.groupID;
			case SessionType.Notification:
				return newServerMsg.sendID === this.storeCurrentConversation.userID;
			default:
				return false;
		}
	},
	markConversationAsRead() {
		IMSDK.asyncApi(IMSDK.IMMethods.MarkConversationMessageAsRead, IMSDK.uuid(), this.storeCurrentConversation.conversationID);
	},
	removeImData(){
		uni.removeStorage({ key: 'IMToken' });
		uni.removeStorage({ key: 'IMUserID' });
	},
	getRuntimePlatform() {
		  const systemInfo = uni.getSystemInfoSync();
		  const compilePlatform = process.env.UNI_PLATFORM;
		  //1：iOS，2：Android，3：Windows，4：OSX，5：WEB，6：小程序，7：linux，8：AndroidPad，9：IPad，10：Admin
		  let platformType=5;
		  // H5 环境
		  if (compilePlatform === 'h5') platformType= 5;  
		
		  // 小程序环境
		  if (compilePlatform.startsWith('mp-')) {
			 const mpType = compilePlatform.split('-')[1]; // 如 weixin/alipay
			 platformType=6;
		  }
		  // App 环境
		  if (compilePlatform === 'app-plus') {
			 if(systemInfo.platform.toLowerCase() === 'android'){
				 platformType=2;
			 }
			 if(systemInfo.platform.toLowerCase() === 'ios'){
				 platformType=1;
			 }
		  }
		  console.log("----qxj platformType:"+platformType);
		  uni.showToast({ title:" platformType:"+platformType,icon:'none', duration: 2000 });
		  return platformType;
	},
  }
};
</script>


<style lang="scss">
	@import "@/assets/css/theme.scss";
	/*每个页面公共css */
	// #ifdef VUE3
	@import "@/uni_modules/uview-plus/index.scss";
	// #endif
	// #ifndef VUE3
	@import "uview-ui/index.scss";
	// #endif
	view{
		box-sizing: border-box;
	}
	.ellipsis{
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.ellipsis2{
		overflow:hidden; 
		text-overflow:ellipsis;
		display:-webkit-box; 
		-webkit-box-orient:vertical;
		-webkit-line-clamp:2; 
	}
	.no-data-box{
		box-sizing: border-box;
		width: 100%;
		padding: 200rpx 50rpx;
		text-align: center;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		image{
			width: 200upx;
			height: 150upx;
		}
		.empty-title{
			margin-top: 20rpx;
			font-size: 28rpx;
			color: #bbbbbb;
			 
		}
	}
	.doctor-box{
		margin-top: 15rpx;
		padding: 20rpx 0rpx 0rpx;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		justify-content: flex-start;
		.doctor{
			width: 100%;
			margin-bottom: 15rpx;
			background: #fff;
			padding: 15rpx;
			display: flex;
			flex-direction: column;
			align-items: flex-start;
			justify-content: flex-start;
			&:last-child{
				margin-bottom: 0rpx;
			}
			.item{
				width: 100%;
				display: flex;
				align-items: flex-start;
				justify-content: flex-start;
				.left{
					.head-box{
						width:92rpx;
						height:92rpx;
						position: relative;
						.isline{
							width:92rpx;
							height:92rpx;
							border-radius: 50%;
							border: 2rpx solid #2EDAD4;
							display: flex;
							align-items: center;
							justify-content: center;
							position: absolute;
							bottom: 0rpx;
							.img{
								position: absolute;
								bottom: 1rpx;
								width:75rpx;
								height:35rpx;
								image{
									width:75rpx;
									height:35rpx;
								}
								.name{
									width:75rpx;
									height:35rpx;
									bottom: -3rpx;
									text-align: center;
									position: absolute;
									font-size: 16upx;
									font-family: PingFang SC;
									font-weight: bold;
									color: #ffffff;
								}
							}
							
							
						}
						.doc-img{
							border-radius: 50%;
							width:100%;
							height:100%;
						
						}
						
					}
				}
				
				.right{
					width: calc(100% - 100rpx); 
					margin-left: 20rpx;
					display: flex;
					flex-direction: column;
					align-items: flex-start;
					justify-content: flex-start;
					.doc-box{
						display: flex;
						align-items: center;
						justify-content: space-between;
						.doc-name{
							font-size: 32upx;
							font-family: PingFang SC;
							font-weight: bold;
							color: #111111;
							
						}
						.doc-position{
							margin-left: 16rpx;
							font-size: 26upx;
							font-weight: bold;
							font-family: PingFang SC;
							color: #2A2B2E;
						}
						.doc-dept{
							margin-left: 16rpx;
							font-size: 26upx;
							font-weight: bold;
							font-family: PingFang SC;
							color: #2A2B2E;
						}
					}
					.hospital-box{
						display: flex;
						align-items: center;
						justify-content: flex-start;
						margin-top: 10rpx;
						.tag{
							display: flex;
							align-items: center;
							justify-content: center;
							background-color: #4FC06B;
							border-radius: 10rpx;
							padding: 5rpx 10rpx;
							font-size: 20upx;
							font-weight: bold;
							font-family: PingFang SC;
							color: #ffffff;
						}
						.name{
							margin-left: 6rpx;
							font-size: 26upx;
							font-weight: bold;
							font-family: PingFang SC;
							color: #2A2B2E;
						}
						
					}
					.doc-spec{
						width: 100%;
						display: flex;
						align-items: center;
						justify-content: flex-start;
						margin-top: 15rpx;
						.spec{
							font-size: 26upx;
							font-family: PingFang SC;
							color: #626468;
						}
					}
					.doc-count{
						margin-top: 15rpx;
						display: flex;
						align-items: center;
						justify-content: flex-start;
						.name{
							font-size: 24upx;
							font-family: PingFang SC;
							color: #9B9B9B;
						}
						.count{
							margin: 0rpx 5rpx;
							font-size: 24upx;
							font-family: PingFang SC;
							color: #2A2B2E;
						}
					}
					.doc-price{
						width: 100%;
						margin-top: 15rpx;
						display: flex;
						align-items: center;
						justify-content: flex-start;
						.btn{
							display: flex;
							align-items: center;
							justify-content: center;
							background-color: #2583EB;
							padding: 15rpx 30rpx;
							border-radius: 30rpx;
							font-size: 26upx;
							font-family: PingFang SC;
							color: #fff;
						}
					}
					
				}
			}
			
		}
	}
	 
</style>
<style lang="less">
/*每个页面公共css */
@import './assets/iconfont/iconfont.css';
@import './assets/css/common.less';
/* 全局flex样式 */
@import './common/css/flexCommon.css';
</style>