<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 class="control-bar">
            <button class="control-btn" :class="{ active: !muteMicrophone }" @click="onClickMicrophone">
                <i class="iconfont" :class="{ 'icon-microphone-off': muteMicrophone, 'icon-microphone-on': !muteMicrophone }"></i>
            </button>
            <button class="control-btn" :class="{ active: !muteCamera }" @click="onClickCamera">
                <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 hangup-btn" @click="exitCall">
                <i class="iconfont icon-dianhua"></i>
            </button>
        </div>
    </div>
</template>

<script>
import {
    initTIM,
    initTRTC,
    exitRoom,
    openCloseMicrophone,
    openCloseCamera,
    openCloseSpeaker,
    getCamera
} from './tim-h5-adapter';

export default {
    props: {
        config: {
            type: Object,
            default: () => ({
                sdkAppID: '',
                userID: '',
                userSig: '',
                template: '',
                debugMode: false,
                enableIM: false,
                patID: '',
                frUserID: '',
                toUserID: '',
                doctorName: '',
                patName: '',
                isTextChat: ''
            })
        }
    },
    data() {
        return {
            userId: '',
            userSig: '',
            roomID: '',
            sdkAppID: 0,
            localStream: null,
            remoteStreams: {},
            muteMicrophone: false,
            muteCamera: false,
            useSpeaker: true,
            useCamera: 0,
            cameraList: [],
            getCameraFailText: ''
        };
    },

    onUnload() {
        this.exitCall();
    },

    methods: {
        /**
         * 初始化通话
         */
        async initCall(config) {
            const _this = this;
            console.log('[h5-trtc-room] initCall 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);
                window.addEventListener('tim-sdk-ready', this.handleSDKReady);

                // 初始化 TRTC 并加入房间
                await initTRTC({
                    sdkAppID: config.sdkAppID,
                    roomId: config.roomID,
                    userId: config.userID,
                    userSig: config.userSig
                }).then((res) => {
                    console.log('[h5-trtc-room] trtcClient===', res.trtcClient);
                    _this.getCamera();
                    _this.localStream = res.localStream;
                });

                setTimeout(() => {
                    _this.bindLocalStream();
                }, 500);
            } catch (error) {
                console.error('[h5-trtc-room] 初始化通话失败:', error);
                uni.showToast({
                    title: '初始化通话失败',
                    icon: 'none'
                });
            }
        },

        handleSDKReady() {
            console.log('[h5-trtc-room] TIM SDK 已就绪');
        },

        handleRemoteStreamAdded(event) {
            const { userId, stream } = event.detail;
            console.log('[h5-trtc-room] 远程流添加:', event, userId);
            this.remoteStreams[userId] = stream;
            setTimeout(() => {
                this.bindRemoteStream(userId, stream);
            }, 500);
        },

        handleRemoteStreamRemoved(event) {
            const { userId } = event.detail;
            console.log('[h5-trtc-room] 远程流移除:', userId);
            if (this.remoteStreams[userId]) {
                delete this.remoteStreams[userId];
            }
        },

        async bindLocalStream() {
            const videoElement = document.getElementById(`local-video-box`);
            console.log('[h5-trtc-room] bindLocalStream videoElement：', videoElement);
            if (videoElement) {
                try {
                    console.log('[h5-trtc-room] 绑定本地流到DOM', this.localStream);
                    this.localStream.play('local-video-box');
                    this.localStream.on('error', (error) => {
                        console.log(error);
                        const errorCode = error.getCode();
                        if (errorCode === 0x4043) {
                            // PLAY_NOT_ALLOWED
                        }
                    });
                } catch (error) {
                    console.error('[h5-trtc-room] 初始化本地流失败 ' + error);
                }
            }
        },

        bindRemoteStream(userId, stream) {
            const videoElement = document.getElementById(`remote-video-box`);
            if (videoElement && stream) {
                console.log('[h5-trtc-room] 绑定远程流到元素:', userId);
                stream.play(`remote-video-box`);
                stream.on('error', (error) => {
                    console.log(error);
                    const errorCode = error.getCode();
                    if (errorCode === 0x4043) {
                        // PLAY_NOT_ALLOWED
                    }
                });
            }
        },

        async onClickMicrophone() {
            try {
                this.muteMicrophone = !this.muteMicrophone;
                await openCloseMicrophone(!this.muteMicrophone);
            } catch (error) {
                console.error('[h5-trtc-room] 切换麦克风失败:', error);
                this.muteMicrophone = !this.muteMicrophone;
            }
        },

        async onClickCamera() {
            try {
                this.muteCamera = !this.muteCamera;
                await openCloseCamera(!this.muteCamera);
            } catch (error) {
                console.error('[h5-trtc-room] 开关摄像头失败:', 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('[h5-trtc-room] 切换摄像头成功');
                    });
                }
            } catch (error) {
                console.error('[h5-trtc-room] 切换摄像头失败:', error);
            }
        },

        async getCamera() {
            try {
                await getCamera()
                    .then((devices) => {
                        this.cameraList = devices;
                    })
                    .catch((error) => {
                        this.getCameraFailText = JSON.stringify(error);
                    });
            } catch (error) {
                console.error('[h5-trtc-room] 获取摄像头失败:', error);
            }
        },

        async onClickSpeaker() {
            try {
                this.useSpeaker = !this.useSpeaker;
                await openCloseSpeaker(this.useSpeaker);
            } catch (error) {
                console.error('[h5-trtc-room] 切换扬声器失败:', error);
                this.useSpeaker = !this.useSpeaker;
            }
        },

        /**
         * 退出通话
         * 医生端不调用 logoutTIM，保持全局 TIM 实例可用于后续图文消息
         */
        async exitCall() {
            try {
                window.removeEventListener('remote-stream-added', this.handleRemoteStreamAdded);
                window.removeEventListener('remote-stream-removed', this.handleRemoteStreamRemoved);
                window.removeEventListener('tim-sdk-ready', this.handleSDKReady);

                await exitRoom();

                this.localStream = null;
                this.remoteStreams = {};

                this.$emit('exit');
            } catch (error) {
                console.error('[h5-trtc-room] 退出通话失败:', error);
            }
        }
    }
};
</script>

<style scoped>
/* 视频问诊控制栏图标：复用患者端 iconfont 字体（项目号 4933813） */
@font-face {
    font-family: 'iconfont-trtc';
    src: url('//at.alicdn.com/t/c/font_4933813_bim8rjrgnrl.eot?t=1755238092603');
    src: url('//at.alicdn.com/t/c/font_4933813_bim8rjrgnrl.eot?t=1755238092603#iefix') format('embedded-opentype'),
        url('//at.alicdn.com/t/c/font_4933813_bim8rjrgnrl.woff2?t=1755238092603') format('woff2'),
        url('//at.alicdn.com/t/c/font_4933813_bim8rjrgnrl.woff?t=1755238092603') format('woff'),
        url('//at.alicdn.com/t/c/font_4933813_bim8rjrgnrl.ttf?t=1755238092603') format('truetype'),
        url('//at.alicdn.com/t/c/font_4933813_bim8rjrgnrl.svg?t=1755238092603#iconfont') format('svg');
}

.video-call-container .iconfont {
    font-family: 'iconfont-trtc' !important;
    font-size: 28px;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.video-call-container .icon-microphone-on::before { content: '\e96b'; }
.video-call-container .icon-microphone-off::before { content: '\e654'; }
.video-call-container .icon-camera-on::before { content: '\eca6'; }
.video-call-container .icon-camera-off::before { content: '\eca5'; }
.video-call-container .icon-switch1::before { content: '\e70e'; }
.video-call-container .icon-dianhua::before { content: '\e63b'; }

.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;
}

#local-video-box,
#remote-video-box {
    width: 100%;
    height: 100%;
}

.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: #fff;
    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 12px;
    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);
}

.iconfont {
    font-size: 28px;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}
</style>
