<template>
	<view class="content" @click.sop="">
		<!-- IM连接 -->
		<view v-if="!libPage" class="user">
			<view class="loading">
				<span v-for="i in 4" :key='i'></span>
			</view>	
			<view class="loading-type2">
				<span></span>
			</view>				
			<view class="content-lab">
				<p>appkey：{{form.appkey}}</p>
				<p>token：{{form.token}}</p>
				<p>targetId：{{targetId}}</p>
				<button class="btn">
					连接中请稍等……
				</button>
			</view>
		</view>	
		<view v-if="libPage">
<!-- 			<span>用户ID：</span><span>{{loginUserId}}</span> -->
			<ry-chat-room :chats="chatList" @send="chatSend" @call="callOut" />
		</view>
		<view class="boxs" v-if="isCut">
			<view class="boxs-cen">
				<view class="boxs-des">
					是否接入？
				</view>
				<view class="boxs-btn">
					<button type="default" @click="cutFn(false)">取消</button>
					<button type="default" @click="cutFn(true)">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import * as call from "@/uni_modules/RongCloud-CallWrapper/lib/index"
	import * as IMLib from "@/uni_modules/RongCloud-IMWrapper/js_sdk/index"
	import permision from "@/js_sdk/wa-permission/permission.js";
	import {isEmpty} from '@/libs/index.js';
	import {reasonDeal,errorDeal,imCode} from '@/libs/code.js'
	import config from "@/config/index.js";
	/*聊天组件*/
	import ryChatRoom from '@/components/IM/index.vue';
	export default {
		components:{
			ryChatRoom
		},
		data() {
			return {
				chatList:[],
				loginUserId: "",
				loginUserId1:true,
				loginUserId2:true,
				isLogining: "",
				isInitIm: false,
				form:{
					appkey:config.rongYunAppkey,
					token:'',
					navi:'https://nav-ucqa.rongcloud.net',
					mediaServer:''
				},
				isShow:false,
				libPage:false,
				isReceive:false,
				callSelect:'single',
				mediaSelect:'video',
				current:0,
				cur:0,
				callTypeArr:[
					{
						id:'single',
						label:'单聊'
					},
					{
						id:'group',
						label:'群聊'
					}
				],
				mediaTypeArr:[
					{
						id:'audio',
						label:'音频'
					},
					{
						id:'video',
						label:'音视频'
					}
				],
				targetId:'',
				isRoom:false,
				groupId:'',
				userIds:'',
				isCut:false,
				localSession:'',
				showMask:false,
				isPermission:false,
				isBeauty:false
			}
		},
		onLoad({id}) {
			console.log(id)
			// 初始化 CallLib
			call.init({});	
			/*连接视频通话*/
			this.linkUser(id);	
			call.onCallReceived( (res)=> {
				console.log(res)
				console.log("Engine:OnCallReceived=>"+"监听通话呼入, 目标id=>", res.data.targetId);
				this.isCut=true;
				this.localSession = res.data;
			});
			call.onCallDisconnected((res)=>{
				console.log(res)
				console.log("Engine:OnCallDisconnected=>"+"通话挂断/拒绝, 挂断原因=>", res.data.reason);
				this.isCut=false;
				// 重新渲染视频视图
				uni.$emit('OnCallDisconnected');
				uni.showToast({
					title:reasonDeal(res.data.reason),
					error:"error",
					icon:'none',
					duration:2000
				})
			});
			call.onCallConnected((res)=>{
				console.log(res)
				console.log("Engine:OnCallConnected=>"+"已建立通话通话接通时，通过回调 onCallConnected 通知当前 call 的详细信息", res);
			});
			call.onRemoteUserInvited((res)=>{
				console.log("Engine:OnRemoteUserInvited=>"+"通话中的某一个参与者，邀请好友加入通话 ,远端Id为=>", res.data.userId);
				uni.$emit('OnCallConnected');
			})
			call.onRemoteUserJoined((res)=>{
				console.log("Engine:OnRemoteUserJoined=>"+"主叫端拨出电话，被叫端收到请求后，加入通话，对端Id为=>", res.data.userId);
				uni.$emit('OnCallConnected');
			})
			call.onRemoteUserLeft((res)=>{
				console.log("Engine:OnRemoteUserLeft=>"+"远端用户挂断(群聊触发)，远端Id为=>", res.data.reason);
				// uni.$emit('OnCallConnected');
				uni.showToast({
					title:reasonDeal(res.data.reason),
					error:"error",
					icon:'none',
					duration:2000
				})
			})
			call.onCallOutgoing((res)=>{
				console.log('电话已拨出 主叫端拨出电话后，通过回调 onCallOutgoing 通知当前 call 的详细信息')
			})
			call.onRemoteUserRinging((res)=>{
				console.log('被叫端正在振铃，主叫端拨出电话，被叫端收到请求，发出振铃响应时，回调 onRemoteUserRingin,对端Id为=>', res.data.userId)
			})
			call.onError((res)=>{
				console.log('通话过程中，发生异常')
				uni.showToast({
					title:errorDeal(res.data.reason),
					error:"error",
					icon:'none',
					duration:2000
				});
			})
			call.onRemoteUserMediaTypeChanged((res)=>{
				console.log('当通话中的某一个参与者切换通话类型，例如由 audio 切换至 video，回调 onMediaTypeChanged,切换媒体类型的Id为=>',res.data.user.userId);
			})	
			/*聊天监听*/
			IMLib.addReceiveMessageListener((res)=>{
				this.receiveMessage(res)
			})
		},
		onUnload:function(){
			console.log('onUnload')
			this.removeAllListeners();
		},
		onBackPress(){
			console.log('返回')
			IMLib.disconnect();
		},
		methods: {
			linkUser(targetId){
				if(!targetId){console.log("未收到用户id");return;}
				let accountInfo=uni.getStorageSync('accountInfo');
				if(!accountInfo){return}
				accountInfo=JSON.parse(accountInfo);
				let rongyunToken=accountInfo.rongyunToken;
				rongyunToken=accountInfo.token
				this.form.token=rongyunToken;//连接融云的token
				this.targetId=targetId;//对方ID
				this.connect();					
			},
			removeAllListeners(){
				call.unInit();
				//移除监听-接收到通话呼入
				call.removeCallReceivedListener();
				// 移除监听-开始呼叫通话的回调
				call.removeCallOutgoingListener();
				// 移除监听-通话已接通
				call.removeCallReceivedListener();
				// 移除监听-通话已结束
				call.removeCallDisconnectedListener();
				// 移除监听-对端用户正在振铃
				call.removeRemoteUserRingingListener();
				// 移除监听-对端用户加入了通话
				call.removeRemoteUserJoinedListener();
				// 移除监听-有用户被邀请加入通话
				call.removeRemoteUserInvited();
				// 移除监听-对端用户挂断
				call.removeRemoteUserLeftListener();
				// 移除监听-对端用户切换了媒体类型
				call.removeRemoteUserMediaTypeChangedListener();
				// 移除监听-通话出现错误的回调
				call.removeErrorListener();
				
			},
			//是否接入
			cutFn(isFlag){
				//确认接入
				if(isFlag){
					this.isCut=false;
					if (this.localSession.callId && this.localSession.callId.length > 0) {
						this.onCallReceived(this.localSession);
					}
				}else{
				//取消接入
					this.isCut=false;
					call.hangup();
				}
			},
			//连接IM
			connect(){
				if(!this.form.appkey){
					uni.showToast({
						title:"请输入appKey",
						icon: "error",
						duration:2000
					})
					return;
				}
				if (!this.form.token) {
				    uni.showToast({
				    	title:"请输入token",
				    	icon: "error",
				    	duration:2000
				    })
				    return;
				  }
				  this.connectIM().then((userId)=>{
					  this.libPage = true;
					  this.loginUserId = userId;
					  uni.showToast({
						icon:"none",
					  	title:'连接成功,'+userId
					  });
					  if(uni.getSystemInfoSync().platform === 'android'){
						  permision.requestAndroidPermission('android.permission.CAMERA');
						  permision.requestAndroidPermission('android.permission.RECORD_AUDIO');
					  }
				  }).catch((e)=>{
						uni.setStorageSync('login-params',{
							appkey:this.form.appkey,
							token:this.form.token,
							navi:this.form.navi
						});
						console.log(e)
						console.log("连接IM发生错误... code=",e.message);
						uni.showToast({
							title:imCode(e),
							icon: "error",
							duration:2000
						})
						this.isInitIm=false;
					});			
			},
			//连接IM
			connectIM(){
				//判断是否初始化
				if(!this.isInitIm){
					if(this.form.navi){
						console.log('有nav')
						console.log(this.form.navi)
						IMLib.setServerInfo(this.form.navi,'')
					};
					IMLib.init(this.form.appkey)
					this.isInitIm = true;
				}else{
					uni.showToast({
						title:"正在连接。。。",
						icon: "error",
						duration:2000
					})
					return;
				}
				return new Promise((resolve,reject)=>{
						IMLib.connect(this.form.token,(res)=> {
							console.log('im已连接')
							console.log(res)
							if (res.code === 0) {
								uni.setStorageSync('login-params',{
									appkey:this.form.appkey,
									token:this.form.token,
									navi:this.form.navi
								});
								resolve(res.userId);
							} else {
								reject(res.code);
							}
						});
				});
				
			},
			//呼叫
			callOut(){
				
				//单聊音频
				if(this.callSelect ==='single'&&this.mediaSelect ==='audio'){
					if(this.targetId === ''){
						uni.showToast({
							title:"请输入对方ID",
							icon: "error",
							duration:2000
						})
						return;
					}
					this.callMsg(this.mediaSelect,this.targetId,this.callSelect);
				}else if(this.callSelect ==='single'&&this.mediaSelect ==='video'){
					if(this.targetId === ''){
						uni.showToast({
							title:"请输入对方ID",
							icon: "error",
							duration:2000
						})
						return;
					}
					//单聊视频
					this.callMsg(this.mediaSelect,this.targetId,this.callSelect);
				}else if(this.callSelect ==='group'&&this.mediaSelect ==='video'){
					let userIdsArr = this.userIds.split(',');
					uni.setStorageSync('room-parameters', {
						callType: 'out',
						mediaType: this.mediaSelect,
						targetId: '',
						callSelect:this.callSelect,
						groupId:this.groupId,
						userIds:userIdsArr
					});
					uni.navigateTo({
						url:'/pages/chatRoom/chatRoom'
					});
				}else if(this.callSelect ==='group'&&this.mediaSelect ==='audio'){
					let userIdsArr = this.userIds.split(',');
					uni.setStorageSync('room-parameters', {
						callType: 'out',
						mediaType: this.mediaSelect,
						targetId: '',
						callSelect:this.callSelect,
						groupId:this.groupId,
						userIds:userIdsArr
					});
					uni.navigateTo({
						url:'/pages/chatRoom/chatRoom'
					});
				}
			},
			callMsg(mediaSelect,targetId,callSelect){
				console.log(targetId)
				console.log(mediaSelect)
				uni.setStorageSync('room-parameters', {
					callType: 'out',
					mediaType: mediaSelect,
					targetId: targetId,
					callSelect:callSelect
				});
				uni.navigateTo({
					url:'/pages/chatRoom/chatRoom'
				});
			},
			//通话类型切换
			callChange(e){
				this.callSelect = e.target.value;
			},
			//媒体类型切换
			mediaChange(e){
				this.mediaSelect = e.target.value;
			},
			//是否接收逻辑
			onCallReceived(session) {
				// //呼入
				uni.setStorageSync('room-parameters', {
					callType: 'in',
					mediaType: session.mediaType === 0 ? 'audio' : 'video'
				});
				//跳转.nvue
				uni.navigateTo({
					url:'/pages/chatRoom/chatRoom'
				});
			},
			//组件发消息回调
			chatSend(info){
				if(isEmpty(info)){
					return;
				}
				let item={
					msg:info,
					type:'mine',
					user:'自己'
				}
				this.chatList.push(item);
			},
			//融云发送消息
			sendMsgIM(){
				const msg = {
					conversationType: ConversationType.PRIVATE,// 会话类型
					targetId: '会话 ID',
					content: {
						objectName: objectName,
						content: '发送内容',
						extra: '附加内容'
					},
					pushContent: '当下发远程推送消息时，在通知栏里会显示这个字段。',
					pushData: '远程推送附加信息',
				}
				sendMessage(msg, (result) => {
					// 消息发送成功
				  if(result.code === 0){
					  console.log(result.messageId)
				  }
				});					
			},
			// 接受消息回调
			receiveMessage(res){
				console.log(res)
				let item={
					msg:res,
					user:'对方'
				}
				this.chatList.push(item);			
			}
		}
	}
</script>
<style lang="less" scoped>
	page{
		height: 90vh;
		overflow-y:hidden;
	}
	.content-lab{
		text-align: center;
		.btn{
			display: inline-block;
			color: #fff;
			background: #2da2ea;
			margin-top: 20px;
		}		
	}
	.boxs{
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		background: rgba(0,0,0,.5);
		z-index: 9999;
	
	}
	.boxs-cen{
		width: 80%;
		height: 300upx;
		background: #FFFFFF;
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		margin: auto;
		border-radius: 4upx;
	}
	.boxs-des{
		margin-top: 50upx;
		color: #000000;
		text-align: center;
	}
	.boxs-btn{
		margin-top: 50upx;
		display: flex;
		justify-content: space-between;
	}	
   .loading{
		width: 150upx;
		height: 100upx;
		margin: 260upx auto 0;
		display: flex;
		justify-content: space-around;
		align-items: center;
		span{
			display: inline-block;
			width: 8px;
			height: 100%;
			border-radius: 4px;
			background: lightgreen;
			-webkit-animation: load 1.04s ease infinite;
			&:nth-child(2){
				-webkit-animation-delay:0.13s;
			}
			&:nth-child(3){
				-webkit-animation-delay:0.26s;
			}
			&:nth-child(4){
				-webkit-animation-delay:0.39s;
			}
			&:nth-child(5){
				-webkit-animation-delay:0.52s;
			}		
		}		
	}
	@-webkit-keyframes load{
		0%,100%{
			height: 80upx;
			background: lightgreen;
		}
		50%{
			height: 120upx;
			margin-top: -20px;
			background: lightblue;
		}
	}	
	
		.loading-type2{
            width:500upx;
            height: 60px;
            margin: 0 auto;
            margin-top: 10px;
            position: relative;
			span{
				width: 50px;
				height: 30px;
				border-radius: 50%;
				background: lightgreen;
				position: absolute;
				top: 50%;
				margin-top: -15px;
				overflow: hidden;
				-webkit-animation: changePosition 2.4s linear infinite;	
			}			
        }
        @-webkit-keyframes changePosition{
            0%,100%{
                -webkit-transform: translate(70px);
            }
            20%{
                width: 50px;
                height: 30px;
                margin-top:-15px;
                -webkit-transform: translate(0px);
            }
            30%{
                width: 20px;
                height: 60px;
                margin-top:-30px;
                -webkit-transform: translate(0px);
            }
            35%{
                width: 50px;
                height: 30px;
                margin-top:-15px;
                -webkit-transform: translate(5px);
                background: lightblue;
            }
            70%{
                width: 50px;
                height: 30px;
                margin-top:-15px;
                -webkit-transform: translate(400upx);
            }
            80%{
                width: 20px;
                height: 60px;
                margin-top:-30px;
                -webkit-transform: translate(400upx);
            }
            85%{
                width: 50px;
                height: 30px;
                margin-top:-15px;
                -webkit-transform: translate(390upx);
                background: lightgreen;
            }

        }	
</style>
