<template>
	<view class="videoContont">
		<image style="width: 750rpx;position: absolute;top: 0;left: 0;z-index: 1;" :style="{height:sysInfoHeight+'px'}"
			src="../../static/images/my/videoBg.png" mode=""></image>
		<!-- 对方的视频 -->
		<trtc-remote-view v-if="remoteUserId" :userId="remoteUserId" :viewId="remoteUserId"
			style="width: 750rpx;position: absolute;top: 0;left: 0;z-index: 333 !important;"
			:style="{height:sysInfoHeight+'px'}"></trtc-remote-view>
		<!-- 我的视频大/小 -->
		<view :class="isJie?'mySmartVideo':'myVideo'" :style="{height:isJie?'300rpx':sysInfoHeight+'px'}">
			<trtc-local-view :userId="userId" :viewId="userId" style="flex: 1;"></trtc-local-view>
		</view>

		<!-- 顶部信息 -->
		<view class="topInfo" v-if="isRol == 1 && userType == 2">
			<image class="topInfo-avatar" :src="resumesIdInfo.avatar" mode="aspectFill"></image>
			<text class="topInfo-name">
				{{resumesIdInfo.resumesName}}
			</text>
			<view class="topInfo-time">
				<!-- 邀请你语音通话... -->
				<smhTimer v-if="isJie" ref="timer" :auto="isJie" />
			</view>
		</view>
		<view class="topInfo" v-if="isRol == 1 && userType == 1">
			<image class="topInfo-avatar" :src="company.companyLogo" mode="aspectFill"></image>
			<text class="topInfo-name">
				{{company.companyName}}
			</text>
			<view class="topInfo-time">
				<!-- 邀请你语音通话... -->
				<smhTimer v-if="isJie" ref="timer" :auto="isJie" />
			</view>
		</view>
		<view class="topInfo" v-if="isRol == 2 && userType == 1">
			<image class="topInfo-avatar" :src="company.companyLogo" mode="aspectFill"></image>
			<text class="topInfo-name">
				{{company.companyName}}
			</text>
			<view class="">
				<text class="topInfo-time" v-if="isRol == 2 && isJie == false">
					邀请你通话...
				</text>
				<smhTimer v-if="isJie" ref="timer" :auto="isJie" />
			</view>

		</view>
		<view class="topInfo" v-if="isRol == 2 && userType == 2">
			<image class="topInfo-avatar" :src="resumesIdInfo.avatar" mode="aspectFill"></image>
			<text class="topInfo-name">
				{{resumesIdInfo.resumesName}}
			</text>
			<view class="">
				<text class="topInfo-time" v-if="isRol == 2 && isJie == false">
					邀请你通话...
				</text>
				<smhTimer v-if="isJie" ref="timer" :auto="isJie" />
			</view>

		</view>
		<!-- 底部未接通按钮 -->
		<view v-if="isJie == false" class="bottomInfoContont">
			<!-- 发起人 -->
			<view v-if="isRol==1" class="bottomInfo" style="justify-content: center;">
				<view class="bottomInfo-item" @click="jieOrGuaCall(4)">
					<image class="bottomInfo-item-img" src="/static/images/voice/cancel.png" mode=""></image>
					<text class="bottomInfo-item-txt">
						挂断
					</text>
				</view>
			</view>
			<!-- 底部操作(语音未接通) 接受人 -->
			<view v-if="isRol==2" class="bottomInfo">
				<view class="bottomInfo-item" @click="jieOrGuaCall(4)">
					<image class="bottomInfo-item-img" src="/static/images/voice/cancel.png" mode=""></image>
					<text class="bottomInfo-item-txt">
						挂断
					</text>
				</view>
				<view class="bottomInfo-item" @click="jieOrGuaCall(2)">
					<image class="bottomInfo-item-img" src="/static/images/voice/answer.png" mode=""></image>
					<text class="bottomInfo-item-txt">
						接听
					</text>
				</view>
			</view>
		</view>
		<!-- 底部接通后 -->
		<view class="bottomInfoContont" v-if="isJie == true">
			<!-- 语音通话 -->
			<view class="bottomInfo flex align-center justify-between" v-if="messageType == 21">
				<view class="bottomInfo-item" @click="setStopLocalAudio()">
					<view class="bottomInfo-item-center">
						<image class="bottomInfo-item-centerI"
							:src="isOpenMicrophone?'/static/images/voice/openMkf.png':'/static/images/voice/closeMkf.png'"
							mode="widthFix">
						</image>
					</view>
					<text class="bottomInfo-item-txt">
						{{isOpenMicrophone?'麦克风已开':'麦克风已关'}}
					</text>
				</view>
				<view class="bottomInfo-item" @click="jieOrGuaCall(4)">
					<image class="bottomInfo-item-img" src="/static/images/voice/cancel.png" mode=""></image>
					<text class="bottomInfo-item-txt">
						挂断
					</text>
				</view>
			</view>
			<!-- 视频 -->
			<view class="bottomInfo flex align-center justify-between flex-wrap" v-if="messageType == 20">
				<view class="bottomInfo-item" @click="setStopLocalAudio()">
					<view class="bottomInfo-item-center">
						<image class="bottomInfo-item-centerI"
							:src="isOpenMicrophone?'/static/images/voice/openMkf.png':'/static/images/voice/closeMkf.png'"
							mode="widthFix">
						</image>
					</view>
					<text class="bottomInfo-item-txt">
						{{isOpenMicrophone?'麦克风已开':'麦克风已关'}}
					</text>
				</view>
				<view class="bottomInfo-item">
					<!-- 前置摄像头开启 -->
					<view class="bottomInfo-item-center" v-if="isFrontCamera" @click="selectVideoCamera()">
						<image class="bottomInfo-item-centerI" style="width: 70rpx;"
							src="/static/images/voice/fanzhuan_font.png" mode="widthFix">
						</image>
					</view>
					<!-- 后置摄像头开启 -->
					<view class="bottomInfo-item-center" @click="selectVideoCamera()"
						style="background-color: rgba(27,27,27, 0.4);" v-else>
						<image class="bottomInfo-item-centerI" style="width: 70rpx;"
							src="/static/images/voice/fanhzuan-back.png" mode="widthFix">
						</image>
					</view>
					<text class="bottomInfo-item-txt">
						翻转摄像头
					</text>
				</view>
				<view class="bottomInfo-item">
					<!-- 摄像头开启 -->
					<view class="bottomInfo-item-center" v-if="isOpenCamera" @click="openOrClosCamera()">
						<image class="bottomInfo-item-centerI" style="width: 70rpx;"
							src="/static/images/voice/openSxt.png" mode="widthFix">
						</image>
					</view>
					<!-- 摄像头已关 -->
					<view class="bottomInfo-item-center" @click="openOrClosCamera()"
						style="background-color: rgba(27,27,27, 0.4);" v-else>
						<image class="bottomInfo-item-centerI" style="width: 70rpx;"
							src="/static/images/voice/closeSxt.png" mode="widthFix">
						</image>
					</view>
					<text class="bottomInfo-item-txt">
						{{isOpenCamera?'摄像头已开':'摄像头已关'}}
					</text>
				</view>
				<view class="bottomInfo-item" style="height: 0;width: 164rpx;">

				</view>
				<view class="bottomInfo-item" @click="jieOrGuaCall(4)" style="margin-top: 40rpx;">
					<image class="bottomInfo-item-img" src="/static/images/voice/cancel.png" mode=""></image>
					<text class="bottomInfo-item-txt">
						挂断
					</text>
					<!-- {{remoteUserId}}-{{isJie}} -->
				</view>
				<view class="bottomInfo-item" style="height: 0;width: 164rpx;">

				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import smhTimer from '@/components/smh-timer/smh-timer.vue'
	import httpRequest from '@/common/httpRequest.js'
	import TrtcCloud from "@/TrtcCloud/lib/index";
	import TrtcRemoteView from '@/TrtcCloud/view/TrtcRemoteView';
	import TrtcLocalView from '@/TrtcCloud/view/TrtcLocalView';
	import {
		TRTCAppScene,
		TRTCRoleType,
		TRTCAudioQuality,
		TRTCVideoStreamType,
		TRTCBeautyStyle,
		TRTCAudioRoute
	} from '@/TrtcCloud/lib/TrtcDefines';
	export default {
		components: {
			smhTimer,
			TrtcLocalView,
			TrtcRemoteView,
		},
		data() {
			return {
				trtcCloud: TrtcCloud.createInstance(), //创建 TRTC 的对象实例。
				sdkAppId: parseInt(uni.getStorageSync('sdkAppId')), //trtcSdkAppId
				byUserId: '', //对方的userId
				userId: uni.getStorageSync('userId').toString(),
				chatContentId: '',
				isRol: 1, //1:发起人 2：接受人
				messageType: '21', //类型 20:视频通话 21:语音通话
				chatConversationId: '',
				screenHeight: '', //屏幕高度
				videoStatusInter: null, //获取通话状态定时器
				videoStatus: 1, //通话状态 1:未接通 2:接通 4:挂断
				isJie: false, //是否接通 true:接通 false:未接通
				isOpenMicrophone: true, //是否打开麦克风
				isOpenCamera: true, //摄像头是否开启
				resumesIdInfo: {
					resumesName: '',
					avatar: '',
				}, //用户简历
				company: {
					companyLogo: '',
					companyName: '',
				}, //企业信息
				userType: 1, //1:用户 2:企业
				postPushId: '', //岗位id，
				resumesId: '', //简历id
				isRemoterAvailable: false, //是否拉取到别人的视频流
				isFrontCamera: true, //默认前置摄像头
				sysInfoHeight: 0, //屏幕总高度
				remoteUserId: '', //对方的userid
				byJoinUserId: '', //trtc监听到的userID
			};
		},
		watch: {
			videoStatus() {
				//通话中
				if (this.videoStatus == 2) {
					this.isJie = true
					//接听后开启麦克风采集
					this.startAudio()
					this.remoteUserId = this.byJoinUserId
					this.trtcCloud.startRemoteView(this.remoteUserId, TRTCVideoStreamType
						.TRTCVideoStreamTypeBig, this.remoteUserId);

				} else if (this.videoStatus == 4) { //如果等于4，那么就是挂断电话
					console.log(this.videoStatus, '走这里了4444444')
					this.exitRoom()
				}
			},
		},
		onLoad(option) {
			const sysInfoHeight = uni.getSystemInfoSync().screenHeight
			this.sysInfoHeight = sysInfoHeight
			//定时获取通话状态
			this.getVideoStatus()
			let systemInfo = uni.getSystemInfoSync();
			//获取手机系统状态栏高度
			this.screenHeight = systemInfo.screenHeight - systemInfo.statusBarHeight;
			if (option.byUserId) {
				this.byUserId = option.byUserId
			}
			if (option.isRol) {
				this.isRol = option.isRol
			}
			if (option.messageType) {
				this.messageType = option.messageType
			}
			if (option.chatConversationId) {
				this.chatConversationId = option.chatConversationId
			}
			if (option.chatContentId) {
				this.chatContentId = option.chatContentId
				//获取getUserSig 开始进房操作
				this.getUserSig()
			}
			if (option.postPushId) {
				this.postPushId = option.postPushId
			}
			console.log(option.resumesId, '这是resumesId')
			if (option.resumesId) {

				this.resumesId = option.resumesId
			}
			// if (option.userType) {
			// 	this.userType = option.userType
			// 	if (this.userType == 1) { //发起人是用户
			// 		if (this.isRol == 1) { //发起人
			// 			//查询企业信息
			// 			console.log('发起人查企业')
			// 			this.selectPostPushDetails()
			// 		} else { //接受人
			// 			//查询用户简历信息
			// 			console.log('接受人')
			// 			this.selectResumesByResumesId()
			// 		}
			// 	} else { //发起人是企业
			// 		if (this.isRol == 1) { //发起人
			// 			//查询用户简历信息
			// 			this.selectResumesByResumesId()
			// 		} else { //接受人
			// 			//查询企业信息
			// 			this.selectPostPushDetails()
			// 		}
			// 	}
			// }
			this.userType = uni.getStorageSync('userType')
			this.selectPostPushDetails()
			this.selectResumesByResumesId()
			console.log(this.userType, '当前的userType')
			this.onEventTric()
		},
		onUnload(e) {
			// 页面卸载的时候销毁一下trtc
			TrtcCloud.destroyInstance();
			//状态也重置一下
			uni.setStorageSync('isDial', false)
		},
		onBackPress(e) {
			if (e.from != 'navigateBack') { //如果不是挂断也走挂断操作
				console.log('返回')
				this.jieOrGuaCall(5)
				return true
			}

		},
		methods: {
			//定时器获取接电话的状态
			getVideoStatus() {
				this.videoStatus = uni.getStorageSync('videoStatus')
				this.videoStatusInter = setInterval(() => {
					this.videoStatus = uni.getStorageSync('videoStatus')
				}, 1000)
			},
			//开启/关闭摄像头
			openOrClosCamera() {
				if (this.isOpenCamera) { //关闭
					this.trtcCloud.stopLocalPreview();
					// this.trtcCloud.muteLocalVideo(TRTCVideoStreamType.TRTCVideoStreamTypeBig, true);
				} else { //开启
					this.trtcCloud.startLocalPreview(true, this.userId);
					// this.trtcCloud.muteLocalVideo(TRTCVideoStreamType.TRTCVideoStreamTypeBig, false);
				}
				this.isOpenCamera = !this.isOpenCamera
			},
			//翻转摄像头
			selectVideoCamera() {
				this.isFrontCamera = !this.isFrontCamera
				this.trtcCloud.switchCamera(this.isFrontCamera);
			},
			//开启/关闭麦克风
			setStopLocalAudio() {
				if (this.isOpenMicrophone) { //r如果麦克风开启则静音
					this.trtcCloud.muteLocalAudio(true); //静音
					this.isOpenMicrophone = false
				} else { //否则开启麦克风
					this.trtcCloud.muteLocalAudio(false);
					this.isOpenMicrophone = true
				}
			},
			//接电话或拒绝
			jieOrGuaCall(type) {
				let data = {
					videoStatus: type,
					chatContentId: this.chatContentId,
				}
				httpRequest.post('/app/chat/updateChatContent', data).then(res => {
					if (res.code == 0) {
						if (type == 4 || type == 5) { //挂断则退房
							this.exitRoom()
						} else if (type == 2) { //接通（接受人）
							this.isJie = true
							this.remoteUserId = this.byJoinUserId
							this.trtcCloud.startRemoteView(this.remoteUserId, TRTCVideoStreamType
								.TRTCVideoStreamTypeBig, this.remoteUserId);
							console.log(typeof this.remoteUserId, '这是对方的userid')
							console.log(this.remoteUserId, '这是对方的userid')
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			//开启视频（我）
			startLocalPreview() {
				//开启摄像头采集
				this.trtcCloud.startLocalPreview(this.isFrontCamera, this.userId);
			},
			//开启麦克风采集（我）
			startAudio() {
				//开启麦克风采集
				this.trtcCloud.startLocalAudio(TRTCAudioQuality.TRTCAudioQualityDefault);
			},
			//退房
			exitRoom() {
				this.trtcCloud.exitRoom();
			},
			//监听trtc sdk事件
			onEventTric() {
				//监听远端用户退出房间
				this.trtcCloud.on("onRemoteUserLeaveRoom", (userId) => {
					console.log('对方退房了')
					//直接退房
					this.exitRoom()
				});
				this.trtcCloud.on("onRemoteUserEnterRoom", (userId) => {
					console.log('对方进房了')
					this.byJoinUserId = userId.toString()
				})
				//远端用户是否存在可播放的画面
				// this.trtcCloud.on("onUserVideoAvailable", (res) => {
				// 	console.log(`远端有可播放的画面` + res);
				// 	const {
				// 		userId,
				// 		available
				// 	} = res;
				// 	if (userId && available) {
				// 		this.byJoinUserId = userId.toString()
				// 	}
				// });
				//自己进房的通知
				this.trtcCloud.on("onEnterRoom", (result) => {
					console.log('1111')
					if (result > 0) {
						console.log(`进房成功，耗时: ${result}ms`);
						if (this.messageType == 20) { //如果是视频通话则开启摄像头
							this.startLocalPreview()
						}
					}
				});
				this.trtcCloud.on('onExitRoom', (reason) => {
					console.log(`退房成功 reason = ${reason}`);
					//正常退出房间后再返回
					uni.navigateBack()
				});
				this.trtcCloud.on('onWarning', (res) => {
					console.log('- onWarning: ', JSON.stringify(res));
				});
				this.trtcCloud.on('onError', (res) => {
					console.log('- onError: ', JSON.stringify(res));
				});
			},
			//进房
			setEnterRoom(userSig) {
				const params = {
					strRoomId: this.chatContentId.toString(),
					sdkAppId: this.sdkAppId,
					userId: uni.getStorageSync('userId').toString(),
					userSig: userSig,
					role: TRTCRoleType.TRTCRoleAnchor, //anchor:“主播”角色，可以推流和拉流。 audience:“观众”角色，只能拉流观看，无法推流。
				}
				this.trtcCloud.enterRoom(params, TRTCAppScene.TRTCAppSceneVideoCall);
			},
			//获取sign
			getUserSig() {
				httpRequest.getT('/app/chat/selectSign').then(res => {
					if (res.code == 0) {
						//进房
						this.setEnterRoom(res.data)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			//获取企业信息
			selectPostPushDetails() {
				let data = {
					postPushId: this.postPushId
				}
				httpRequest.getT('/app/postPush/selectPostPushDetails', data).then(res => {
					if (res.code == 0) {
						this.company = res.data.company
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			//获取用户简历
			selectResumesByResumesId() {
				let data = {
					resumesId: this.resumesId
				}
				httpRequest.getT('/app/resumes/selectResumesByResumesId', data).then(res => {
					if (res.code == 0) {
						this.resumesIdInfo = res.data
					}
				})
			},
		}
	}
</script>

<style lang="scss">
	@import url("./css/videoVoice.css");
</style>