<template>
	<view class="videoContont" :style="{height:screenHeight+'px'}">
		<!-- 发起人 -->
		<block v-if="messageType==20">
			<!-- 我的视频(拨打视频未接通) -->
			<view v-show="isOpenCamera" class="local-video" :class="isJie?'mySmartVideo':''"
				:style="{height:screenHeight+'px'}" id="local-video">
			</view>
			<!-- 对方的视频（拨打视频接通后） -->
			<view class="local-video" :style="{height:screenHeight+'px'}" v-show="isJie == true" id="myLocalVideo">
			</view>
		</block>
		<!-- 顶部信息 -->
		<view class="topInfo" v-if="isRol == 1 && userType == 2">
			<image class="topInfo-avatar" :src="resumesIdInfo.avatar" mode="aspectFill"></image>
			<view class="topInfo-name">
				{{resumesIdInfo.resumesName}}
			</view>
			<view class="topInfo-time">
				<!-- 邀请你语音通话... -->
				<smhTimer v-if="isJie" ref="timer" @timing="timing" :auto="isJie" />
			</view>
		</view>
		<view class="topInfo" v-if="isRol == 1 && userType == 1">
			<image class="topInfo-avatar" :src="company.companyLogo" mode="aspectFill"></image>
			<view class="topInfo-name">
				{{company.companyName}}
			</view>
			<view class="topInfo-time">
				<!-- 邀请你语音通话... -->
				<smhTimer v-if="isJie" ref="timer" @timing="timing" :auto="isJie" />
			</view>
		</view>
		<view class="topInfo" v-if="isRol == 2 && userType == 1">
			<image class="topInfo-avatar" :src="company.companyLogo" mode="aspectFill"></image>
			<view class="topInfo-name">
				{{company.companyName}}
			</view>
			<view class="topInfo-time" v-if="isRol == 2">
				<block v-if="isJie == false">邀请你通话...</block>
				<smhTimer v-if="isJie" ref="timer" @timing="timing" :auto="isJie" />
			</view>
		</view>
		<view class="topInfo" v-if="isRol == 2 && userType == 2">
			<image class="topInfo-avatar" :src="resumesIdInfo.avatar" mode="aspectFill"></image>
			<view class="topInfo-name">
				{{resumesIdInfo.resumesName}}
			</view>
			<view class="topInfo-time" v-if="isRol == 2">
				<block v-if="isJie == false">邀请你通话...</block>
				<smhTimer v-if="isJie" ref="timer" @timing="timing" :auto="isJie" />
			</view>
		</view>
		<!-- 未接通 -->
		<block v-if="isJie == false">
			<!-- 发起人 -->
			<view v-if="isRol==1" class="bottomInfo flex align-center justify-center">
				<view class="bottomInfo-item" @click="jieOrGuaCall(4)">
					<image class="bottomInfo-item-img" src="../../static/images/voice/cancel.png" mode=""></image>
					<view class="bottomInfo-item-txt">
						挂断
					</view>
				</view>
			</view>
			<!-- 底部操作(语音未接通) 接受人 -->
			<view v-if="isRol==2" class="bottomInfo flex align-center justify-between">
				<view class="bottomInfo-item" @click="jieOrGuaCall(4)">
					<image class="bottomInfo-item-img" src="../../static/images/voice/cancel.png" mode=""></image>
					<view class="bottomInfo-item-txt">
						挂断
					</view>
				</view>
				<view class="bottomInfo-item" @click="jieOrGuaCall(2)">
					<image class="bottomInfo-item-img" src="../../static/images/voice/answer.png" mode=""></image>
					<view class="bottomInfo-item-txt">
						接听
					</view>
				</view>
			</view>

		</block>
		<!-- 接通 -->
		<block v-if="isJie">
			<!-- 语音通话 -->
			<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>
					<view class="bottomInfo-item-txt">
						{{isOpenMicrophone?'麦克风已开':'麦克风已关'}}
					</view>
				</view>
				<view class="bottomInfo-item" @click="jieOrGuaCall(4)">
					<image class="bottomInfo-item-img" src="../../static/images/voice/cancel.png" mode=""></image>
					<view class="bottomInfo-item-txt">
						挂断
					</view>
				</view>
			</view>
			<!-- 视频 -->
			<view class="bottomInfo flex align-center justify-center flex-wrap" v-if="messageType == 20">
				<view class="flex align-center justify-between" style="width: 100%;">
					<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>
						<view class="bottomInfo-item-txt">
							{{isOpenMicrophone?'麦克风已开':'麦克风已关'}}
						</view>
					</view>
					<view class="bottomInfo-item">
						<!-- 前置摄像头开启 -->
						<view class="bottomInfo-item-center" v-if="cameraType==1" @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>
						<view class="bottomInfo-item-txt">
							翻转摄像头
						</view>
					</view>
					<view class="bottomInfo-item">
						<!-- 摄像头开启 -->
						<view class="bottomInfo-item-center" v-if="isOpenCamera" @click="closeCamera()">
							<image class="bottomInfo-item-centerI" style="width: 70rpx;"
								src="../../static/images/voice/openSxt.png" mode="widthFix">
							</image>
						</view>
						<!-- 摄像头已关 -->
						<view class="bottomInfo-item-center" @click="openCamera()"
							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>
						<view class="bottomInfo-item-txt">
							{{isOpenCamera?'摄像头已开':'摄像头已关'}}
						</view>
					</view>
				</view>

				<!-- <view class="bottomInfo-item" style="height: 0;width: 164rpx;">

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

				</view> -->
			</view>
		</block>


	</view>
</template>

<script>
	import TRTC from 'trtc-sdk-v5';
	import {
		BasicBeauty
	} from 'trtc-sdk-v5/plugins/video-effect/basic-beauty';
	import smhTimer from '@/components/smh-timer/smh-timer.vue'
	export default {
		components: {
			smhTimer
		},
		data() {
			return {
				sdkAppId: parseInt(uni.getStorageSync('sdkAppId')), //trtcSdkAppId
				byUserId: '', //对方的userId
				chatContentId: '',
				isRol: 1, //1:发起人 2：接受人
				messageType: '21', //类型 20:视频通话 21:语音通话
				chatConversationId: '',
				screenHeight: '', //屏幕高度
				videoStatusInter: null, //获取通话状态定时器
				videoStatus: 1, //通话状态 1:未接通 2:接通 4:挂断
				isJie: false, //是否接通 true:接通 false:未接通
				trtc: null, //trtc单例对象
				isOpenMicrophone: true, //是否打开麦克风
				isOpenCamera: true, //摄像头是否开启
				resumesIdInfo: {
					resumesName: '',
					avatar: '',
				}, //用户简历
				company: {
					companyLogo: '',
					companyName: '',
				}, //企业信息
				userType: 1, //1:用户 2:企业
				postPushId: '', //岗位id，
				resumesId: '', //简历id
				isRemoterAvailable: false, //是否拉取到别人的视频流
				cameraType: 1, //默认使用前置摄像头
			};
		},
		watch: {
			videoStatus() {
				//通话中
				if (this.videoStatus == 2) {
					console.log('开始拉取视频')
					//接通后开启音频
					this.startLocalAudio()
					this.isJie = true

				} else if (this.videoStatus == 4) { //如果等于4，那么就是挂断电话
					console.log(this.videoStatus, '走这里了4444444')
					this.exitRoom()
				}
			},
		},
		onLoad(option) {
			//定时获取通话状态
			this.getVideoStatus()
			let systemInfo = uni.getSystemInfoSync();
			console.log(systemInfo, '系统信息')
			//获取屏幕高度
			//获取手机系统状态栏高度
			this.screenHeight = systemInfo.windowHeight - 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
			}
			if (option.resumesId) {
				this.resumesId = option.resumesId
			}
			// if (option.userType) {
			// 	this.userType = option.userType
			// 	if (this.userType == 1) { //发起人是用户
			// 		if (this.isRol == 1) { //发起人
			// 			//查询企业信息
			// 			this.selectPostPushDetails()
			// 		} else { //接受人
			// 			//查询用户简历信息
			// 			this.selectResumesByResumesId()
			// 		}
			// 	} else { //发起人是企业
			// 		if (this.isRol == 1) { //发起人
			// 			//查询用户简历信息
			// 			this.selectResumesByResumesId()
			// 		} else { //接受人
			// 			//查询企业信息
			// 			this.selectPostPushDetails()
			// 		}
			// 	}
			// }
			this.userType = uni.getStorageSync('userType')
			this.selectPostPushDetails()
			this.selectResumesByResumesId()
			this.onRemoteVideoAvailable()
			this.getRemoteUserExit()
			this.addRefreshListener()
		},
		onUnload(e) {
			console.log(e, '页面卸载')
			clearInterval(this.videoStatusInter)
			this.videoStatusInter = null
			this.unloadRoom()
		},
		onBackPress(e) {
			if (e.from != 'navigateBack') { //如果不是挂断也走挂断操作
				this.jieOrGuaCall(5)
			}
		},
		methods: {
			//翻转摄像头
			async selectVideoCamera() {
				if (this.cameraType == 2) { //切换至前置摄像头
					await this.trtc.updateLocalVideo({
						option: {
							useFrontCamera: true
						}
					});
					this.cameraType = 1
				} else { //切换至后置摄像头
					await this.trtc.updateLocalVideo({
						option: {
							useFrontCamera: false
						}
					});
					this.cameraType = 2
				}
			},
			//计时回掉
			timing(e) {

			},
			//打开摄像头
			async openCamera() {
				// 打开摄像头
				await this.trtc.updateLocalVideo({
					mute: false
				});
				this.isOpenCamera = true
			},
			//关闭摄像头
			async closeCamera() {
				// 关闭摄像头，在关闭摄像头后，摄像头预览画面会变成黑屏，您可以在此时显示业务侧自身的 UI 遮罩。
				await this.trtc.updateLocalVideo({
					mute: true
				});
				this.isOpenCamera = false
			},
			//获取企业信息
			selectPostPushDetails() {
				let data = {
					postPushId: this.postPushId
				}
				this.$Request.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
				}
				this.$Request.getT('/app/resumes/selectResumesByResumesId', data).then(res => {
					if (res.code == 0) {
						this.resumesIdInfo = res.data
					}
				})
			},
			//监听页面是否刷新了
			addRefreshListener() {
				// 监听页面显示的事件，可以用来判断是否刷新了页面
				window.addEventListener('pageshow', (event) => {
					console.log(event, '页面刷新了')
					// alert('页面刷新了')
					this.jieOrGuaCall(5)
					// 页面刷新了直接挂断电话
				});
			},
			//退房并销毁trtc
			async unloadRoom() {
				await this.trtc.exitRoom();
				// 退房成功后，若后续无需使用 trtc 实例，则可以调用 trtc.destroy 方法销毁实例，及时释放相关资源。销毁后的 trtc 实例无法继续使用，需要重新创建新的实例。
				this.trtc.destroy();
			},
			//关闭/开启摄像头
			async setStopLocalAudio() {
				if (this.isOpenMicrophone) { //如果开启则静音
					await this.trtc.updateLocalAudio({
						mute: true
					})
					this.isOpenMicrophone = false
				} else {
					await this.trtc.updateLocalAudio({
						mute: false
					})
					this.isOpenMicrophone = true
				}
			},
			//退房
			async exitRoom() {
				let pages = getCurrentPages();
				let hasPrevPage = pages.length > 1;
				if (hasPrevPage) {
					// 有上一页
					//直接返回
					uni.navigateBack()
					uni.setStorageSync('isDial', false)
				} else {
					// 没有上一页
					//返回首页
					uni.switchTab({
						url: '/pages/index/index'
					})
					uni.setStorageSync('isDial', false)
				}
			},
			//接电话或拒绝
			jieOrGuaCall(type) {
				let data = {
					videoStatus: type,
					chatContentId: this.chatContentId,
				}
				this.$Request.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
							if (this.messageType == 20) { //视频通话时开启摄像头
								setTimeout(() => {
									this.openCameraAndAudio()
								}, 500)
							}
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			//获取sign
			getUserSig() {
				this.$Request.getT('/app/chat/selectSign').then(res => {
					if (res.code == 0) {
						//进房
						this.setEnterRoom(res.data)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			},
			//h5进房
			async setEnterRoom(userSig) {
				try {
					let data = {
						strRoomId: this.chatContentId.toString(),
						scene: 'rtc', //rtc实时通话模式 live在线直播模式
						sdkAppId: this.sdkAppId,
						userId: uni.getStorageSync('userId') + '',
						userSig: userSig,
						role: 'anchor', //anchor:“主播”角色，可以推流和拉流。 audience:“观众”角色，只能拉流观看，无法推流。
						autoReceiveAudio: true, //自动接收音频
					}
					await this.trtc.enterRoom(data);
					if (this.messageType == 20) { //视频通话时开启摄像头
						// if (this.isRol == 1) { //是发起人则直接打开摄像头
						// 	this.openCameraAndAudio()
						// }
						this.openCameraAndAudio()

					}


					console.log('进房成功');
				} catch (error) {
					console.error('进房失败 ' + error);
				}
			},
			async openCameraAndAudio() {
				//开启摄像头
				const view = 'local-video';
				await this.trtc.startLocalVideo({
					view
				});
				// 设置基础美颜效果
				await this.trtc.startPlugin('BasicBeauty', {
					beauty: 0.5, // 美颜
					brightness: 0.5, // 明亮
					ruddy: 0.5, // 红润
				});
				//摄像头状态设置为开启
				this.isOpenCamera = true
			},
			//对方退房（挂断）
			getRemoteUserExit() {
				//监听对方是否退房
				this.trtc.on(TRTC.EVENT.REMOTE_USER_EXIT, event => {
					// 如果对方退房了则是对方挂断了了,自己也走退房
					this.exitRoom()
				});
			},
			//创建trtc单例并监听视频流
			onRemoteVideoAvailable() {
				//创建trtc实例
				this.trtc = TRTC.create({
					plugins: [BasicBeauty]
				});
				this.trtc.on(TRTC.EVENT.REMOTE_VIDEO_AVAILABLE, ({
					userId,
					streamType
				}) => {
					this.isRemoterAvailable = true
					// 为了播放视频画面，您需在 DOM 中放置一个 HTMLElement，可以是一个 div 标签，假设其 id 为 `${userId}_${streamType}`
					const view = 'myLocalVideo';
					this.trtc.startRemoteVideo({
						userId,
						streamType,
						view
					});
					console.log('已拉取到别人的视频流')
					//已拉取到别人的视频流

				});
			},
			//开启麦克风
			async startLocalAudio() {
				//开启麦克风
				await this.trtc.startLocalAudio();
				this.isOpenMicrophone = true
			},
			//定时器获取接电话的状态
			getVideoStatus() {
				this.videoStatus = uni.getStorageSync('videoStatus')
				this.videoStatusInter = setInterval(() => {
					this.videoStatus = uni.getStorageSync('videoStatus')
				}, 1000)
			},
		}
	}
</script>

<style lang="scss">
	.videoContont {
		background-image: radial-gradient(circle at center, #00DD9A 10%, #0D0D0D 100%);
		position: relative;
	}

	.mySmartVideo {
		width: 200rpx !important;
		height: 300rpx !important;
		border-radius: 24rpx !important;
		position: fixed !important;
		top: 100rpx !important;
		right: 30rpx !important;
		z-index: 9999 !important;
	}

	.local-video {
		width: 100%;
	}

	.topInfo {
		width: 100%;
		height: auto;
		position: absolute;
		top: 230rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.topInfo-avatar {
			width: 170rpx;
			height: 170rpx;
			border-radius: 24rpx;
		}

		.topInfo-name {
			color: #FFFFFF;
			font-size: 44rpx;
			font-weight: 500;
			margin-top: 20rpx;
		}

		.topInfo-time {
			color: #FFFFFF;
			font-size: 28rpx;
			font-weight: 500;
		}
	}

	.bottomInfo {
		width: 100%;
		height: auto;
		position: absolute;
		bottom: 180rpx;
		left: 0;
		padding: 0 50rpx;

		.bottomInfo-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
		}

		.bottomInfo-item-center {
			width: 164rpx;
			height: 164rpx;
			border-radius: 50%;
			background-color: #FFFFFF;
			display: flex;
			align-items: center;
			justify-content: center;

			.bottomInfo-item-centerI {
				width: 64rpx;
				height: 64rpx;
			}
		}


		.bottomInfo-item-img {
			width: 164rpx;
			height: 164rpx;
			border-radius: 50%;
		}

		.bottomInfo-item-txt {
			color: #FFFFFF;
			font-size: 28rpx;
			font-weight: 500;
			margin-top: 12rpx;
		}
	}
</style>