import { $http } from '../config/https.js';
import Toast from './toast';
import { SDKAPPID, getSDKAppID, genTestUserSig } from './GenerateTestUserSig.js';
// #ifdef MP-WEIXIN
import TIM from 'tim-wx-sdk';
import COS from 'cos-wx-sdk-v5';
// #endif
// #ifndef MP-WEIXIN
import TIM from 'tim-js-sdk';
// #endif
import Cache from './cache.js';
const getRuntimeApp = () => {
    const app = typeof getApp === 'function' ? getApp() : null;
    if (app) {
        app.globalData = app.globalData || {};
        return app;
    }
    return { globalData: {} };
};
const app = new Proxy(
    {},
    {
        get(target, key) {
            return getRuntimeApp()[key];
        },
        set(target, key, value) {
            getRuntimeApp()[key] = value;
            return true;
        }
    }
);

// initTim 重试计数器，避免appInfo延迟到达时 TIM 永不初始化
let _initTimRetry = 0;
const _INIT_TIM_MAX_RETRY = 10; // 最多重试 10 次（1s/次，共10s）

//初始化IM 消息
const initTim = (callback) => {
    const sdkAppID = getSDKAppID();
    console.log('[TIM][医生端] initTim -> SDKAppID:', sdkAppID);
    if (!sdkAppID) {
        if (_initTimRetry < _INIT_TIM_MAX_RETRY) {
            _initTimRetry++;
            console.warn('[TIM][医生端] appInfo 未就绪，1s 后重试 initTim (第 ' + _initTimRetry + ' 次)');
            setTimeout(() => initTim(callback), 1000);
        } else {
            console.warn('[TIM][医生端] appInfo 多次重试仍为空，放弃初始化。请检查 03100143 接口返回是否含 imAppID/imSecret');
            if (callback) callback();
        }
        return;
    }
    _initTimRetry = 0;

    let TIMInfo = Cache.get('TIMInfo');
    if (!TIMInfo) {
        TIMInfo = {};
        Cache.set('TIMInfo', TIMInfo);
    }
    if (app.globalData.timObj == null) {
        let timOptions = {
            SDKAppID: sdkAppID
        };
        app.globalData.timObj = TIM.create(timOptions);

        app.globalData.timObj.setLogLevel(0);

        // #ifdef MP-WEIXIN
        app.globalData.timObj.registerPlugin({
            'cos-wx-sdk': COS
        });
        // #endif
        if (!TIMInfo || Object.keys(TIMInfo).length === 0) {
            loginTim(callback);
        } else {
            if (TIMInfo.loginStatus == 'Y') {
                loginOut(() => loginTim(callback));
            } else {
                loginTim(callback);
            }
        }
    } else {
        let loginStatus = TIMInfo.loginStatus;
        if (loginStatus != 'Y') {
            loginTim(callback);
        } else if (callback) {
            callback();
        }
    }
};
/**
 * 全局接受到消息后触发
 */
const onMessageReceived = function (event, callback) {
    if (event.data) {
        event.data.map((item) => {
            console.log(item);
            const patientData = Cache.get('patientData');
            const userData = Cache.get('userData');
            let fromuser = item.from;
            if (patientData && 'patient' + patientData.patID === fromuser) {
                if (callback) {
                    callback();
                }
            }
        });
    }
};
/**
 * 登录IM用户
 */
const loginTim = (callback) => {
    if (app.globalData.timObj) {
        let TIMInfo = Cache.get('TIMInfo') || {};
        const userData = Cache.get('userData') || {};
        if (!userData.userID) {
            TIMInfo.loginStatus = 'N';
            Cache.set('TIMInfo', TIMInfo);
            console.warn('[TIM][医生端] loginTim 跳过：userData.userID 为空');
            if (callback) callback();
            return;
        }
        let userID = 'user' + userData.userID;
        let user = genTestUserSig(userID || '');
        console.log('[TIM][医生端] loginTim -> userID:', userID, 'sdkAppID:', user && user.sdkappid);
        let promise = app.globalData.timObj.login({
            userID: userID || '',
            userSig: user && user.userSig ? user.userSig : ''
        });
        promise
            .then((imResponse) => {
                console.log('[TIM][医生端] login response:', imResponse);
                if (imResponse.data.errorCode == 0) {
                    let params = {
                        params: [
                            {
                                imUserID: 'user' + userData.userID,
                                userType: 'U',
                                userID: userData.userID
                            }
                        ]
                    };
                    $http.post('urlDeault', null, {
                        code: '03090002',
                        data: params,
                        success: function (res) {}
                    });
                    TIMInfo.loginStatus = 'Y';
                    TIMInfo.isKickedOut = true;
                    app.globalData.timObj.on(TIM.EVENT.KICKED_OUT, monitorKickedOut);
                    app.globalData.timObj.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
                    Cache.set('TIMInfo', TIMInfo);
                } else {
                    TIMInfo.loginStatus = 'N';
                    Cache.set('TIMInfo', TIMInfo);
                }
                if (callback) {
                    callback();
                }
            })
            .catch(function (imError) {
                console.warn('[TIM][医生端] login error:', imError);
                let TIMInfo = Cache.get('TIMInfo') || {};
                TIMInfo.loginStatus = 'N';
                Cache.set('TIMInfo', TIMInfo);
                if (callback) callback();
            });
    } else {
        initTim(callback);
    }
};
/**
 * 登出
 */
const loginOut = (callback) => {
    const tim = app && app.globalData && app.globalData.timObj;
    if (!tim || typeof tim.logout !== 'function') {
        // H5 或 IM 未初始化场景：仅更新本地 TIMInfo，直接回调
        const TIMInfo = Cache.get('TIMInfo') || {};
        TIMInfo.loginStatus = 'N';
        Cache.set('TIMInfo', TIMInfo);
        if (callback) callback();
        return;
    }
    let promise;
    try {
        promise = tim.logout();
    } catch (e) {
        console.warn('[TIM] logout threw:', e);
    }
    if (promise && typeof promise.then === 'function') {
        promise
            .then(() => {
                const TIMInfo = Cache.get('TIMInfo') || {};
                TIMInfo.loginStatus = 'N';
                Cache.set('TIMInfo', TIMInfo);
                if (callback) callback();
            })
            .catch(function (imError) {
                console.warn('[TIM] logout reject:', imError);
                if (callback) callback();
            });
    } else {
        if (callback) callback();
    }
};
/**被踢出 */
const monitorKickedOut = (event) => {
    let TIMInfo = Cache.get('TIMInfo');
    let { isKickedOut } = TIMInfo;
    TIMInfo.isKickedOut = false;
    Cache.set('TIMInfo', TIMInfo);
    if (isKickedOut) {
        uni.setStorage({
            key: 'TIMInfo',
            data: TIMInfo,
            success: function () {
                uni.showModal({
                    title: '您的账号在别处登录',
                    content: '是否重新登录???\n取消登录后将不能收到实时音视频消息',
                    success: function (e) {
                        TIMInfo.isKickedOut = true;
                        if (e.cancel) {
                            TIMInfo.loginStatus = 'N';
                        }
                        if (e.confirm) {
                            loginTim();
                        }
                        Cache.set('TIMInfo', TIMInfo);
                    },
                    fail: function (e) {}
                });
            }
        });
    }
};
/**
 * 邀请医生
 */
const inviteDoctor = () => {
    const patientData = Cache.get('patientData');
    const userData = Cache.get('userData');
    let messageContent = {};
    messageContent.userID = userData.userID;
    messageContent.admID = patientData.admID;
    messageContent.patID = patientData.patID;
    messageContent.patName = patientData.patName;
    messageContent.userName = userData.userName;
    messageContent.type = 'I';
    messageContent.text = '邀请您视频问诊';
    messageContent.roomNo = app.globalData.roomNo;
    messageContent.inviteDocName = app.globalData.toUserName;
    messageContent.invitePatName = patientData.patName;
    let message = app.globalData.timObj.createTextMessage({
        to: app.globalData.toUser,
        conversationType: TIM.TYPES.CONV_C2C,
        payload: {
            text: JSON.stringify(messageContent)
        }
    });
    // 2. 发送消息
    let promise = app.globalData.timObj.sendMessage(message);
    if (promise) {
        promise.then((imResponse) => {});
    }
};
const handleSendMessage = (type, text, toUser, toUserName, roomNo, patientData, other) => {
    if (!patientData) {
        patientData = Cache.get('patientData');
    }
    const userData = Cache.get('userData');
    let messageContent = {};
    messageContent.userID = userData.userID;
    messageContent.admID = patientData.admID;
    messageContent.patID = patientData.patID;
    messageContent.patName = patientData.patName;
    messageContent.userName = userData.userName;
    messageContent.type = type;
    messageContent.text = text;
    if (type == 'I') {
        if (toUserName) {
            messageContent.inviteDocName = toUserName;
        }
        if (roomNo) {
            messageContent.roomNo = roomNo;
        }
        messageContent.invitePatName = patientData.patName;
        app.globalData.toUser = toUser;
        app.globalData.roomNo = roomNo;
        app.globalData.text = text;
        app.globalData.toUserName = toUserName;
        creatTimer(toUser, inviteDoctor);
    }
    if (!toUser) {
        toUser = 'patient' + patientData.patID;
    }
    console.log(JSON.stringify(messageContent));
    let message = app.globalData.timObj.createTextMessage({
        to: toUser,
        conversationType: TIM.TYPES.CONV_C2C,
        payload: {
            text: JSON.stringify(messageContent)
        }
    });
    // 2. 发送消息
    let promise = app.globalData.timObj.sendMessage(message);
    if (promise) {
        promise
            .then((imResponse) => {
                if (type != 'M' && type != 'V' && type != 'I' && type != 'E' && type != 'R') {
                    let eventCode = '';
                    switch (type) {
                        case 'B':
                            //医生停诊
                            eventCode = '2003';
                            break;
                        case 'D':
                            //待支付订单
                            eventCode = '2005';
                            break;
                        case 'F':
                            //待评价消息
                            eventCode = '2006';
                            break;
                        case 'P':
                            //待确认处方
                            eventCode = '2008';
                            break;
                    }
                    saveMessage(eventCode, text, patientData);
                }
                if (other && other.error) {
                    other.success.call();
                }
            })
            .catch(function (imError) {
                if (imError.code == '20003') {
                    uni.showModal({
                        title: '发送即时消息失败',
                        content: '对方未开通消息接收,可提醒对方登录互联网小程序或请联系管理员',
                        showCancel: false,
                        confirmText: '知道了'
                    });
                    if (other && other.error) {
                        other.fail.call();
                    }
                    return false;
                }
            });
        return true;
    }
};
// 停诊使用
const handleSendMessage2 = (type, text, toUser, patientData) => {
    // const patientData = wx.getStorageSync('patientData');
    const userData = Cache.get('userData');
    let messageContent = {};
    messageContent.userID = userData.userID;
    messageContent.admID = patientData.admID;
    messageContent.patID = patientData.patID;
    messageContent.patName = patientData.patName;
    messageContent.userName = userData.userName;
    messageContent.type = type;
    messageContent.text = text;
    if (type == 'I') {
        // if (toUserName) messageContent.inviteDocName = toUserName;
        // if (roomNo) messageContent.roomNo = roomNo;
        messageContent.invitePatName = patientData.patName;
        app.globalData.toUser = toUser;
        // app.roomNo = roomNo;
        app.globalData.text = text;
        // app.toUserName = toUserName;
        creatTimer('user' + userData.userID, inviteDoctor);
    }
    if (!toUser) {
        toUser = 'patient' + patientData.patID;
    }
    console.log(JSON.stringify(messageContent));
    let message = app.globalData.timObj.createTextMessage({
        to: toUser,
        conversationType: TIM.TYPES.CONV_C2C,
        payload: {
            text: JSON.stringify(messageContent)
        }
    });
    // 2. 发送消息
    let promise = app.globalData.timObj.sendMessage(message);
    if (promise) {
        promise
            .then((imResponse) => {
                if (type != 'M' && type != 'V' && type != 'I' && type != 'E' && type != 'R') {
                    let eventCode = '';
                    switch (type) {
                        case 'B':
                            //医生停诊
                            eventCode = '2003';
                            break;
                        case 'D':
                            //待支付订单
                            eventCode = '2005';
                            break;
                        case 'F':
                            //待评价消息
                            eventCode = '2006';
                            break;
                        case 'P':
                            //待确认处方
                            eventCode = '2008';
                            break;
                    }
                    saveMessage2(eventCode, text, patientData);
                }
            })
            .catch(function (imError) {
                if (imError.code == '20003') {
                    uni.showToast({
                        title: '对方未开通消息接收,请联系管理员',
                        icon: 'none'
                    });
                    return false;
                }
            });
        return true;
    }
};
const saveMessage2 = (eventCode, content, patientData) => {
    const userData = Cache.get('userData');
    // const patientData = wx.getStorageSync('patientData');
    let receiveUser = patientData.patID;
    let receiveTypeCode = 'P';
    if (eventCode == '2008') {
        receiveUser = userData.userID;
        receiveTypeCode = 'U';
    }
    let params = {
        params: [
            {
                sendUserName: userData.userName,
                receiveUserName: patientData.patName,
                eventCode: eventCode,
                sendTypeCode: 'U',
                receiveTypeCode: receiveTypeCode,
                sendUser: userData.userID,
                receiveUser: receiveUser,
                content: content,
                userID: userData.userID,
                admID: patientData.admID
            }
        ]
    };
    $http.post('urlDeault', this, {
        code: '03100096',
        data: params,
        success: function (res) {
            if (res.errorCode == '0') {
            }
        }
    });
};
/**
 * 保存消息到消息列表
 */
const saveMessage = (eventCode, content, patientData) => {
    const userData = Cache.get('userData');
    if (!patientData) {
        patientData = Cache.get('patientData');
    }
    let receiveUser = patientData.patID;
    let receiveTypeCode = 'P';
    if (eventCode == '2008') {
        receiveUser = userData.userID;
        receiveTypeCode = 'U';
    }
    let params = {
        params: [
            {
                sendUserName: userData.userName,
                receiveUserName: patientData.patName,
                eventCode: eventCode,
                sendTypeCode: 'U',
                receiveTypeCode: receiveTypeCode,
                sendUser: userData.userID,
                receiveUser: receiveUser,
                content: content,
                userID: userData.userID,
                admID: patientData.admID
            }
        ]
    };
    $http.post('urlDeault', this, {
        code: '03100096',
        data: params,
        success: function (res) {
            if (res.errorCode == '0') {
            }
        }
    });
};
/**
 * 发送视频呼叫消息
 */
const handleSendVideo = async (confirm, cancel) => {
    const patientData = Cache.get('patientData');
    const userData = Cache.get('userData');
    let messageContent = {};
    messageContent.userID = userData.userID;
    messageContent.admID = patientData.admID;
    messageContent.patID = patientData.patID;
    messageContent.patName = patientData.patName;
    messageContent.userName = userData.userName;
    messageContent.type = 'V';
    messageContent.text = '视频呼叫';
    let message = app.globalData.timObj.createTextMessage({
        to: 'patient' + patientData.patID,
        conversationType: TIM.TYPES.CONV_C2C,
        payload: {
            text: JSON.stringify(messageContent)
        }
    });
    // 2. 发送消息
    let promise = app.globalData.timObj.sendMessage(message);
    if (promise) {
        promise
            .then((imResponse) => {})
            .catch(function (imError) {
                uni.showModal({
                    title: '呼叫失败',
                    content: '呼叫患者失败,是否重新呼叫???',
                    success: function (e) {
                        if (e.cancel) {
                            if (cancel) {
                                cancel();
                            }
                        }
                        if (e.confirm) {
                            if (confirm) {
                                confirm();
                            }
                        }
                    },
                    fail: function (e) {}
                });
            });
    }
};
const allowToJoin = (path, roomNo, inviteFlag) => {
    // #ifdef H5
    callVedioPat(path, roomNo, inviteFlag);
    return;
    // #endif
    if (typeof uni.getSetting !== 'function') {
        callVedioPat(path, roomNo, inviteFlag);
        return;
    }
    uni.getSetting({
        success: (res) => {
            if (!res.authSetting['scope.camera'] || !res.authSetting['scope.record']) {
                //获取摄像头权限
                uni.showModal({
                    title: '视频问诊需要以下权限',
                    content: '摄像头/麦克风\n为了让医生更好的诊疗,满足政策监管要求',
                    confirmText: '开启权限',
                    cancelText: '取消',
                    success: function (res) {
                        if (res.confirm) {
                            getPermission(path, roomNo, inviteFlag);
                        } else if (res.cancel) {
                            uni.showModal({
                                title: '提示',
                                content: '未开启摄像头和麦克风权限,不能进行视频问诊'
                            });
                        }
                    }
                });
            } else {
                callVedioPat(path, roomNo, inviteFlag);
            }
        },
        fail(res) {
            uni.showModal({
                title: '提示',
                content: '权限检测失败!'
            });
        }
    });
};
const getPermission = (path, roomNo, inviteFlag) => {
    if (typeof uni.authorize !== 'function') {
        callVedioPat(path, roomNo, inviteFlag);
        return;
    }
    uni.authorize({
        scope: 'scope.camera',
        success(res) {
            uni.authorize({
                scope: 'scope.record',
                success(res) {
                    callVedioPat(path, roomNo, inviteFlag);
                },
                fail(res) {
                    uni.showModal({
                        title: '提示',
                        content: '开启权限失败!'
                    });
                }
            });
        },
        fail(res) {
            uni.showModal({
                title: '提示',
                content: '开启权限失败!'
            });
        }
    });
};
// 视频呼叫
const callVedioPat = (path, roomNo, inviteFlag) => {
    // const innerAudioContext = wx.createInnerAudioContext()
    // innerAudioContext.autoplay = true
    // innerAudioContext.src = '../assets/voice/startVideo.mp3'
    // innerAudioContext.onPlay(() => {
    //   console.log('开始播放')
    // })
    // innerAudioContext.onError((res) => {
    //   console.log(res.errMsg)
    //   console.log(res.errCode)
    // })
    // innerAudioContext.onError((res) => {
    //   console.log(res.errMsg)
    //   console.log(res.errCode)
    // })
    const patientData = Cache.get('patientData');
    const userData = Cache.get('userData');
    let data = {
        params: [
            {
                roomID: roomNo || patientData.roomNo,
                // 房间ID
                userType: 'U',
                // U-医生,P-患者
                userID: userData.userID || '',
                // 人员ID
                frUser: 'user' + userData.userID || ''
            }
        ]
    };
    $http.post('urlS', this, {
        code: '02090003',
        data: data,
        namespace: 'Y',
        success: function (res) {
            if (+res.errorCode === 0) {
                wx: uni.navigateTo({
                    url: path,
                    success: (result) => {
                        if (inviteFlag != 'Y') {
                            handleSendVideo(allowToJoin);
                        }
                        let data = {};
                        if (roomNo) {
                            data.roomNo = roomNo;
                        }
                        if (inviteFlag != 'Y') {
                            creatTimer('patient' + patientData.patID, handleSendVideo);
                        }
                        result.eventChannel.emit('visitRelatedInformation', data);
                    },
                    fail: function (e) {
                        console.log(e);
                    }
                });
                callPat();
            } else {
            }
        }
    });
};
/**
 * 删除定时器
 */
const clearTimer = (timer) => {
    clearInterval(app.globalData[timer]);
    app.globalData[timer] = null;
};
/**
 * 创建定时器 10秒定时器
 */
const creatTimer = (timer, callback) => {
    if (app.globalData[timer]) {
        //如果该用户已创建定时器，先清除掉定时器。
        clearInterval(app.globalData[timer]);
        setTimeout(() => {
            app.globalData[timer] = setInterval(() => {
                callback();
            }, 10000);
        }, 100);
    } else {
        app.globalData[timer] = setInterval(() => {
            callback();
        }, 10000);
    }
};
/**
 * 后台状态改为呼叫中
 */
const callPat = () => {
    const patientData = Cache.get('patientData');
    const userData = Cache.get('userData');
    let data = {
        params: [
            {
                hospID: userData.hospID,
                userID: userData.userID,
                locID: userData.locID,
                admID: patientData.admID
            }
        ]
    };
    $http.post('urlS', this, {
        code: '03100058',
        data: data,
        namespace: 'Y',
        success: function (res) {
            if (+res.errorCode === 0) {
                patientData.statusCode = 'CI';
                Cache.set('patientData', patientData);
            } else {
                Toast(res.errorMessage);
            }
        }
    });
};
/**
 * 获取小程序相关信息
 */
const GetAPPInfo = (callback) => {
    var appID = '';
    if (typeof uni.getAccountInfoSync === 'function') {
        var accountInfo = uni.getAccountInfoSync();
        appID = accountInfo.miniProgram.appId;
    }
    let data = {
        params: [
            {
                appID: appID,
                flag: 'D'
            }
        ]
    };
    $http.post('urlS', this, {
        code: '03100058',
        data: data,
        namespace: 'Y',
        success: function (res) {
            if (+res.errorCode === 0) {
                Cache.set('AppData', res.result);
                if (callback) {
                    callback();
                }
            } else {
                Toast(res.errorMessage);
            }
        }
    });
};
export default {
    allowToJoin,
    initTim,
    loginTim,
    handleSendMessage,
    loginOut,
    clearTimer,
    creatTimer,
    handleSendMessage2
};
