<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.checkMicPermissionThenStartAudio();
					this.isJie = true
				} else if (this.videoStatus == 4) { //挂断电话
					console.log(this.videoStatus, '走这里了4444444')
					this.exitRoom()
				}
			},
		},
		onLoad(option) {
			//定时获取通话状态
			this.getVideoStatus()
			let systemInfo = uni.getSystemInfoSync();
			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
				// 新增：获取签名前先校验基础权限（防止无权限进房）
				this.checkBasePermissionThenGetSig();
			}
			if (option.postPushId) this.postPushId = option.postPushId
			if (option.resumesId) this.resumesId = option.resumesId
			
			this.userType = uni.getStorageSync('userType')
			this.selectPostPushDetails()
			this.selectResumesByResumesId()
			this.onRemoteVideoAvailable()
			this.getRemoteUserExit()
			this.addRefreshListener()
		},
		onUnload(e) {
			clearInterval(this.videoStatusInter)
			this.videoStatusInter = null
			this.unloadRoom()
		},
		onBackPress(e) {
			if (e.from != 'navigateBack') {
				this.jieOrGuaCall(5)
			}
		},
		methods: {
			// 新增：校验音视频基础权限后再获取签名（核心）
			async checkBasePermissionThenGetSig() {
				// 1. 校验麦克风权限（所有通话必选）
				const hasMic = await this.$queue.checkPermission(
					'microphone',
					'音视频通话需要麦克风权限，用于正常语音沟通'
				);
				if (!hasMic) {
					uni.showToast({ title: '麦克风权限不足，无法进行通话', icon: 'none' });
					this.exitRoom();
					return;
				}

				// 2. 视频通话额外校验相机权限
				if (this.messageType === 20) {
					const hasCamera = await this.$queue.checkPermission(
						'camera',
						'视频通话需要相机权限，用于正常视频展示'
					);
					if (!hasCamera) {
						uni.showToast({ title: '相机权限不足，无法进行视频通话', icon: 'none' });
						this.exitRoom();
						return;
					}
				}

				// 权限通过，才获取签名并进房
				this.getUserSig();
			},

			// 新增：校验麦克风权限后再开启音频
			async checkMicPermissionThenStartAudio() {
				const hasMic = await this.$queue.checkPermission('microphone', '通话需要麦克风权限');
				if (hasMic) {
					this.startLocalAudio();
				} else {
					this.isOpenMicrophone = false;
					uni.showToast({ title: '麦克风权限不足，无法正常通话', icon: 'none' });
				}
			},

			// 翻转摄像头
			async selectVideoCamera() {
				// 切换摄像头前再次校验相机权限
				if (this.messageType === 20) {
					const hasCamera = await this.$queue.checkPermission('camera', '切换摄像头需要相机权限');
					if (!hasCamera) {
						uni.showToast({ title: '相机权限不足，无法切换摄像头', icon: 'none' });
						return;
					}
				}

				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
				}
			},

			// 打开摄像头（加权限校验）
			async openCamera() {
				const hasCamera = await this.$queue.checkPermission('camera', '打开摄像头需要相机权限');
				if (!hasCamera) {
					uni.showToast({ title: '相机权限不足，无法打开摄像头', icon: 'none' });
					return;
				}

				await this.trtc.updateLocalVideo({ mute: false });
				this.isOpenCamera = true
			},

			// 关闭摄像头
			async closeCamera() {
				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) => {
					this.jieOrGuaCall(5)
				});
			},

			// 退房并销毁trtc
			async unloadRoom() {
				if (this.trtc) {
					await this.trtc.exitRoom();
					this.trtc.destroy();
					this.trtc = null;
				}
			},

			// 关闭/开启麦克风（加权限校验）
			async setStopLocalAudio() {
				const hasMic = await this.$queue.checkPermission('microphone', '操作麦克风需要权限');
				if (!hasMic) {
					uni.showToast({ title: '麦克风权限不足，无法操作', icon: 'none' });
					return;
				}

				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;
				uni.setStorageSync('isDial', false)
				if (hasPrevPage) {
					uni.navigateBack()
				} else {
					uni.switchTab({ url: '/pages/index/index' })
				}
			},

			// 接/挂电话（加权限校验）
			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) {
								// 接通视频前再次校验相机权限
								this.$queue.checkPermission('camera', '视频通话需要相机权限').then(hasCamera => {
									if (hasCamera) {
										setTimeout(() => { this.openCameraAndAudio() }, 500)
									} else {
										this.jieOrGuaCall(4); // 权限不足自动挂断
									}
								});
							}
						}
					} 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' })
				})
			},

			// 进房（权限已提前校验）
			async setEnterRoom(userSig) {
				try {
					let data = {
						strRoomId: this.chatContentId.toString(),
						scene: 'rtc',
						sdkAppId: this.sdkAppId,
						userId: uni.getStorageSync('userId') + '',
						userSig: userSig,
						role: 'anchor',
						autoReceiveAudio: true,
					}
					await this.trtc.enterRoom(data);
					
					// 视频通话开启摄像头（权限已校验）
					if (this.messageType == 20) {
						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() {
				if (!this.trtc) return;
				this.trtc.on(TRTC.EVENT.REMOTE_USER_EXIT, event => {
					this.exitRoom()
				});
			},

			// 创建trtc实例
			onRemoteVideoAvailable() {
				if (!this.trtc) {
					this.trtc = TRTC.create({ plugins: [BasicBeauty] });
					this.trtc.on(TRTC.EVENT.REMOTE_VIDEO_AVAILABLE, ({ userId, streamType }) => {
						this.isRemoterAvailable = true
						const view = 'myLocalVideo';
						this.trtc.startRemoteVideo({ userId, streamType, view });
					});
				}
			},

			// 开启麦克风（权限已提前校验）
			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>