<template>
    <view>
        <nav-bar
			id="navBar"
			ref="navBar"
            :navbar-data="navbarData"
            @handleSend="handleSend($event, { tagId: 'navBar' })"
            @handleMessageReceived="handleMessageReceived($event, { tagId: 'navBar' })"
        ></nav-bar>
        <view class="page-room">
            <trtc-room id="trtcComponent" ref="trtcComponent" :config="rtcConfig" @handleLoginShow="handleLoginShow($event, { tagId: 'trtcComponent' })"></trtc-room>
			<view class="tip-toast" v-if="showTipToast">
                <view>当前房间为1v1双人通话房间</view>
                <view>不希望其他人打扰</view>
            </view>
        </view>
    </view>
</template>

<script>
// #ifdef MP-WEIXIN
import TrtcRoom from '@/components/wx-trtc-room/trtc-room';
// #endif
// #ifdef H5
import TrtcRoom from '@/components/h5-trtc-room/trtc-room';
// #endif
import navBar from '@/components/navbar/index';
import GenerateTestUserSig from '@/debug/GenerateTestUserSig';
import $http from '@/utils/https';
import httpConfig from '@/utils/httpConfig';
const app = getApp();
export default {
    components: {
        'trtc-room': TrtcRoom,
        navBar
    },
    data() {
        return {
            imgHost: httpConfig && httpConfig.imgHost ? httpConfig.imgHost : '',
            rtcConfig: {
                sdkAppID: '',
                // 必要参数 开通实时音视频服务创建应用后分配的 sdkAppID
                patID: '',
                userID: '', // 必要参数 用户 ID 可以由您的帐号系统指定
                userSig: '', // 必要参数 身份签名，相当于登录密码的作用
                template: '', // 必要参数 组件模版，支持的值 1v1 grid custom ，注意：不支持动态修改, iOS 不支持 pusher 动态渲染
                frUserID: '',
                toUserID: '',
                isTextChat: '',
                admID: '',
                doctorName: '',
                patName: ''
            },
            showTipToast: false,
            height: app.globalData.height * 2 + 20,
            navbarData: {
                isGoHome: true,
                isGoBack: true,
                title: 'none',
                isMonitorNewMessage: 'im',
                isMonitorCalls: 'noMonitor'
            }
        };
    },
    /**
     * 生命周期函数--监听页面加载
     * @param {*} options 配置项
     */
    onLoad: function (options) {
		console.log('onLoad')
        uni.setNavigationBarTitle({
            title: '视频看诊'
        });
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('visitRelatedInformation', (data) => {
			console.log(JSON.stringify(data));
            // 将String 类型的 true false 转换成 boolean
            Object.getOwnPropertyNames(data).forEach((key) => {
                if (data[key] === 'true') {
                    data[key] = true;
                }
                if (data[key] === 'false') {
                    data[key] = false;
                }
            });
            data.localVideo = true;
            data.localAudio = true;
            this.options = data;
            this.updatePersonnelStatus('I'); // 查询是否进入房间
            
            // 监听TRTC Room 关键事件
            // this.bindTRTCRoomEvent();

            // querystring 只支持传递 String 类型, 注意类型转换
            this.enterRoom({
                roomID: Number(data.roomID),
                userID: data.patID,
                patID: data.patID,
                doctorName: data.doctorName,
                patName: data.patName,
                frUserID: data.frUserID,
                toUserID: data.toUserID,
                isTextChat: data.isTextChat,
                admID: data.admID,
                template: data.template,
                debugMode: data.debugMode,
                cloudenv: data.cloudenv,
                frontCamera: data.frontCamera,
                localVideo: true,
                localAudio: true,
                enableEarMonitor: data.enableEarMonitor,
                enableAutoFocus: data.enableAutoFocus,
                localMirror: data.localMirror,
                enableAgc: data.enableAgc,
                enableAns: data.enableAns,
                encsmall: data.encsmall,
                videoHeight: data.videoHeight,
                videoWidth: data.videoWidth,
                scene: data.scene,
                maxBitrate: data.maxBitrate ? Number(data.maxBitrate) : 0,
                minBitrate: data.minBitrate ? Number(data.minBitrate) : 0
            });
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        console.log('room ready');
		// #ifdef MP
        uni.setKeepScreenOn({
            keepScreenOn: true
        });
		// #endif
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log('onShow');
        // this.onLoad();
        let pages = getCurrentPages();
        let currentPage = pages[pages.length - 1];
        let homeMsgData = this.$cache.get('homeMsgData');
        let mesIndex = '';
        console.log('homeMsgData', homeMsgData, 'currentPage', currentPage);
        let keys = Object.keys(homeMsgData);
        keys.forEach(function (item, index) {
            if (homeMsgData && (homeMsgData.type === 'E' || !homeMsgData.type) && homeMsgData[item].timetamp == currentPage.options) {
                mesIndex = index;
            }
        });
        if (mesIndex != '') {
            homeMsgData.remove(mesIndex);
            this.$cache.set('homeMsgData', homeMsgData);
        }
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        console.log('room hide');
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        console.log('room unload');
        this.updatePersonnelStatus('O');
		this.zpSelectComponent('#trtcComponent').exitCall(); // 退出通话
		
		// #ifdef MP
        uni.setKeepScreenOn({
            keepScreenOn: false
        });
		// #endif
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        let { imgHost, rtcConfig } = this;
        if (res.from === 'button') {
            // 来自页面内转发按钮
            console.log('来自页面内转发按钮', res.target);
        }
        return {
            title: rtcConfig.patName + '正在看诊，邀请您加入陪诊',
            path: 'pages/index/pages/waitingConsulation/waitingConsulation?isLink=true&admID=' + rtcConfig.admID,
            imageUrl: imgHost + '/images/icon/share-invitation.jpeg'
        };
    },
    methods: {
        enterRoom: function (params) {
            console.log('trtcRoom37', params);
            params.template = params.template || 'grid';
            params.roomID = params.roomID;
            params.userID = params.isTextChat !== 'yes' ? params.frUserID : this.randomUserID();
            console.log('*trtcRoom 41', params);
            const Signature = GenerateTestUserSig.genTestUserSig(params.userID);
            params.sdkAppID = Signature.sdkAppID;
            params.userSig = Signature.userSig;
            this.template = params.template;
			let rtcConfig = this.rtcConfig
            if (params.template === 'grid') {
                rtcConfig = {
					roomID: params.roomID,
                    sdkAppID: params.sdkAppID, // 您的实时音视频服务创建应用后分配的 sdkAppID
                    userID: params.userID,
                    doctorName: params.doctorName,
                    patID: params.patID,
                    patName: params.patName,
                    admID: params.admID,
                    userSig: params.userSig,
                    template: params.template, // 1v1 grid custom
                    debugMode: params.debugMode, // 非必要参数，打开组件的调试模式，开发调试时建议设置为 true
                    frontCamera: params.frontCamera,
                    enableEarMonitor: params.enableEarMonitor,
                    enableAutoFocus: params.enableAutoFocus,
                    localMirror: params.localMirror,
                    enableAgc: params.enableAgc,
                    enableAns: params.enableAns,
                    encsmall: params.encsmall ? 1 : 0,
                    videoWidth: params.videoWidth,
                    videoHeight: params.videoHeight,
                    scene: params.scene, // rtc live
                    maxBitrate: params.maxBitrate,
                    minBitrate: params.minBitrate,
                    beautyLevel: 0, // 开启美颜等级 0～9级美颜
                    enableIM: false, // 可选，仅支持初始化设置（进房前设置），不支持动态修改，需要开通云通信功能
                    frUserID: params.frUserID,
                    toUserID: params.toUserID,
                    isTextChat: params.isTextChat
                };
            } else {
                rtcConfig = {
					roomID: params.roomID,
                    admID: params.admID,
                    doctorName: params.doctorName,
                    patID: params.patID,
                    patName: params.patName,
                    frUserID: params.frUserID,
                    toUserID: params.toUserID,
                    isTextChat: params.isTextChat,
                    sdkAppID: params.sdkAppID, // 您的实时音视频服务创建应用后分配的 sdkAppID
                    userID: params.userID,
                    userSig: params.userSig,
                    template: params.template, // 1v1 grid custom
                    debugMode: params.debugMode, // 非必要参数，打开组件的调试模式，开发调试时建议设置为 true
                    beautyLevel: 0, // 默认开启美颜
                    enableIM: false // 可选，仅支持初始化设置（进房前设置），不支持动态修改，需要开通云通信功能
                };
            }

            this.setData(
                {
                    rtcConfig: rtcConfig
                },
                () => {
                    // 进房前决定是否推送视频或音频 部分机型会出现画面卡死，原因不明，必须放到进房成功事件后设置
                    // console.log('rtcConfig', this.data.rtcConfig)
                    // if (params.localVideo === true || params.template === '1v1') {
                    //   this.trtcComponent.publishLocalVideo()trtcConfig
                    // }
                    // if (params.localAudio === true || params.template === '1v1') {
                    //   this.trtcComponent.publishLocalAudio()
                    // }
                    console.log('trtcEnterRoom === ', this.zpSelectComponent('#navBar'))
					this.zpSelectComponent('#navBar').handleClose(); // 进入视频问诊页面，关闭呼叫视频提示框
					
					// 获取 rtcroom 实例
					this.trtcComponent = this.zpSelectComponent('#trtcComponent');
					console.log('获取 rtcroom 实例：', this.rtcConfig);
					this.trtcComponent.initCall(this.rtcConfig);
					
					
                    // roomID 取值范围 1 ~ 4294967295
                    // this.trtcComponent
                    //     .enterRoom({
                    //         roomID: params.roomID
                    //     })
                    //     .then(() => {
                    //         if (this.template === 'custom') {
                    //             // 设置推流端视窗的坐标和尺寸
                    //             this.trtcComponent.setViewRect({
                    //                 userID: params.userID,
                    //                 xAxis: '480rpx',
                    //                 yAxis: '160rpx',
                    //                 width: '240rpx',
                    //                 height: '320rpx'
                    //             });
                    //         }
                    //     })
                    //     .catch((res) => {
                    //         console.error('* room joinRoom 进房失败:', res);
                    //     });
                }
            );
        },

        bindTRTCRoomEvent: function () {
            const TRTC_EVENT = this.trtcComponent.EVENT;
            this.timestamp = [];
            // 初始化事件订阅
            this.trtcComponent.on(TRTC_EVENT.LOCAL_JOIN, (event) => {
                console.log('* room LOCAL_JOIN', event);
                // 进房成功，触发该事件后可以对本地视频和音频进行设置
                if (this.options.localVideo === true) {
                    this.trtcComponent.publishLocalVideo();
                }
                if (this.options.localAudio === true) {
                    this.trtcComponent.publishLocalAudio();
                }
            });
            this.trtcComponent.on(TRTC_EVENT.LOCAL_LEAVE, (event) => {
                console.log('* room LOCAL_LEAVE', event);
            });
            this.trtcComponent.on(TRTC_EVENT.ERROR, (event) => {
                console.log('* room ERROR', event);
            });
            // 远端用户进房
            this.trtcComponent.on(TRTC_EVENT.REMOTE_USER_JOIN, (event) => {
                console.log('* room REMOTE_USER_JOIN', event, this.trtcComponent.getRemoteUserList());
                this.timestamp.push(new Date());
                // 1v1视频通话时限制人数为两人的简易逻辑，建议通过后端实现房间人数管理
                // 2人以上同时进行通话请选择网格布局
                if (this.template === '1v1' && this.timestamp.length > 1) {
                    const interval = this.timestamp[1] - this.timestamp[0];
                    if (interval < 1000) {
                        // 房间里已经有两个人
                        this.setData(
                            {
                                showTipToast: true
                            },
                            () => {
                                setTimeout(() => {
                                    this.setData({
                                        showTipToast: false
                                    });
                                    uni.navigateBack({
                                        delta: 1
                                    });
                                }, 4000);
                            }
                        );
                    }
                }
            });

            // 远端用户退出
            this.trtcComponent.on(TRTC_EVENT.REMOTE_USER_LEAVE, (event) => {
                console.log('* room REMOTE_USER_LEAVE', event, this.trtcComponent.getRemoteUserList());
                if (this.template === '1v1') {
                    this.timestamp = [];
                }
                if (this.template === '1v1' && this.remoteUser === event.data.userID) {
                    this.remoteUser = null;
                }
            });
            // 远端用户推送视频
            this.trtcComponent.on(TRTC_EVENT.REMOTE_VIDEO_ADD, (event) => {
                console.log('* room REMOTE_VIDEO_ADD', event, this.trtcComponent.getRemoteUserList());
                // 订阅视频
                const userList = this.trtcComponent.getRemoteUserList();
                const data = event.data;
                if (this.template === '1v1' && (!this.remoteUser || this.remoteUser === data.userID)) {
                    // 1v1 只订阅第一个远端流
                    this.remoteUser = data.userID;
                    this.trtcComponent.subscribeRemoteVideo({
                        userID: data.userID,
                        streamType: data.streamType
                    });
                } else if (this.template === 'grid') {
                    this.trtcComponent.subscribeRemoteVideo({
                        userID: data.userID,
                        streamType: data.streamType
                    });
                }
                if (this.template === 'custom' && data.userID && data.streamType) {
                    let index = userList.findIndex((item) => {
                        return item.userID === data.userID;
                    });
                    index++;
                    const y = 320 * index + 160;
                    // 设置远端视图坐标和尺寸
                    this.trtcComponent.setViewRect({
                        userID: data.userID,
                        streamType: data.streamType,
                        xAxis: '480rpx',
                        yAxis: y + 'rpx',
                        width: '240rpx',
                        height: '320rpx'
                    });
                }
            });

            // 远端用户取消推送视频
            this.trtcComponent.on(TRTC_EVENT.REMOTE_VIDEO_REMOVE, (event) => {
                console.log('* room REMOTE_VIDEO_REMOVE', event, this.trtcComponent.getRemoteUserList());
            });

            // 远端用户推送音频
            this.trtcComponent.on(TRTC_EVENT.REMOTE_AUDIO_ADD, (event) => {
                console.log('* room REMOTE_AUDIO_ADD', event, this.trtcComponent.getRemoteUserList());
                // 订阅音频
                const data = event.data;
                if (this.template === '1v1' && (!this.remoteUser || this.remoteUser === data.userID)) {
                    this.remoteUser = data.userID;
                    this.trtcComponent.subscribeRemoteAudio({
                        userID: data.userID
                    });
                } else if (this.template === 'grid' || this.template === 'custom') {
                    this.trtcComponent.subscribeRemoteAudio({
                        userID: data.userID
                    });
                }
                // 如果不订阅就不会自动播放音频
                // this.trtcComponent.subscribeRemoteAudio({ userID: data.userID })
            });
            // 远端用户取消推送音频
            this.trtcComponent.on(TRTC_EVENT.REMOTE_AUDIO_REMOVE, (event) => {
                console.log('* room REMOTE_AUDIO_REMOVE', event, this.trtcComponent.getRemoteUserList());
            });
            this.trtcComponent.on(TRTC_EVENT.IM_SDK_READY, (event) => {
                console.log('* room IM_SDK_READY', event);
            });
            this.trtcComponent.on(TRTC_EVENT.IM_MESSAGE_RECEIVED, (event) => {
                console.log('* room IM_MESSAGE_RECEIVED', event);
            });
        },

        randomUserID: function () {
            return new Date().getTime().toString(16).split('').reverse().join('');
        },

        randomRoomID: function () {
            return parseInt(Math.random() * 9999);
        },

        // 发送消息
        handleSend(e, _dataset) {
            this.handleDataset(e, _dataset);
            this.trtcComponent._sendIMMessage();
        },

        // 监听到消息触发查询消息列表
        handleMessageReceived(event, _dataset) {
            this.handleDataset(event, _dataset);
            let data = event.detail;
            this.trtcComponent.handleMessageReceived(data);
        },

        // 吊起头部是否登录显示
        handleLoginShow(e, _dataset) {
            this.handleDataset(e, _dataset);
            this.zpSelectComponent('#navBar').handleLoginShow();
        },

        //  更新人员状态(进入房间后和退出房间后调用)
        updatePersonnelStatus(loginType) {
            console.log('updatePersonnelStatus: ', this.options);
            let { roomID, patID } = this.options;
            let data = {
                params: [
                    {
                        roomID,
                        userType: 'P',
                        userID: patID,
                        loginType
                    }
                ]
            };
            $http.post('urlS', this, {
                code: '02090002',
                data: data,
                namespace: 'Y',
                success: function (res) {
                    if (+res.errorCode === 0) {
                        console.log(res);
                    } else {
                        console.log(res.errorMessage);
                    }
                }
            });
        }
    }
};
</script>
<style>
/* miniprogram/pages/room/room.wxss */
.page-room {
    width: 100vw;
    overflow: hidden;
}

.tip-toast {
    position: absolute;
    top: 40vh;
    width: 70vw;
    left: 15vw;
    border-radius: 12rpx;
    height: 20vh;
    background: rgba(0, 0, 0, 0.8);
    color: white;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.tip-toast view {
    padding: 20rpx 0;
    font-size: 32rpx;
}
</style>
