//2021年9月28日17:46:44 小谢 IM封装
import {sdkAppID,sdkAppKey} from "@/utils/config.js";
let txIm = {};
// #ifdef APP-PLUS
txIm = uni.requireNativePlugin('TX-TencentIM');
// #endif

const Im_store = {
	state: {
		isLogin: false, //是否登录
		isSDKReady: false, // TIM SDK 是否 ready
		//APP IM data
		msgslist: [], //单聊的消息列表
		qunmsgslist:[],//群聊的历史消息
		myconversationList: [], //会话列表 我的会话列表
		dfuserId: "", //单聊的时候 对方的userID
		groupId:"",//正在聊天的群聊id
		Unread:0,//未读的消息数
		//APP IM data end
	},
	mutations: {
		SetgroupId(state, groupId) {
			state.groupId = groupId;
		},
		SetToken(state, token) {
			state.token = token;
		},
		//修改群消息
		setqunmsgslist(state, qunmsgslist) {
			state.qunmsgslist = qunmsgslist;
		},
		//更新登录状态
		toggleIsLogin(state, isLogin) {
			state.isLogin = typeof isLogin === 'undefined' ? !state.isLogin : isLogin
		},
		//退出登录重置状态
		reset(state) {
			state.isLogin = false
			state.isSDKReady = false
		},
		// APP fun
		//修改单聊消息
		Setmsgslist(state, data) {
			state.msgslist = data;
		},
		//修改单聊对方ID
		setdfuserId(state, data) {
			state.dfuserId = data;
		},
		setmyconversationList(state, data) {
			state.myconversationList = data;
		},
		setUnread(state, data){//未读的消息数
			state.Unread = data;
		}
		
		//APP fun edn
	},

	actions: {
		reloads(store, vla) {
			// #ifdef APP-PLUS
			plus.runtime.restart(); //重新启动
			// #endif

			// #ifdef MP-WEIXIN
			const updateManager = wx.getUpdateManager();
			updateManager.applyUpdate()
			// #endif

			// #ifdef H5
			location.reload();
			// #endif
		},
		//APP或者小程序 都调用 初始化IM登录
		InItImlogin(store, type) {
			let IMUserID = uni.getStorageSync("IMUserID");
			// #ifdef APP-PLUS
			store.dispatch("loginStatus", String(IMUserID)).then((res) => { //获取登录状态
				//"登录状态",res);
				if (res.loginStatus != 1) {
					//没登录
					store.dispatch("baselogin", String(IMUserID))
				} else {
					//已经登录了
					store.dispatch("baselogin", String(IMUserID))
				}
			})
			// #endif
		},
		//APP SDK funticon
		///登录 APP的
		baselogin(store, userId = "user1") {
			var _self = this;
			//初始化SDK
			let isSuccess = txIm.initSDK({
				sdkAppID: sdkAppID,
				logLevel: 0
			}, result => {
				
			})
			//"isSuccess",isSuccess);
			//如果初始化成功
			if (isSuccess) {
				txIm.removeAdvancedMsgListener(); //移除高级消息监听
				txIm.removeGroupListener(); //移除群消息监听
				txIm.removeFriendListener(); //移除好友消息监听
				txIm.removeSignalingListener(); ///删除签名列表
				//设置高级消息接口监听
				txIm.addAdvancedMsgListener(result => {
					let txIm = {};
					// #ifdef APP-PLUS
					txIm = uni.requireNativePlugin('TX-TencentIM');
					// #endif
					//"新消息来了");
					//新消息来了
					//震动
					// uni.vibrateLong({
					//     success: function () {
					//         //('success');
					//     }
					// });

					//....
					// 去刷新消息
					// 1.刷新聊天界面里面的消息
					// 2.刷新消息 页面里面的消息
					//如果当前对话的人 和 给我发消息的人是一个人 就自动同步一波
					if(result.type=='onRecvNewMessage'){
						if (store.state.dfuserId == result.msg.userId) {
							store.dispatch("getC2CHistoryMessageList", {msgId:""}).then((res) => {}); //去刷新聊天界面的消息
							store.dispatch("getConversationList", {}).then(()=>{}); //刷新获取会话列表
						} else  {
							store.dispatch("getConversationList", {}).then(()=>{}); //刷新获取会话列表
							store.dispatch("messageTisfun", {}); //播放提醒消息
						}
					}else if(result.type=='onRecvC2CReadReceipt'){
						// if (store.state.dfuserId == result.receiptList[0].userId) {
						// 	store.dispatch("getC2CHistoryMessageList", {msgId:""}).then((res) => {}); //去刷新聊天界面的消息
						// 	store.dispatch("getConversationList", {}).then(()=>{}); //刷新获取会话列表
						// } else  {
						// 	store.dispatch("getConversationList", {}).then(()=>{}); //刷新获取会话列表
						// 	store.dispatch("messageTisfun", {}); //播放提醒消息
						// }
						return false;
					}else{
						store.dispatch("getConversationList", {}).then(()=>{}); //刷新获取会话列表
						store.dispatch("messageTisfun", {}); //播放提醒消息
					}
					
					if(store.state.groupId==result.msg.groupId){
						store.dispatch("getGroupHistoryMessageList", {}); //获取最新的群消息
					}
					
					let msg = result.msg;
					if (msg.elemType == 3) {
						txIm.downloadImage({
							"msgId": msg.msgId
						}, progressResult => {
						}, succResult => {
							// //"succResult",succResult)
						}, result => {
							
						})
					} else if (msg.elemType == 4) {
						//下载语音消息
						txIm.downloadSound({
							"msgId": msg.msgId
						}, progressResult => {
							
						}, succResult => {
							
						}, failResult => {
							
						})
					} else if (msg.elemType == 5) {
						//下载视频消息
						txIm.downloadVideo({
							"msgId": msg.msgId
						}, progressResult => {
							
						}, succResult => {
							
						}, failResult => {
							
						})
					} else if (msg.elemType == 6) {
						//下载文件消息
						txIm.downloadFile({
							"msgId": msg.msgId
						}, progressResult => {
							
						}, succResult => {
							
						}, failResult => {
							
						})
					}
				});
				//设置群消息监听
				txIm.setGroupListener(result => {
					//群消息监听
					//(result,"群消息监听");
				});
				//设置好友消息监听
				txIm.setFriendListener(result => {
					//(result,"设置好友消息监听");
				});
				//添加信号侦听器？
				txIm.addSignalingListener(result => {
					//(result,"添加好友信息监听");
					if (result.type === "onReceiveNewInvitation") { //收到新的邀请
						_self.inviteData = result;
					}
				});
				//登录
				txIm.login({
					sdkAppID: sdkAppID,
					sdkAppKey: sdkAppKey,
					userId: userId, //要登录的用户id 可以加密 格式不限
					expireTime: 31536000,//604800, //登录过期时间，可以不填写 365天
					filePath: plus.io.convertLocalFileSystemURL('_doc'), //文件路径？
				}, result => {
					//(result, "登录完成");
					//_self.currentUser = _self.user1; //修改当前登录的用户id IMid
					//上传安卓平台证书
					let txIm1 = {};
					// #ifdef APP-PLUS
					txIm1 = uni.requireNativePlugin('TX-TencentIM');
					// #endif
					
					//设置推送证书
					// txIm1.setOfflinePushConfig({
					// 	//下面这个是测试的
					// 	"businessId": 11632, //腾讯后台填写平台推送信息后获取的id
					// }, result => {
					// })
				})
			}
		},
		//获取登录状态
		loginStatus() {
			return new Promise((reslove, reject) => {
				let status = txIm.getLoginStatus();
				reslove(status);
			})
		},
		//获取当前登录用户
		getLoginUser() {
			return new Promise((reslove, reject) => {
				let user = txIm.getLoginUser();
				reslove(user);
			})
		},
		//设置用户信息 
		setSelfProfile(store, infodate) {
			// #ifdef APP-PLUS
			let obj1 = {};
			if (infodate.needid) {
				obj1.Tag_Profile_Custom_needid = infodate.needid; //人脉表id 有时候不传
			}
			txIm.setSelfProfile({ //APP
				"allowType": 0,
				"customInfo": { //自定义字段
					// Tag_Profile_Custom_serid
					// Tag_Profile_Custom_uid
					...obj1,
				},
				"userName": infodate.userName, //用户昵称
				"userAvatar": infodate.userAvatar,
			}, result => {
				//设置用户信息ok
			})
			// #endif
		},
		//设置用户信息 单独设置人脉id
		setSelfProfiletwo(store, infodate) {
			// #ifdef APP-PLUS
			let obj1 = {};
			if (infodate.needid) {
				obj1.Tag_Profile_Custom_needid = infodate.needid; //人脉表id 有时候不传
			}
			txIm.setSelfProfile({ //APP
				"allowType": 0,
				"customInfo": { //自定义字段
					...obj1,
				},
			}, result => {
				//设置用户信息ok
			})
			// #endif
		},
		//获取单聊历史消息
		getC2CHistoryMessageList(store, obj) {
			return new Promise((reslove, reject) => {
				txIm.getC2CHistoryMessageList({
					"userId": store.state.dfuserId, //obj.userId,
					"count": 99999, //拉取消息的个数
					msgId:"",
					// "msgId": "144115232869100554-1634110694-3123053130",//obj.msgId, //this.historyC2CMsgId
				}, result => {
					let txIm = {};
					// #ifdef APP-PLUS
					txIm = uni.requireNativePlugin('TX-TencentIM');
					// #endif
					let msgs = result.msgs;
					// //(result, "d0历史消息");
					msgs.reverse(); //数组逆序一下
					msgs = msgs.map((msg, index) => {
						if (msg.elemType == 3) {
							//获取图片资源
							txIm.getImageUrl({"msgId":msg.msgId},result=>{
								msg.url_imageList = result.imageList;
							})
							
						} else if (msg.elemType == 4) {
							//音频？
							txIm.downloadSound({"msgId":msg.msgId},progressResult=>{
								
							},succResult=>{
								//下载成功
								if (succResult.path) {
									// //"语音消息下载成功",succResult);
									msg.mp3file = succResult;
								}
							},failResult=>{
								
							})
							
							
							//获取sound资源url
							txIm.getSoundUrl({"msgId":msg.msgId},result=>{
								// //("----------------------------------------");
								// //(result,"获取语音资源成功");
								// //("----------------------------------------");
								if(result.code==0){
									msg.SoundUrl = result;
								}
							})
							
							
						} else if (msg.elemType == 5) {
							//视频
							txIm.downloadVideo({
								"msgId": msg.msgId
							}, progressResult => {
								
							}, succResult => {
								//下载成功
							}, failResult => {
								
							})
						} else if (msg.elemType == 6) {
							//文件
							txIm.downloadFile({
								"msgId": msg.msgId
							}, progressResult => {
								
							}, succResult => {
								//下载成功
							}, failResult => {
								
							})
						}else if(msg.elemType == 2){
							//自定义消息
							// //msg,"msgitem1");
							if(msg.customElem.extension){
								if(msg.customElem.extension.indexOf("type")!=-1){
									if(msg.customElem.desc){
										msg.customdata = JSON.parse(msg.customElem.desc);
									}
								}
							}
							
						}
						return msg;
					});
					if (result.msgs.length > 0) {
						//this.historyC2CMsgId = result.msgs[result.msgs.length - 1].msgId
					}
					// //(msgs, "历史消息");
					store.commit("Setmsgslist", msgs)
					reslove(result);
				})
			})

		},
		//获取单聊历史消息 end
		
		//获取群聊历史消息
		getGroupHistoryMessageList(store, objects) {
			return new Promise((reslove, reject) => {
				// "msgId":objects.msgId
				txIm.getGroupHistoryMessageList({"groupId":store.state.groupId,"count":999999,"msgId":""},result=>{
					let msgs = result.msgs;
					// //(result, "q历史消息");
					msgs.reverse(); //数组逆序一下
					msgs = msgs.map((msg,index)=>{  
						
						if (msg.elemType == 3) {
							//下载图片
							//获取图片资源
							txIm.getImageUrl({"msgId":msg.msgId},result=>{
								msg.url_imageList = result.imageList;
							})
							
						} else if (msg.elemType == 4) {
							//音频？
							txIm.downloadSound({"msgId":msg.msgId},progressResult=>{
								
							},succResult=>{
								if (succResult.path) {
									// //"语音消息下载成功",succResult);
									msg.mp3file = succResult;
								}
							},failResult=>{
								
							})
							
							
							//获取sound资源url
							txIm.getSoundUrl({"msgId":msg.msgId},result=>{
								// //("----------------------------------------");
								// //(result,"获取语音资源成功");
								// //("----------------------------------------");
								if(result.code==0){
									msg.SoundUrl = result;
								}
							})
							
						} else if (msg.elemType == 5) {
							//视频
							txIm.downloadVideo({
								"msgId": msg.msgId
							}, progressResult => {
								
							}, succResult => {
								//下载视频成功
							}, failResult => {
								
							})
						} else if (msg.elemType == 6) {
							//文件
							txIm.downloadFile({
								"msgId": msg.msgId
							}, progressResult => {
								
							}, succResult => {
								//下载文件成功
							}, failResult => {
								//下载文件失败
							})
						}else if(msg.elemType == 2){
							//自定义消息
							//msg,"msgitem");
							if(msg.customElem.extension){
								if(msg.customElem.extension.indexOf("type")!=-1){
									if(msg.customElem.desc){
										msg.customdata = JSON.parse(msg.customElem.desc);
									}
								}
							}
						}
						return msg;
					});
					// //"群历史消息",msgs);
					store.commit("setqunmsgslist", msgs)
					reslove(msgs);
					
				})
			})
			
		},
		//获取群聊历史消息end
		
		//获取群信息start
		getGroupsInfo(store, obj){
			return new Promise((reslove, reject) => {
				txIm.getGroupsInfo({"groupIdList":[store.state.groupId]},result=>{
					reslove(result);
				})
			})
		},
		//获取群信息end
		
		//获取群成员列表 start
		getGroupMemberList(store, obj){
			let groupId = obj.groupId?obj.groupId:store.state.groupId;
			return new Promise((reslove, reject) => {
				txIm.getGroupMemberList({"groupId":groupId,"filter":0,"nextSeq":0},result=>{
					reslove(result);
				})
			})
		},
		//获取群成员列表end
		
		
		//获取会话列表
		getConversationList(store, obj) {
			return new Promise((reslove, reject) => {
				txIm.getConversationList({
					nextSeq: 0,
					count: 99999,
				}, result => {
					let conversationList = result.conversationList; //会话消息列表
					let Unread = 0; //未读
					conversationList.forEach((item, index) => {
						Unread += item.unreadCount;
					})
					//"未读总", Unread);
					// //"conversationList",conversationList);
					store.commit("setmyconversationList", conversationList); //更新会话列表
					store.commit('setUnread',Unread);//未读的数量
					
					
					let CornerIndex = 1;
					if (Unread > 0 && Unread <= 99) {
						uni.setTabBarBadge({
							index: CornerIndex,
							text: String(Unread),
						})
						// #ifdef APP-PLUS
						plus.runtime.setBadgeNumber(Unread);
						// #endif
					} else if (Unread > 0 && Unread > 99) {
						uni.setTabBarBadge({
							index: CornerIndex,
							text: "99",
						})
						// #ifdef APP-PLUS
						plus.runtime.setBadgeNumber(99);
						// #endif
					} else {
						uni.removeTabBarBadge({
							index: CornerIndex
						});
						// #ifdef APP-PLUS
						plus.runtime.setBadgeNumber(0);
						// #endif
					}
					reslove(result);

				})
			})
		},
		//APP SDK funticon
		//极光推送设置别名 用于推送
		setupJYJPush(store, name) {
			// #ifdef APP-PLUS
			const jyJPush = uni.requireNativePlugin('JY-JPushThird');
			jyJPush.setJYJPushTags({
				userTag: name,
			}, result => {
				//设置tag push is成功
			});
			// #endif
		},
		//批量获取指定用户的资料
		geIMtUsersInfo(store,obj){
			return new Promise((reslove, reject) => {
				txIm.getUsersInfo({userIdList:obj.userIdList},result=>{
					reslove(result)
				})
			});
		},
		//新消息提示
		messageTisfun(){
			//"语音消息提醒");
			
			let isvoicemsg = uni.getStorageSync("isvoicemsg");
			if(isvoicemsg=='-1'){
				//"设置关闭了消息 不提示 ！");
				return false;
			}
			this.platform = uni.getSystemInfoSync().platform;
			let src = 'https://runimg.jxdsy.cn/bank/msg_tips.mp3'
			if(this.platform=='ios'){
				const bgAudioMannager=uni.getBackgroundAudioManager();
				bgAudioMannager.title = '鹿马消息提示...';
				bgAudioMannager.singer = '小马将为你进行实时播报语音';
				bgAudioMannager.coverImgUrl = 'https://runimg.jxdsy.cn/bank/logo.png';
				bgAudioMannager.src = src;
				bgAudioMannager.play();
				bgAudioMannager.onEnded((res)=>{ //自然播放完毕
					bgAudioMannager.pause(); //pause 暂停
				});
			}else{
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = src;
				innerAudioContext.onPlay(() => { //音频播放时
					uni.vibrateLong();//震动 调用//400ms//长震动
				});
				innerAudioContext.onError((res) => { //音频播放错误
					
				});
			}
		}
		
		
		
	}
}
export default Im_store;