<template>
    <view>
        <view class="page-room">
            <trtc-room ref="trtcComponent" :config="rtcConfig" @exit="onExitRoom"></trtc-room>
        </view>
    </view>
</template>

<script>
// 医生端 H5 视频看诊房间页（参考患者端 MY_MiniApp_H5/src/pages/message/pages/im/trtcRoom/trtcRoom.vue 实现）
import TrtcRoom from '@/components/h5-trtc-room/trtc-room';
import { SDKAPPID, genTestUserSig } from '@/utils/GenerateTestUserSig.js';
import { $http } from '@/config/https.js';
import Cache from '@/utils/cache';
import messageUtil from '@/utils/message.js';

const app = getApp();

export default {
    components: {
        'trtc-room': TrtcRoom
    },
    data() {
        return {
            rtcConfig: {
                sdkAppID: '',
                patID: '',
                userID: '',
                userSig: '',
                template: '',
                frUserID: '',
                toUserID: '',
                isTextChat: '',
                admID: '',
                doctorName: '',
                patName: '',
                roomID: ''
            },
            options: {}
        };
    },

    onLoad: function (options) {
        console.log('[doctor trtcRoom] onLoad', options);
        uni.setNavigationBarTitle({ title: '视频看诊' });

        const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel();
        if (eventChannel && typeof eventChannel.on === 'function') {
            eventChannel.on('visitRelatedInformation', (data) => {
                console.log('[doctor trtcRoom] visitRelatedInformation:', data);
                this.handleEnter(data || {});
            });
        } else {
            // 兜底：H5 部分场景拿不到 eventChannel 时，直接根据 patientData 进房
            console.warn('[doctor trtcRoom] eventChannel 不可用，使用 patientData 兜底');
            this.handleEnter({});
        }
    },

    onUnload: function () {
        console.log('[doctor trtcRoom] onUnload');
        this.updatePersonnelStatus('O');
        try {
            if (this.$refs.trtcComponent && typeof this.$refs.trtcComponent.exitCall === 'function') {
                this.$refs.trtcComponent.exitCall();
            }
        } catch (e) {
            console.error('[doctor trtcRoom] exitCall error:', e);
        }
    },

    methods: {
        /**
         * 处理进房逻辑：组装 rtcConfig 并调用组件 initCall
         */
        handleEnter(data) {
            const patientData = Cache.get('patientData') || {};
            const userData = Cache.get('userData') || {};

            const roomID = Number(data.roomID || data.roomNo || patientData.roomNo);
            const userID = 'user' + userData.userID;
            const patID = 'patient' + (data.patID || patientData.patID);

            if (!roomID) {
                uni.showToast({ icon: 'none', title: '房间号缺失，无法进房' });
                return;
            }
            if (!userData.userID) {
                uni.showToast({ icon: 'none', title: '医生身份缺失，请重新登录' });
                return;
            }

            const Signature = genTestUserSig(userID);
            const sdkAppID = Signature.sdkappid;
            const userSig = Signature.userSig;

            // 关键日志：用于跟患者端对比 SDKAppID 是否一致
            console.log('[doctor trtcRoom] [TIM/TRTC] SDKAppID:', sdkAppID, 'userID:', userID, 'roomID:', roomID);

            this.options = Object.assign({}, data, { roomID, patID, userID });

            this.rtcConfig = {
                roomID,
                sdkAppID,
                userID,
                userSig,
                template: 'grid',
                debugMode: false,
                enableIM: false,
                patID,
                frUserID: data.frUserID || userID,
                toUserID: data.toUserID || patID,
                admID: data.admID || patientData.admID || '',
                doctorName: data.doctorName || userData.userName || '',
                patName: data.patName || patientData.patName || '',
                isTextChat: data.isTextChat || ''
            };

            this.updatePersonnelStatus('I');

            this.$nextTick(() => {
                if (this.$refs.trtcComponent && typeof this.$refs.trtcComponent.initCall === 'function') {
                    this.$refs.trtcComponent.initCall(this.rtcConfig);
                } else {
                    console.error('[doctor trtcRoom] trtc-room 子组件未就绪');
                }
            });
        },

        /**
         * 更新医生在房间内的状态（与患者端一致接口 02090002，userType='U'）
         */
        updatePersonnelStatus(loginType) {
            const userData = Cache.get('userData') || {};
            const roomID = this.options.roomID;
            const userID = userData.userID;
            if (!roomID || !userID) return;
            const data = {
                params: [
                    {
                        roomID,
                        userType: 'U',
                        userID,
                        loginType
                    }
                ]
            };
            $http.post('urlS', this, {
                code: '02090002',
                data,
                namespace: 'Y',
                success: function (res) {
                    console.log('[doctor trtcRoom] updatePersonnelStatus(' + loginType + ') ->', res && res.errorCode);
                }
            });
        },

        /**
         * 子组件 exit 事件：清理定时器 + 返回上一页
         */
        onExitRoom() {
            console.log('[doctor trtcRoom] onExitRoom');
            const patientData = Cache.get('patientData') || {};
            try {
                messageUtil.clearTimer && messageUtil.clearTimer('patient' + patientData.patID);
            } catch (e) {
                console.warn('[doctor trtcRoom] clearTimer error:', e);
            }
            uni.navigateBack({ delta: 1 });
        }
    }
};
</script>

<style>
.page-room {
    width: 100vw;
    overflow: hidden;
}
</style>
