<template>
	<page-meta :page-font-size="fontValue+'px'" :root-font-size="fontValue+'px'"></page-meta>
	<view>
		<cu-custom :isBack='true' >
		   <template v-slot:content>
		     <text class="text-jiachu text-black">群组通话</text>
		   </template>
		 </cu-custom>
		 <view class="IncolumnC">
		 	<image class="AvatarImg" :src="friendAvatar" mode="scaleToFill"></image>
		 	<text v-if="friend.value" class="text-black text-lg"></text>
		 	<text class="text-black text-lg" style="margin-top: 10rpx;">{{friendName}}</text>
			<view class="InrowC" style="margin-top: 80rpx;">
		 		<text class="text-black text-lg">{{stateNote}}</text>
		 		<image style="width: 52rpx;height: 52rpx;margin-left: 6rpx;" src="/static/mine/loading2.gif" mode=""></image>
		 	</view>
			<view class="InrowC" style="margin-top: 300rpx;">
				<image v-if="!canClose" style="width:110rpx ;height: 110rpx;" src="/static/mine/icon_on.png" mode="scaleToFill" @click="acceptWebrtc"></image>
				<image v-if="canClose" style="width:110rpx ;height: 110rpx;" src="/static/mine/icon_off.png" mode="scaleToFill" @click="closeWebrtcBT"></image>
				<image v-if="speacker" style="margin-left: 50rpx;width:110rpx ;height: 110rpx;" src="/static/mine/ysq_on.png" mode="scaleToFill" @click="changeSpeack"></image>
				<image v-if="!speacker" style="margin-left: 50rpx;width:110rpx ;height: 110rpx;" src="/static/mine/ysq_off.png" mode="scaleToFill" @click="changeSpeack"></image>
			</view>
		 </view>
	</view>
</template>

<script setup lang="ts">
	import {onLoad,onReady,onShow,onUnload} from '@dcloudio/uni-app';
	import {ref,watch} from 'vue'
	import * as ASCIIUtils from '@/uni_modules/wrs-js-modbusCRCHex/js_sdk/wrs-ASCIIUtils.js';
	import * as HexUtils from '@/uni_modules/wrs-js-modbusCRCHex/js_sdk/wrs-HexUtils.js';
	import {
		UTSWebRTC
	} from "@/uni_modules/wrs-uts-webrtc";
	import {
		UTSVoipMgr
	} from "@/uni_modules/wrs-uts-voip"
	
	import MessageUtils from "@/utils/MessageUtils";
	import CuCustom from '@/colorui/components/cu-custom.vue'
	import UserApi from "@/api/UserApi";
	import {useUserStore} from '@/store/userStore'
	import {useWsStore} from "@/store/WsStore";
	import {storeToRefs} from "pinia";
	import type Webrtc from '@/mode/Webrtc';
	import ChatType from "@/utils/ChatType";
	import {usePeerStore} from "@/store/peerStore";
	import SendCode from '@/utils/SendCode'
    import Auth from "@/api/Auth";
    const fontValue=ref(Auth.getfontSize());
	
	let webRTC = new UTSWebRTC();
	let candidateList=[];
	let usersId = [];
	let otherPersons=[];
	let friendAvatar='/static/logo512.png';
	let friendName='';
	let stateNote =ref("正在呼叫");
	let audioObj=null;
	const timeCall=ref(0);
	const timer=ref();
	
	const wsStore = useWsStore();
	const peerStore = usePeerStore();
	const friendId = ref("");
	const friend = ref("");
	
	const startTime = ref(0)
	const isCaller = ref(false);
	const showVideo = ref(false);
	const speacker = ref(false);
	const canClose = ref(true);
	const user = useUserStore().getUser()
	const isConnect = ref(false)
	const videoIsOpen = ref(false)
	const hadClose = ref(false);

	const androidpermission = ref(false);
	
	const {isClose} = storeToRefs(peerStore)
	const {offer} = storeToRefs(peerStore)
	const {answer} = storeToRefs(peerStore)
	const {candidate} = storeToRefs(peerStore)
	const {isAccept} = storeToRefs(peerStore)
	
	
	
	watch(isAccept, (newVal) => {
	  if (newVal) {
		  timeCall.value=45;
		  startTime.value = new Date().getTime()
		  createPeerConnection(friendId.value);
	      getoffer();
	  }
	})
	watch(isClose, (newVal) => {
		console.log('isCloseisClose',newVal)
	  if (newVal) {
		  if(videoIsOpen.value){
		  	//通知视频播放页面关闭
			let data={
				type:'isClose'
			}
			uni.$emit('webRTCvideoE', { msg:JSON.stringify(data)});
		  }
		  else{
			  uni.navigateBack()
		  }
	    
	  }
	})
	
	watch(offer, (newVal) => {
	  if (newVal) {//收到offer
		  recOffer(newVal);
	  }
	})
	watch(answer, (newVal) => {
	  if (newVal) {//收到answer
		  recAnswer(newVal);
	  }
	})
	
	watch(candidate, (newVal) => {
	  if (newVal) {//收到candidate
	    console.log('candidate--------');
		recCandidate(newVal);
	  }
	})
	
	const chaoshipanduan = () => {
		timeCall.value=45;
		timer.value = setInterval(() => {
			timeCall.value=timeCall.value-1;
			if(timeCall.value==0&&!isConnect.value){
				MessageUtils.message('暂时无法连接，请稍后重试！')
			}
			else if(isConnect.value){
				clearInterval(timer.value);//正常接通
				return;
			}
			else if(timeCall.value<-2&&!isConnect.value){
				uni.navigateBack();
			}
		}, 1000);
	}
	
	const audioObjstart = () => {
		audioObj=uni.createInnerAudioContext();
		audioObj.loop=true;
		audioObj.volume=0.2;
		audioObj.src='/hybrid/html/images/calling.mp3';
		audioObj.play();
	}
	
	const audioObjstop = () => {
		if(audioObj){
			audioObj.stop();
		}
	}
	
	onShow(()=>{
		// console.log('onShow',videoIsOpen.value)
		if(videoIsOpen.value){
			uni.navigateBack();
			return;
		}
		if(uni.getSystemInfoSync().platform == "ios"){
			let state = UTSVoipMgr.getApplicationState();
			if(state!=2){
				if(!isCaller.value){
					//let provider = new UTSCXProvider()
					UTSVoipMgr.endCall({
						uuid: uni.getStorageSync("voip_UUID")
					}, (resp: any)=>{
						console.log(JSON.stringify(resp))
					})
				}
				initData();
				//getfriendMsg();
				//audioObjstart();
				setTimeout(function() {
				  // 这里写要延时执行
				  if(isCaller.value){//主动发起通话
				  }
				  else{
				  	//acceptWebrtc();//自动接听
					receiveJoin(friendId.value);
				  }
				}, 1500);
			}
		}
		else{
			initData();
			//getfriendMsg();
			setTimeout(function() {
			  // 这里写要延时执行
			  if(isCaller.value){//主动发起通话
			  }
			  else{
				receiveJoin(friendId.value);
			  	//acceptWebrtc();//自动接听
			  }
			}, 1500);
		}
		
		// console.log('getApplicationstate2-------',state);
		
	})
	onReady(()=>{
		console.log('onReady');
		chaoshipanduan();
		setTimeout(function() {
		  // 这里写要延时执行的代码
		  if(showVideo.value){
		    console.log('onReady1');
		    webRTC.setSpeakerEnable(true)
			speacker.value=true;
		  }
		  else{
		    console.log('onReady2');
		    webRTC.setSpeakerEnable(false)
		  }
		}, 300); 
	});
	onLoad((opt) => {
		console.log(opt)
		usePeerStore().updateBusyStatus(true)
		usePeerStore().updateCloseStatus(false)
		if(typeof opt?.showVideo === 'string'){
		  showVideo.value = opt?.showVideo === 'true'
		}
		candidateList=[];
		friendId.value = opt?.friendId;
		
		if(typeof opt?.isCaller === 'string'){
		  isCaller.value = opt?.isCaller === 'true'
		  if(isCaller.value){
			  canClose.value = true;
			  console.log('onLoad',usePeerStore().users);
			  usersId=JSON.parse(usePeerStore().users);
			  joinRoom();
		  }
		  console.log('isCaller',canClose);
		}
		audioObjstart();
		
		// 开始本地抓流
		if (uni.getSystemInfoSync().platform == "ios") {
			
		}
		else{
			requestPermission([
				"android.permission.CAMERA",
				"android.permission.RECORD_AUDIO"
			])
		}
		
	});
	
	onUnload(()=>{
		clearInterval(timer.value);//正常接通
		audioObjstop();
		if(!hadClose.value){
			closeWebrtc();
		}
		webRTC.destroyAllPeerConnection();
		peerStore.setCallId(undefined);
		peerStore.setOffer(undefined);
		peerStore.setAnswer(undefined);
		peerStore.setCandidate(undefined);
		peerStore.updateBusyStatus(false);
		peerStore.updateCloseStatus(false);
		peerStore.setIsAccept(false);
	});
	const requestPermission = (permissions:any) =>{
		plus.android.requestPermissions(
			permissions,
			function(resultObj) {
				for (var i = 0; i < resultObj.granted.length; i++) {
					var grantedPermission = resultObj.granted[i];
					androidpermission.value=true;
					console.log('已获取的权限：' + grantedPermission);
					if(grantedPermission=='android.permission.CAMERA'){
						webRTC.startVideoCapture({
							isFront:true,
							width: 1280,
							height: 720,
							fps: 30
						})
					}
				}
				for (var i = 0; i < resultObj.deniedPresent.length; i++) {
					var deniedPresentPermission = resultObj.deniedPresent[i];
					console.log('拒绝本次申请的权限：' + deniedPresentPermission);
				}
				for (var i = 0; i < resultObj.deniedAlways.length; i++) {
					var deniedAlwaysPermission = resultObj.deniedAlways[i];
					console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
				}
				// 若所需权限被永久拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限  
				if (resultObj.deniedAlways.length > 0) {
					// var Intent = plus.android.importClass("android.content.Intent");
					// var Settings = plus.android.importClass("android.provider.Settings");
					// var Uri = plus.android.importClass("android.net.Uri");
					// var mainActivity = plus.android.runtimeMainActivity();
					// var intent = new Intent();
					// intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
					// var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
					// intent.setData(uri);
					// mainActivity.startActivity(intent);
				}
			},
			function(error) {
				console.log('申请权限错误：' + error.code + " = " + error.message);
			});
	}
	
	const initData = () =>{
		console.log('initWebRTC')
		// 设置webRTC的回调
		webRTC.onCallback((resp:any) => {
			let opt = resp.opt
			console.log("webRTC.onCallback opt:" + opt)
			switch (opt) {
				// 信令状态改变
				case "onSignalingChange": {
					console.log("onSignalingChange:" + JSON.stringify(resp))
					let state = resp.state
					if (state) {
						switch (state) {
							case 0: {
								console.log("RTCSignalingStateStable")
							}
							break;
							case 1: {
								console.log("RTCSignalingStateHaveLocalOffer")
							}
							break;
							case 2: {
								console.log("RTCSignalingStateHaveLocalPrAnswer")
							}
							break;
							case 3: {
								// 
								console.log("RTCSignalingStateHaveRemoteOffer")
							}
							break;
							case 4: {
								console.log("RTCSignalingStateHaveRemotePrAnswer")
							}
							break;
							case 5: {
								console.log("RTCSignalingStateClosed")
								let userId = resp.userId
								if (userId) {
									//this.userLeave(userId)
								}
							}
		
							break;
							default:
								break;
						}
					}
				}
				break;
				case "onIceGatheringChange": {
					console.log("onIceGatheringChange:" + JSON.stringify(resp))
					let state = resp.state
					if (state) {
						switch (state) {
							case 0: {
								console.log("RTCIceGatheringStateNew")
							}
							break;
							case 1: {
								console.log("RTCIceGatheringStateGathering")
							}
							break;
							case 2: {
								console.log("RTCIceGatheringStateComplete")
							}
							break;
							default:
								break;
						}
					}
				}
				break;
				// 生成IceCandidate
				case "onIceCandidate": {
					let userId = resp.userId
					console.log("onIceCandidate--",userId)
					let candidate = resp.iceCandidate
					let data = {
						candidate: candidate.sdp,
						sdpMLineIndex: candidate.sdpMLineIndex,
						sdpMid: candidate.sdpMid,
					}
					let tempList = [];
					tempList.push(data);
					sendCandidate(tempList);	
				}
				break;
				case "onIceConnectionChange": {
					console.log("onIceConnectionChange:" + JSON.stringify(resp))
					let state = resp.state
					switch (state) {
						case 0: {
							console.log("RTCIceConnectionStateNew")
						}
						break;
						case 1: {
							console.log("RTCIceConnectionStateChecking")
						}
						break;
						case 2: {
							// 这步没有
							console.log("RTCIceConnectionStateConnected");
							stateNote.value ='已连接';
							isConnect.value=true;
							audioObjstop();
							console.log('------1',showVideo.value,videoIsOpen.value)
							if(showVideo.value&&!videoIsOpen.value){//打开视频
							    videoIsOpen.value=true;
								webRTC.setSpeakerEnable(true)
								console.log('------2',showVideo.value,videoIsOpen.value)
								uni.navigateTo({
									url:'/imcall/webRTCVideoView'
								})
								setTimeout(function() {
								  // 这里写要延时执行的代码
								  let data={
								  	type:'users',
								  	users:otherPersons
								  }
								  uni.$emit('webRTCvideoE', { msg:JSON.stringify(data)});
								}, 1000);
							}
						}
						break;
						case 3: {
							console.log("RTCIceConnectionStateCompleted")
						}
						break;
						case 4: {
							console.log("RTCIceConnectionStateFailed")
							stateNote.value ='连接已断开';
							
						}
						break;
						case 5: {
							// 通讯被断开，一般是对方掉线或者STUN/TURN 服务器问题：如果 ICE 服务器配置不当，或者 STUN/TURN 服务器不可用，可能会导致连接失败。确保你的 STUN/TURN 服务器正常工作并且可达。
							stateNote.value ='连接已断开';
							console.log("RTCIceConnectionStateDisconnected")
							let data={
								type:'state',
								stateNote:stateNote.value
							}
							uni.$emit('webRTCvideoE', { msg:JSON.stringify(data)});
							let userId = resp.userId
							if (userId) {
								//this.userLeave(userId)
							}
						}
						break;
						case 6: {
							console.log(" RTCIceConnectionStateClosed")
							stateNote.value ='连接已断开';
							let userId = resp.userId
							if (userId) {
								//this.userLeave(userId)
							}
						}
						break;
						case 7: {
							console.log(" RTCIceConnectionStateCount")
						}
						break;
						default:
							break;
					}
		
				}
		
				break;
				// 收到其他用户的音频或视频流
				case "onAddStream": {
					let userId = resp.userId
					console.log("onAddStream:",resp)
					if (userId) {
						let stream = resp.stream
						if (stream) {
							// 如果有视频流，则显示其他用户的视频
							let videoTracks = stream.videoTracks
							if (videoTracks) {
								if (videoTracks.length > 0) {
									let users=[];
									users.push(friendId.value);
									let exist =existUser(userId)
									if (!exist) {
										console.log("显示远程视频流:" + userId)
										otherPersons.push({
											userId: userId
										})
										let data={
											type:'users',
											users:otherPersons
										}
										uni.$emit('webRTCvideoE', { msg:JSON.stringify(data)});
									}
								}
							}
						}
					}
		
				}
				break;
				case "onRemoveStream": {
		
				}
				break;
		
				default:
					break;
			}
		})
		console.log('initWebRTC11')
		// 初始化视频
		webRTC.initVideoTrack({
			trackId: "video0",
			isScreencast: false // 仅对Android生效
		})
		// 初始化音频
		webRTC.initAudioTrack({
			trackId: "audio0"
		})
		console.log('initWebRTC22')
		if (uni.getSystemInfoSync().platform == "ios") {
			webRTC.configureAudioSession({
				category: "playAndRecord",
				mode: "voiceChat"
			})
		} else {
			
		}
		// 开始本地抓流
		if (uni.getSystemInfoSync().platform == "ios") {
			webRTC.startVideoCapture({
				isFront:true,
				width: 1280,
				height: 720,
				fps: 30
			})
		}
	};
	
	const getfriendMsg = () => {
		UserApi.getUser(friendId.value).then((res) => {
		  friend.value = res.data
		  if (friend.value) {
		    friendName=friend.value.name;
			friendAvatar=encodeURI(friend.value.avatar);
			if(isCaller.value){//主动发起通话
				//sendcallingMsg();
			}
			else{
				//acceptWebrtc();//自动接听
			}
		  }
		})
	}
	
	const changeSpeack = () => {
		if(speacker.value){
			speacker.value=false;
		}
		else{
			speacker.value=true;
		}
		console.log('setAudioEnabled',speacker.value)
		webRTC.setSpeakerEnable(speacker.value)
	}
	
	const acceptWebrtc = () => {
		console.log('acceptWebrtc');
		//给自己发一份忙碌状态，多个客户端同一个人不能同时接受，需要客户端接受后，其他客户端就关闭
		let data={
		    code: SendCode.WEBRTC_BUSY,
		    message: {
				chatId:friendId.value,
				fromId: user.id,
				type: ChatType.FRIEND,
				msgtype:'accept',
				video: showVideo.value,
		    }
		}
		console.log(data);
		useWsStore().send(JSON.stringify(data));
		canClose.value = true;
	}
	const closeWebrtcBT = () => {
		uni.navigateBack();
	}
	const closeWebrtc = () => {
		if (user.id) {
		  const closeMessage = {
		    code: SendCode.WEBRTC_CLOSE,
		    message: {
		      chatId:friendId.value,
		      fromId: user.id,
		      timestamp: new Date().getTime(),
		      type: ChatType.FRIEND,
		      msgtype:'close'
		    }
		  }
		  wsStore.send(JSON.stringify(closeMessage))
		  hadClose.value=true;
		  console.log('发送关闭消息', closeMessage)
		  //发起方才有发送视频结果消息的权限
		  if (isCaller.value) {
		    //界面展示视频消息情况，例如：对方是否接受了视频通话，通话时长
		    const message= {
				id:null,
				localtime:null,
				mine:true,
		        messageType:SendCode.WEBRTC_result,
		        chatId:friendId.value,
		        fromId: user.id,
		        timestamp: new Date().getTime(),
		        type: ChatType.FRIEND,
		        result: isConnect.value,
		        video: showVideo.value,
		        duration: isConnect.value ? new Date().getTime() - startTime.value : 0
		    }
		    console.log(message)
		    wsStore.sendWEBRTCresult(message);
		  }
		}
	}
	const sendSocketData = (data:any) => {
		wsStore.sendWEBRTC(data)
		console.log('发送消息', data);
	}
	
	const sendCandidate = (candidateList:any) =>{
		let msg: Webrtc = {
		  chatId: friendId.value,
		  fromId: user.id,
		  type: ChatType.FRIEND,
		  msgtype:'candidate',
		  conetType:showVideo.value,
		  payload:JSON.stringify(candidateList)
		}
		console.log("将本机candidate发送给对方")
		sendSocketData(msg);
	}
	
	//主动发起通话操作，isCaller为true-----------------------------
	const sendcallingMsg = (othfriendId:any) => {
		console.log('sendcallingMsg');
		let msg: Webrtc = {
		  chatId:othfriendId,
		  fromId: user.id,
		  type: ChatType.GROUP,
		  msgtype:'calling',
		  conetType:showVideo.value,
		  timestamp: new Date().getTime(),
		  payload:''
		}
		let data={
			code:SendCode.WEBRTC_CALL,
			message: msg
		}
		console.log('sendcallingMsg',data);
		useWsStore().send(JSON.stringify(data))
	}
	// 创建与某个用户的连接
	const createPeerConnection = (userId:any) => {
		let hasPeerConnection = webRTC.hasPeerConnection({
			userId: userId
		})
		if (!hasPeerConnection) { // 如果没有连接则创建连接
			console.log("当前用户没有连接，正在创建")
			
			let params = {
				iceServers:[],
				sdpSemantics:1,
				continualGatheringPolicy:1,
				constraints:{},
				userId:''
			}
			
			params.iceServers = [{
					urls: ["stun:203.175.169.52:3478",
						"turn:203.175.169.52:3478"
					],
					username: 'aaaaa',
					credential: 'bbbbb'
				}
			]
			
			params.userId = userId;
			params.sdpSemantics = 1 // 0: RTCSdpSemanticsPlanB 1:RTCSdpSemanticsUnifiedPlan
			params.continualGatheringPolicy =
				1 // 0: RTCContinualGatheringPolicyGatherOnce 1: RTCContinualGatheringPolicyGatherContinually
			params.constraints = {
				mandatory: {},
				optional: {
					DtlsSrtpKeyAgreement: "true"
				}
			}
			userId = webRTC.createPeerConnection(params)
			// 给连接添加本地视频
			console.log("添加本地视频")
			let videoResp = webRTC.addVideoTrack({
				userId: userId,
				streamIds: ["video0"]
			})
			let videoFlag = videoResp.flag
			if (!videoFlag) {
				console.log("添加本地视频出错:" + JSON.stringify(videoFlag))
			}
			// 给连接添加本地音频
			console.log("添加本地音频")
			let audioResp = webRTC.addAudioTrack({
				userId: userId,
				streamIds: ["audio0"]
			})
			let audioFlag = audioResp.flag
			if (!audioFlag) {
				console.log("添加本地音频出错:" + JSON.stringify(videoFlag))
			}
		} else {
			console.log("已经有连接，无需创建")
		}
	};
	
	const getoffer = () => {
		// var videoV="false";
		// if(showVideo.value){
		// 	videoV="true";
		// }
		console.log('getoffer')
		webRTC.createOffer({
		    userId:friendId.value,
		    setLocalDescription: false
		}, (resp:any) => {
			console.log(resp);
				let flag = resp.flag
				if (flag) {
					let sessionDescription = resp.sessionDescription
					let type = sessionDescription.type
					let sdp = sessionDescription.sdp
					console.log('sessionDescription',sessionDescription)
					
					webRTC.setLocalDescription({
						userId: friendId.value,
						type: type,
						sdp: sdp
					}, (localDescResp:any) => {
						let localFlag = localDescResp.flag
						console.log('setLocalDescription',localFlag)
					})
					
					let data = {
						type: "SessionDescription",
						payload: {
							sdp:sdp,
							type: type
						}
					}
					let msg: Webrtc = {
					  chatId: friendId.value,
					  fromId: user.id,
					  type: ChatType.FRIEND,
					  msgtype:'offer',
					  conetType:showVideo.value,
					  payload:JSON.stringify(data.payload)
					}
					// 发送给接听方
					sendSocketData(msg)
		        }
		    }
		)
		
	}
	
	//收到answer
	const recAnswer = (strdata:string) => {
		let data=JSON.parse(strdata);
		console.log("recOffer:--",data)
		if(data.msgtype!='answer'){
			return;
		}
		
		let answer=JSON.parse(data.payload)
		console.log('answeroffer1----',answer);
		createPeerConnection(data.fromId)
		webRTC.setRemoteDescription({
			userId:data.fromId,
			type: "answer",
			sdp: answer.sdp
		}, (resp:any) => {
			let flag = resp.flag
			console.log('answeroffer2----',resp);
		})
		
	}
	
	//被动接听通话操作，isCaller为false-----------------------------
	//收到recOffer
	const recOffer = (strdata:string) => {
		let data=JSON.parse(strdata);
		console.log("recOffer:--",data)
		if(data.msgtype!='offer'){
			return;
		}
		createPeerConnection(data.fromId)
		// 设置远程Description
		let payload=JSON.parse(data.payload);
		
		webRTC.setRemoteDescription({
			userId:data.fromId,
			type: payload.type,
			sdp: payload.sdp
		}, (resp) => {
			let flag = resp.flag
			if (flag) {
				console.log("生成answer")
				// 生成answer
				webRTC.createAnswer({
					userId:data.fromId,
					setLocalDescription: false
				}, (answerResp:any) => {
					let flag = answerResp.flag
					if (flag) {
						// console.log("createAnswer result:" + JSON.stringify())
						let sessionDescription = answerResp.sessionDescription
						let type = sessionDescription.type
						let sdp = sessionDescription.sdp
						// 设置本地Description
						console.log("设置setLocalDescription")
						webRTC.setLocalDescription({
							userId:data.fromId,
							type: type,
							sdp: sdp
						}, (localDescResp:any) => {
							let localFlag = localDescResp.flag
							if (localFlag) {
								// 发送answer
								let msg: Webrtc = {
								  chatId:data.fromId,
								  fromId:user.id,
								  type: ChatType.FRIEND,
								  msgtype:'answer',
								  conetType:showVideo.value,
								  payload:JSON.stringify({sdp:sdp,type: type})
								}
								console.log('answer',msg)
								sendSocketData(msg)
							} else {
								console.log("setLocalDescription error:" + JSON
									.stringify(
										localDescResp))
							}
						})
					} else {
						console.log("createAnswer error:" + JSON.stringify(resp))
					}
				})
				
			} else {
				console.log("setRemoteDescription error:")
			}
		})
	}
	
	const recCandidate = (strdata:any) => {
		
		let data = JSON.parse(strdata);
		console.log(data);
		if(data.msgtype!='candidate'){
			return;
		}
		
		let hasPeerConnection = webRTC.hasPeerConnection({userId: data.fromId})
		if (!hasPeerConnection) {
			return
		}
		let datalist = JSON.parse(data.payload)
		datalist.forEach((item) => {
			console.log("添加远程IceCandidate:" + JSON.stringify(item))
			// 添加远程IceCandidate
			webRTC.addIceCandidate({
				userId:data.fromId,
				sdpMid:item.sdpMid,
				sdpMLineIndex: item.sdpMLineIndex,
				sdp: item.candidate
			}, (resp:any) => {
				let flag = resp.flag
				if (!flag) {
					console.log("addIceCandidate error:" + JSON.stringify(resp))
				}
			})
		})
	}
	
	// const answer = () => {
	// 	var videoV="false";
	// 	if(showVideo.value){
	// 		videoV="true";
	// 	}
	// 	webRTC.answer({
	// 		OfferToReceiveAudio: "true",
	// 		OfferToReceiveVideo:videoV
	// 	}, (resp) => {
	// 		let flag = resp.flag
	// 		if (flag) {
	// 			let sdp = resp.sdp
	// 			let type = ""
	// 			switch (sdp.type) {
	// 				case 0:
	// 					type = "offer"
	// 					break;
	// 				case 1:
	// 					type = "prAnswer"
	// 					break;
	// 				case 2:
	// 					type = "answer"
	// 					break;
	// 				case 3:
	// 					type = "rollback"
	// 					break;
	// 				default:
	// 					break;
	// 			}
	// 			let data = {
	// 				type: "SessionDescription",
	// 				payload: {
	// 					sdp: sdp.sdp,
	// 					type: type
	// 				}
	// 			}
	// 			// 发送给呼叫方
	// 			let msg: Webrtc = {
	// 			  chatId:friendId.value,
	// 			  fromId:user.id,
	// 			  type: ChatType.FRIEND,
	// 			  msgtype:'answer',
	// 			  conetType:showVideo.value,
	// 			  payload:JSON.stringify(data.payload)
	// 			}
	// 			console.log('answer',msg)
	// 			sendSocketData(msg)
	// 		} else {
	// 			console.log(resp)
	// 		}
	// 	})
	// }
//--------------------------------------------------
// 本人加入房间
const joinRoom = () => {
	// 发送消息给房间里的其他人，有新人加进来了，由其他人生成offer返回给自己，自己再返回offer给其他人
	usersId.forEach((item: any) => {
		if(user.id!=item){
			sendcallingMsg(item);
		}
	})
}

const receiveJoin = (userId:any) => {
	if (userId) {
		let exist =existUser(userId)
		if (exist) {
			console.log("该用户已经在房间里:" + userId)
			return
		}
		console.log("新用户加入房间:" + userId)
		// 创建了与这个用户的连接
		createPeerConnection(userId)

		// 生成offer
		console.log("生成offer")
		webRTC.createOffer({
			userId: userId,
			setLocalDescription: false
		}, (resp:any) => {
			let flag = resp.flag
			if (flag) {
				let sessionDescription = resp.sessionDescription
				let type = sessionDescription.type
				let sdp = sessionDescription.sdp
				// 设置本地Description
				console.log("设置本地Description:" + JSON.stringify(sessionDescription))
				webRTC.setLocalDescription({
					userId: userId,
					type: type,
					sdp: sdp
				}, (localDescResp:any) => {
					let localFlag = localDescResp.flag
					if (localFlag) {
						// 将offer发送给对方
						console.log("发送offer:" + JSON.stringify(sdp))
						let data = {
							type: "SessionDescription",
							payload: {
								sdp:sdp,
								type: type
							}
						}
						let msg: Webrtc = {
						  chatId: friendId.value,
						  fromId: user.id,
						  type: ChatType.FRIEND,
						  msgtype:'offer',
						  conetType:showVideo.value,
						  payload:JSON.stringify(data.payload)
						}
						// 发送
						sendSocketData(msg)
					} else {
						console.log("setLocalDescription error:" + JSON.stringify(
							localDescResp))
					}
				})
			} else {
				console.log("createOffer error:" + JSON.stringify(resp))
			}
		})
	}
}

const existUser = (userId) => {
	for (let i = 0; i < otherPersons.length; i++) {
		let user = this.otherPersons[i]
		if (user.userId == userId) {
			return true
		}
	}
	return false
}
				
</script>

<style>
.AvatarImg{
	margin-top: 40rpx;
	width: 160rpx;
	height: 160rpx;
	border-radius: 10rpx;
}
.IncolumnC{
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content:center;
}
.InrowC{
	display: flex;
	flex-direction:row;
	align-items: center;
	justify-content:center;
}
</style>
