<template>
	<div class="video-call-container">
		<div class="video-container">
			<!-- 本地视频 -->
			<div class="video-box local-video" v-if="localStream">
				<div id="local-video-box"></div>
				<div class="user-info">我</div>
			</div>

			<!-- 远程视频 -->
			<div class="video-box remote-video" v-for="(stream, uid) in remoteStreams" :key="uid">
				<div id="remote-video-box"></div>
				<div class="user-info">医生({{uid}})</div>
			</div>

			<!-- 无视频流提示 -->
			<div class="no-stream-tip" v-if="!(localStream || Object.keys(remoteStreams).length > 0)">
				等待连接...
			</div>
		</div>
		<!-- <div v-if="!getCameraFailText" style="position: fixed; z-index: 100; top: 50%; height: 50px; display: flex; flex-direction: column; align-items: center; justify-content: center;">
			<div>摄像头信息：</div>
			<div class="cell" v-for="(item,index) in cameraList" :key="index">{{ item.label +':'+ item.deviceId }}</div>
		</div>
		<div v-else style="position: fixed; z-index: 100; top: 50%; height: 50px; display: flex; flex-direction: column; align-items: center; justify-content: center;">
			<div>摄像头获取失败信息：{{getCameraFailText}}</div>
		</div> -->
		<!-- 控制栏 -->
		<div class="control-bar">
			<button class="control-btn" :class="{ active: !muteMicrophone }" @click="openCloseMicrophone">
				<i class="iconfont" :class="{'icon-microphone-off': muteMicrophone, 'icon-microphone-on': !muteMicrophone }"></i>
			</button>
			<button class="control-btn" :class="{ active: !muteCamera }" @click="openCloseCamera">
				<i class="iconfont" :class="{ 'icon-camera-off': !muteCamera, 'icon-camera-on': muteCamera }"></i>
			</button>
			<button class="control-btn active" @click="switchCamera">
				<i class="iconfont icon-switch1"></i>
			</button>
			<button class="control-btn message-btn" :class="{ active: showIMPanel }" @click="toggleIM">
				<i class="iconfont">💬</i>
			</button>
			<button class="control-btn hangup-btn" @click="exitCall">
				<i class="iconfont icon-dianhua"></i>
			</button>
		</div>

		<!-- 图文消息面板 -->
		<chat-panel
			ref="chatPanel"
			:show="showIMPanel"
			:config="chatConfig"
			@close="showIMPanel = false"
		/>
	</div>
</template>

<script>
	import {
		initTIM,
		initTRTC,
		exitRoom,
		logoutTIM,
		openCloseMicrophone, // 开关麦可风
		openCloseCamera, // 开关摄像头
		openCloseSpeaker, // 开关扬声器
		getCamera // 获取摄像头列表
	} from './tim-h5-adapter';
	import ChatPanel from '@/components/chat-panel/chat-panel.vue';

	export default {
		components: {
			ChatPanel
		},
		props: {
			config: {
				type: Object,
				default: () => ({
					sdkAppID: '',
					userID: '',
					userSig: '',
					template: '',
					debugMode: false,
				
					// 是否开启调试模式
					enableIM: false,
				
					// 是否开启 IM
					patID: '',
				
					frUserID: '',
					toUserID: '',
					doctorName: '',
					patName: '',
					isTextChat: ''
				})
			}
		},
		watch: {
			config: {
				handler(newValue) {
					console.log('config newValue', newValue)
				},
				deep: true
			}
		},
		data() {
			return {
				userId: '', // 用户 ID
				userSig: '', // 用户签名
				roomID: '', // 房间 ID
				sdkAppID: 0, // SDKAppID
				localStream: null, // 本地流
				remoteStreams: {}, // 远程流
				muteMicrophone: false, // 是否静音麦克风
				muteCamera: false, // 是否关闭摄像头
				useSpeaker: true, // 是否使用扬声器
				useCamera: 0, // 使用摄像头 0:前置摄像头 1:后置摄像头
				cameraList: [], // 摄像头列表
				getCameraFailText: '',
				showIMPanel: false // IM 消息面板显示/隐藏
			};
		},
		computed: {
			chatConfig() {
				return {
					admID: this.config.admID || '',
					frUserID: this.config.frUserID || '',
					toUserID: this.config.toUserID || '',
					doctorName: this.config.doctorName || '',
					patName: this.config.patName || '',
					patID: this.config.patID || ''
				};
			}
		},

		onLoad(options) {
			console.log('room 组件onload', this.config)
			// 从选项中获取参数
			this.userId = this.config.userID;
			this.roomID = this.config.roomID;
			this.sdkAppID = this.config.sdkAppID || 0; // 实际应用中需要替换为真实的 SDKAppID
			this.userSig = this.config.userSig || ''; // 实际应用中需要从服务端获取
			
			if(!this.userId) {
				uni.showToast({
					icon: "error",
					title: '用户ID不存在，请重试！'
				})
				return
			}
			if(!this.roomID) { 
				uni.showToast({
					icon: "error",
					title: '房间号不存在，请重试！'
				})
				return
			}

			// 初始化 TIM 和 TRTC
			// this.initCall();
		},

		onUnload() {
			// 退出通话并清理资源
			this.exitCall();
		},

		methods: {
			/**
			 * 初始化通话
			 */
			async initCall(config) {
				const _this = this
				console.log('config === ', config)
				try {
					// 初始化 TIM
					await initTIM({
						sdkAppID: config.sdkAppID,
						userID: config.userID,
						userSig: config.userSig,
						debugMode: true,
					});

					// 监听远程流添加事件
					window.addEventListener('remote-stream-added', this.handleRemoteStreamAdded);
					// 监听远程流移除事件
					window.addEventListener('remote-stream-removed', this.handleRemoteStreamRemoved);
					// 监听 TIM SDK 就绪事件
					window.addEventListener('tim-sdk-ready', this.handleSDKReady);
					// 监听 IM 新消息事件 → 自动打开面板并刷新
					window.addEventListener('tim-message-received', this.onIMNewMessage);
					
					// 初始化 TRTC 并加入房间
					await initTRTC({
						sdkAppID: config.sdkAppID,
						roomId: config.roomID,
						userId: config.userID,
						userSig: config.userSig,
					}).then(res => {
						console.log('trtcClient===', res.trtcClient)
						_this.getCamera() // 获取摄像头列表
						_this.localStream = res.localStream
					});
					
					// 设置本地流
					// this.localStream = true;
					setTimeout(() => {
						_this.bindLocalStream(); // 延迟一下再绑定本地流，确保元素已经渲染
					}, 500)
				} catch (error) {
					console.error('初始化通话失败:', error);
					uni.showToast({
						title: '初始化通话失败',
						icon: 'none',
					});
				}
			},

			/**
			 * 处理 SDK 就绪事件
			 */
			handleSDKReady() {
				console.log('TIM SDK 已就绪');
			},

			/**
			 * 处理远程流添加事件
			 */
			handleRemoteStreamAdded(event) {
				const {
					userId,
					stream
				} = event.detail;
				console.log('远程流添加:', event, userId);

				// 更新远程流列表
				this.remoteStreams[userId] = stream;

				// 延迟一下再绑定远程流，确保元素已经渲染
				setTimeout(() => {
					this.bindRemoteStream(userId, stream);
				}, 500);
			},

			/**
			 * 处理远程流移除事件
			 */
			handleRemoteStreamRemoved(event) {
				const {
					userId
				} = event.detail;
				console.log('远程流移除:', userId);

				// 从列表中移除远程流
				if (this.remoteStreams[userId]) {
					delete this.remoteStreams[userId];
				}
			},

			/**
			 * 绑定本地流到 video 元素
			 */
			async bindLocalStream() {
				const videoElement = document.getElementById(`local-video-box`);
				console.log('bindLocalStream videoElement：', videoElement)
				if (videoElement) {
					// 在实际的 TRTC SDK 中，会有方法将流绑定到 video 元素 
					// 这里只是示例，具体实现需要根据实际的 SDK 方法调整
					console.log('绑定本地流到DOM', this.localStream);
					// 例如: stream.play(`local-video-${this.userId}`);
					try {
					  // await localStream.initialize();
					  console.log('初始化本地流成功');
					  this.localStream.play('local-video-box');
					  this.localStream.on('error', error => {
						console.log(error)
					    const errorCode = error.getCode();
					    if (errorCode === 0x4043) {
					      // PLAY_NOT_ALLOWED,引导用户手势操作并调用 stream.resume 恢复音视频播放
					      // stream.resume()
					    }
					  })
					} catch (error) {
					  console.error('初始化本地流失败 ' + error);
					}
				}
			},

			/**
			 * 绑定远程流到 video 元素
			 */
			bindRemoteStream(userId, stream) {
				const videoElement = document.getElementById(`remote-video-box`);
				if (videoElement && stream) {
					// 在实际的 TRTC SDK 中，会有方法将流绑定到 video 元素
					// 这里只是示例，具体实现需要根据实际的 SDK 方法调整
					console.log('绑定远程流到元素:', userId);
					// 例如: 
					stream.play(`remote-video-box`);
					stream.on('error', error => {
						console.log(error)
						const errorCode = error.getCode();
						if (errorCode === 0x4043) {
							// PLAY_NOT_ALLOWED,引导用户手势操作并调用 stream.resume 恢复音视频播放
							// stream.resume()
						}
					})
				}
			},
			

			/**
			 * 开关麦克风
			 */
			async openCloseMicrophone() {
				try {
					this.muteMicrophone = !this.muteMicrophone;
					await openCloseMicrophone(!this.muteMicrophone);
				} catch (error) {
					console.error('切换麦克风失败:', error);
					this.muteMicrophone = !this.muteMicrophone;
				}
			},

			/**
			 * 开关摄像头
			 */
			async openCloseCamera() {
				try {
					this.muteCamera = !this.muteCamera;
					await openCloseCamera(!this.muteCamera);
				} catch (error) {
					console.error('开关摄像头失败:', error);
					this.muteCamera = !this.muteCamera;
				}
			},
			
			/**
			 * 切换摄像头
			 */
			async switchCamera() {
				try {
					if(this.cameraList.length > 1) {
						this.useCamera = this.useCamera ? 0 : 1;
						let cameraId = this.cameraList[this.useCamera].deviceId;
						this.localStream.switchDevice('video', cameraId).then(() => {
						  console.log('切换摄像头成功');
						});
					}
					
				} catch (error) {
					console.error('切换摄像头失败:', error);
				}
			},
			
			
			// 获取摄像头
			async getCamera() {
				try {
					await getCamera().then(devices => {
						console.log(devices)
						this.setData({
							cameraList: devices
						})
					}).catch(error => {
						this.getCameraFailText = JSON.stringify(error)
					})
				} catch (error) {
					console.error('切换摄像头失败:', error);
				}
			},

			/**
			 * 切换扬声器
			 */
			async openCloseSpeaker() {
				try {
					this.useSpeaker = !this.useSpeaker;
					await openCloseSpeaker(this.useSpeaker);
				} catch (error) {
					console.error('切换扬声器失败:', error);
					this.useSpeaker = !this.useSpeaker;
				}
			},

			/**
			 * 退出通话
			 */
			async exitCall() {
				try {
					// 移除事件监听
					window.removeEventListener('remote-stream-added', this.handleRemoteStreamAdded);
					window.removeEventListener('remote-stream-removed', this.handleRemoteStreamRemoved);
					window.removeEventListener('tim-sdk-ready', this.handleSDKReady);
					window.removeEventListener('tim-message-received', this.onIMNewMessage);

					// 关闭 IM 面板
					this.showIMPanel = false;

					// 退出房间
					await exitRoom();

					// 登出 TIM
					await logoutTIM();

					// 重置状态
					this.localStream = null;
					this.remoteStreams = {};

					// 返回上一页
					uni.navigateBack();
				} catch (error) {
					console.error('退出通话失败:', error);
				}
			},

			/**
			 * 切换 IM 消息面板
			 */
			toggleIM() {
				this.showIMPanel = !this.showIMPanel;
				// 打开面板时主动触发加载历史消息
				if (this.showIMPanel) {
					this.$nextTick(() => {
						if (this.$refs.chatPanel) {
							this.$refs.chatPanel.getChatData('bottom');
						}
					});
				}
			},

			/**
			 * 接收到新 IM 消息 → 打开面板并刷新
			 */
			onIMNewMessage(event) {
				console.log('[H5-TRTC] 收到新 IM 消息', event);
				// 自动打开面板
				this.showIMPanel = true;
				// 通知 chat-panel 刷新消息列表
				this.$nextTick(() => {
					if (this.$refs.chatPanel) {
						this.$refs.chatPanel.getChatData('bottom');
					}
				});
			},
		},
	};
</script>

<style scoped>
	.bg-red {
		background-color: #ff3300;
	}
	.video-call-container {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #000;
	}

	.video-container {
		flex: 1;
		position: relative;
		overflow: hidden;
	}

	.video-box {
		position: absolute;
		border-radius: 8px;
		overflow: hidden;
		background-color: #111;
	}

	.local-video {
		width: 100%;
		height: calc(50% - 40px);
		top: calc(50% - 40px);
		right: 0;
		z-index: 10;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
	}

	.remote-video {
		width: 100%;
		height: calc(50% - 40px);
		top: 0;
		left: 0;
		z-index: 10;
	}

	.video-element {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.user-info {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 8px 12px;
		background-color: rgba(0, 0, 0, 0.5);
		color: #fff;
		font-size: 14px;
	}

	.no-stream-tip {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		color: #666;
		font-size: 16px;
	}

	.control-bar {
		height: 80px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #111;
		padding: 0 20px;
	}

	.control-btn {
		width: 56px;
		height: 56px;
		border-radius: 50%;
		color: #fff;
		background-color: #f75c45;
		display: flex;
		justify-content: center;
		align-items: center;
		/* margin: 0 20px; */
		border: none;
		outline: none;
		cursor: pointer;
		font-size: 24px;
	}

	.control-btn.active {
		background-color: #fff;
		color: #0369fe;
	}

	.hangup-btn {
		background-color: #f75c45;
		transform: rotate(135deg);
	}

	/* 消息按钮：默认白底，激活蓝底 */
	.message-btn {
		background-color: #fff;
		color: #0369fe;
	}

	.message-btn.active {
		background-color: #0369fe;
		color: #fff;
	}

	/* 图标字体样式 */
	.iconfont {
		font-size: 28px;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
	}
</style>