// TIM H5 环境适配器（参考患者端 MY_MiniApp_H5/src/components/h5-trtc-room/tim-h5-adapter.js）
import TIM from 'tim-js-sdk';
import TRTC from 'trtc-js-sdk';

// 初始化配置
const TIM_CONFIG = {
    SDKAppID: 0
};

// 存储 TIM 实例
let tim = null;
// 存储 TRTC 实例
let trtcClient = null;
let localStream = null;
let remoteStreams = {};

/**
 * 初始化 TIM SDK
 */
export function initTIM(config) {
    return new Promise((resolve, reject) => {
        try {
            tim = TIM.create({
                SDKAppID: config.sdkAppID || TIM_CONFIG.SDKAppID
            });

            if (config.debugMode) {
                tim.setLogLevel(1);
            } else {
                tim.setLogLevel(4);
            }

            tim.on(TIM.EVENT.SDK_READY, handleSDKReady);
            tim.on(TIM.EVENT.MESSAGE_RECEIVED, handleMessageReceived);
            tim.on(TIM.EVENT.SDK_NOT_READY, handleSDKNotReady);
            tim.on(TIM.EVENT.KICKED_OUT, handleKickedOut);
            tim.on(TIM.EVENT.ERROR, handleError);

            console.log('[h5-trtc-room] 登录 TIM config', config);

            tim.login({
                userID: config.userID,
                userSig: config.userSig
            })
                .then((imResponse) => {
                    console.log('[h5-trtc-room] TIM 登录成功:', imResponse);
                    resolve(tim);
                })
                .catch((imError) => {
                    console.error('[h5-trtc-room] TIM 登录失败:', imError);
                    reject(imError);
                });
        } catch (error) {
            console.error('[h5-trtc-room] TIM 初始化失败:', error);
            reject(error);
        }
    });
}

/**
 * 初始化 TRTC 客户端
 */
export function initTRTC(config) {
    console.log('[h5-trtc-room] initTRTC config：', config);
    return new Promise((resolve, reject) => {
        try {
            trtcClient = TRTC.createClient({
                sdkAppId: config.sdkAppID || TIM_CONFIG.SDKAppID,
                userId: config.userId,
                userSig: config.userSig,
                mode: 'rtc'
            });

            trtcClient.on('stream-added', handleStreamAdded);
            trtcClient.on('stream-subscribed', handleStreamSubscribed);
            trtcClient.on('stream-removed', handleStreamRemoved);
            trtcClient.on('peer-leave', handlePeerLeave);
            trtcClient.on('error', handleTRTCError);

            trtcClient
                .join({ roomId: config.roomId })
                .then(() => {
                    console.log('[h5-trtc-room] 加入房间成功');
                    createLocalStream()
                        .then((stream) => {
                            localStream = stream;
                            trtcClient
                                .publish(localStream)
                                .then(() => {
                                    console.log('[h5-trtc-room] 发布本地流成功');
                                    resolve({ localStream, trtcClient });
                                })
                                .catch((error) => {
                                    console.error('[h5-trtc-room] 发布本地流失败:', error);
                                    reject(error);
                                });
                        })
                        .catch((error) => {
                            console.error('[h5-trtc-room] 创建本地流失败:', error);
                            reject(error);
                        });
                })
                .catch((error) => {
                    console.error('[h5-trtc-room] 加入房间失败:', error);
                    reject(error);
                });
        } catch (error) {
            console.error('[h5-trtc-room] TRTC 初始化失败:', error);
            reject(error);
        }
    });
}

function createLocalStream() {
    return new Promise((resolve, reject) => {
        try {
            const stream = TRTC.createStream({
                audio: true,
                video: true,
                screen: false
            });

            stream
                .initialize()
                .then(() => {
                    console.log('[h5-trtc-room] 本地流初始化成功');
                    resolve(stream);
                })
                .catch((error) => {
                    console.error('[h5-trtc-room] 本地流初始化失败:', error);
                    reject(error);
                });
        } catch (error) {
            console.error('[h5-trtc-room] 创建本地流异常:', error);
            reject(error);
        }
    });
}

function handleStreamAdded(event) {
    const remoteStream = event.stream;
    console.log('[h5-trtc-room] 检测到远程流:', remoteStream.getUserId());
    trtcClient.subscribe(remoteStream);
}

function handleStreamSubscribed(event) {
    const remoteStream = event.stream;
    const userId = remoteStream.getUserId();
    console.log('[h5-trtc-room] 订阅远程流成功:', userId);
    remoteStreams[userId] = remoteStream;
    window.dispatchEvent(
        new CustomEvent('remote-stream-added', {
            detail: { userId, stream: remoteStream }
        })
    );
}

function handleStreamRemoved(event) {
    const remoteStream = event.stream;
    const userId = remoteStream.getUserId();
    console.log('[h5-trtc-room] 远程流移除:', userId);
    if (remoteStreams[userId]) {
        remoteStreams[userId].stop();
        delete remoteStreams[userId];
        window.dispatchEvent(
            new CustomEvent('remote-stream-removed', {
                detail: { userId }
            })
        );
    }
}

function handlePeerLeave(event) {
    const userId = event.userId;
    console.log('[h5-trtc-room] 远端用户离开:', userId);
    if (remoteStreams[userId]) {
        remoteStreams[userId].stop();
        delete remoteStreams[userId];
        window.dispatchEvent(
            new CustomEvent('peer-leave', {
                detail: { userId }
            })
        );
    }
}

function handleSDKReady(event) {
    console.log('[h5-trtc-room] TIM SDK 就绪');
    window.dispatchEvent(new CustomEvent('tim-sdk-ready', { detail: { event } }));
}

function handleMessageReceived(event) {
    console.log('[h5-trtc-room] 收到消息:', event);
    window.dispatchEvent(new CustomEvent('tim-message-received', { detail: { event } }));
}

function handleSDKNotReady(event) {
    console.log('[h5-trtc-room] TIM SDK 未就绪');
    window.dispatchEvent(new CustomEvent('tim-sdk-not-ready', { detail: { event } }));
}

function handleKickedOut(event) {
    console.log('[h5-trtc-room] 被踢下线:', event);
    window.dispatchEvent(new CustomEvent('tim-kicked-out', { detail: { event } }));
}

function handleError(event) {
    console.error('[h5-trtc-room] TIM 错误:', event);
    window.dispatchEvent(new CustomEvent('tim-error', { detail: { event } }));
}

function handleTRTCError(event) {
    console.error('[h5-trtc-room] TRTC 错误:', event);
    window.dispatchEvent(new CustomEvent('trtc-error', { detail: { event } }));
}

/**
 * 退出房间并销毁资源（仅退出 TRTC，不动 TIM）
 */
export function exitRoom() {
    return new Promise((resolve, reject) => {
        try {
            if (localStream) {
                localStream.stop();
                localStream.close && localStream.close();
                localStream = null;
            }

            Object.values(remoteStreams).forEach((stream) => {
                stream.stop();
            });
            remoteStreams = {};

            if (trtcClient) {
                trtcClient
                    .leave()
                    .then(() => {
                        console.log('[h5-trtc-room] 离开房间成功');
                        trtcClient = null;
                        resolve();
                    })
                    .catch((error) => {
                        console.error('[h5-trtc-room] 离开房间失败:', error);
                        trtcClient = null;
                        reject(error);
                    });
            } else {
                resolve();
            }
        } catch (error) {
            console.error('[h5-trtc-room] 退出房间异常:', error);
            reject(error);
        }
    });
}

/**
 * 登出 TIM（医生端通常不调用，避免影响全局 IM 会话）
 */
export function logoutTIM() {
    return new Promise((resolve, reject) => {
        try {
            if (tim) {
                tim.logout()
                    .then((imResponse) => {
                        console.log('[h5-trtc-room] TIM 登出成功:', imResponse);
                        tim.off(TIM.EVENT.SDK_READY, handleSDKReady);
                        tim.off(TIM.EVENT.MESSAGE_RECEIVED, handleMessageReceived);
                        tim.off(TIM.EVENT.SDK_NOT_READY, handleSDKNotReady);
                        tim.off(TIM.EVENT.KICKED_OUT, handleKickedOut);
                        tim.off(TIM.EVENT.ERROR, handleError);
                        tim = null;
                        resolve();
                    })
                    .catch((imError) => {
                        console.error('[h5-trtc-room] TIM 登出失败:', imError);
                        reject(imError);
                    });
            } else {
                resolve();
            }
        } catch (error) {
            console.error('[h5-trtc-room] 登出 TIM 异常:', error);
            reject(error);
        }
    });
}

/**
 * 开关麦克风
 */
export function openCloseMicrophone(enabled) {
    return new Promise((resolve, reject) => {
        try {
            if (localStream) {
                if (enabled) {
                    localStream.unmuteAudio();
                } else {
                    localStream.muteAudio();
                }
                resolve();
            } else {
                reject(new Error('本地流未初始化'));
            }
        } catch (error) {
            console.error('[h5-trtc-room] 切换麦克风失败:', error);
            reject(error);
        }
    });
}

/**
 * 开关摄像头
 */
export function openCloseCamera(enabled) {
    return new Promise((resolve, reject) => {
        try {
            if (localStream) {
                if (enabled) {
                    localStream.unmuteVideo();
                } else {
                    localStream.muteVideo();
                }
                resolve();
            } else {
                reject(new Error('本地流未初始化'));
            }
        } catch (error) {
            console.error('[h5-trtc-room] 切换摄像头失败:', error);
            reject(error);
        }
    });
}

/**
 * 获取摄像头列表
 */
export function getCamera() {
    return new Promise((resolve, reject) => {
        try {
            TRTC.getCameras()
                .then((devices) => {
                    devices.forEach((dev) => {
                        console.log('[h5-trtc-room] camera label: ' + dev.label + ' deviceId: ' + dev.deviceId);
                    });
                    resolve(devices);
                })
                .catch((error) => {
                    reject(error);
                });
        } catch (error) {
            console.error('[h5-trtc-room] 获取摄像头失败:', error);
            reject(error);
        }
    });
}

/**
 * 是否开启扬声器
 */
export function openCloseSpeaker(enabled) {
    return new Promise(async (resolve, reject) => {
        try {
            await TRTC.muteRemoteAudio('*', enabled);
            resolve();
        } catch (error) {
            console.error('[h5-trtc-room] 切换扬声器失败:', error);
            reject(error);
        }
    });
}

export { TIM, TRTC };
