var conn = null;///创建连接


conn = {};
WebIM.config = config;
conn = WebIM.conn = new WebIM.connection({
    appKey: WebIM.config.appkey,
    isHttpDNS: WebIM.config.isHttpDNS,
    url: WebIM.config.xmppURL,
    apiUrl: WebIM.config.apiURL,
    autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
    delivery: WebIM.config.delivery,
    useOwnUploadFun: WebIM.config.useOwnUploadFun
});

//添加回调函数
conn.listen({
    onOpened: function () {},                  //连接成功回调
    onClosed: function () {},                  //连接关闭回调
    onTextMessage: function (message) {      //收到文本消息
        //判断发送消息者是否为新好友
        var userIDArray = new Array();
        $.each($(".left_el_scrollbar .chat__room-session-item"), (index, ele) => {
            userIDArray.push($(ele).attr("id") + ",");
        });
        userIDArray.push(username.toLowerCase() + ",");
        if(userIDArray.indexOf(message.from + ",") < 0){
            conn.fetchUserInfoById([message.from], ['nickname', 'avatarurl']).then((res) => {
                var userMap = {};
                $.each(res.data, (index, itemVal) => {
                    userMap.nickname = itemVal.nickname;
                    userMap.avatarurl = itemVal.avatarurl;
                });
                $(".left_el_scrollbar").append("<div id='"+ message.from +"' name='"+ userMap.nickname +"' onclick='clickMessage(this)' class=\"chat__room-session-item\"><img\n" +
                    "                                        src=\""+ userMap.avatarurl +"\"\n" +
                    "                                        alt=\""+ userMap.nickname +"头像\"><span class=\"chat__room-session-item-unread\"\n" +
                    "                                                                style=\"display: none;\">0</span>\n" +
                    "                                    <div class=\"chat__room-user\"><p class=\"chat__room-user-title\"><span\n" +
                    "                                            title=\""+ userMap.nickname +"\">"+ userMap.nickname +"</span><span>"+ format(parseInt(message.time)).split("|")[1] +"</span></p>\n" +
                    "                                        <p title=\""+ message.data  +"\">"+ message.data +"</p></div>\n" +
                    "                                </div>");
            });
        }
        if(!clickMessageType){
            countSum++;
            $(".message_num").html(countSum);
            $(".message_num").show();
        }
        var userMap = {};
        if(message.from == userID){
            conn.fetchUserInfoById([message.from], ['nickname', 'avatarurl']).then((res) => {
                $.each(res.data, (index, itemVal) => {
                    userMap.nickname = itemVal.nickname;
                    userMap.avatarurl = itemVal.avatarurl;
                });
                $(".right_el_scrollbar").append("<div class=\"chat__room-message\"\n" +
                    "                                     cid=\""+ message.id +"\"><img\n" +
                    "                                        src=\""+ userMap.avatarurl +"\"\n" +
                    "                                        alt=\"avatar\" class=\"avatar\">\n" +
                    "                                    <div class=\"chat__room-message-text\">\n" +
                    "                                        <div class=\"chat__room-message-text-info\"><!----><!---->\n" +
                    "                                            <div class=\"chat__room-message-text-wrapper\"><p>"+ message.data +"</p>\n" +
                    "                                                <p style=\"display: none;\"></p><i class=\"arrow\"></i></div>\n" +
                    "                                        </div>\n" +
                    "                                        <span>"+ formatNotss(parseInt(message.time)) +"</span></div><!----></div>")
                var height = $(".right_el_scrollbar")[0].scrollHeight;
                $(".chat__room-content-scroll .el-scrollbar__wrap").scrollTop(height);
            })
        }else{
            var numVal = $(".left_el_scrollbar div[id="+ message.from +"]").find(".chat__room-session-item-unread").html();
            $(".left_el_scrollbar div[id="+ message.from +"]").find(".chat__room-session-item-unread").html(parseInt(numVal) + 1);
            $(".left_el_scrollbar div[id="+ message.from +"]").find(".chat__room-session-item-unread").show();
        }
        $(".left_el_scrollbar div[id="+ message.from +"]").find(".chat__room-user-title").next().html(message.data);
        $(".left_el_scrollbar div[id="+ message.from +"]").find(".chat__room-user-title").next().attr("title", message.data);
        $(".left_el_scrollbar div[id="+ message.from +"] .chat__room-user-title").find("span").eq(1).html(format(parseInt(message.time)).split("|")[1]);
    },
    onEmojiMessage: function ( message ) {},   //收到表情消息
    onPictureMessage: function ( message ) {
        //判断发送消息者是否为新好友
        var userIDArray = new Array();
        $.each($(".left_el_scrollbar .chat__room-session-item"), (index, ele) => {
            userIDArray.push($(ele).attr("id") + ",");
        });
        if(userIDArray.indexOf(message.from + ",") < 0){
            conn.fetchUserInfoById([message.from], ['nickname', 'avatarurl']).then((res) => {
                var userMap = {};
                $.each(res.data, (index, itemVal) => {
                    userMap.nickname = itemVal.nickname;
                    userMap.avatarurl = itemVal.avatarurl;
                });
                $(".left_el_scrollbar").append("<div id='"+ message.from +"' name='"+ userMap.nickname +"' onclick='clickMessage(this)' class=\"chat__room-session-item\"><img\n" +
                    "                                        src=\""+ userMap.avatarurl +"\"\n" +
                    "                                        alt=\""+ userMap.nickname +"头像\"><span class=\"chat__room-session-item-unread\"\n" +
                    "                                                                style=\"display: none;\">0</span>\n" +
                    "                                    <div class=\"chat__room-user\"><p class=\"chat__room-user-title\"><span\n" +
                    "                                            title=\""+ userMap.nickname +"\">"+ userMap.nickname +"</span><span>"+ format(parseInt(message.time)).split("|")[1] +"</span></p>\n" +
                    "                                        <p title=\"[图片]\">[图片]</p></div>\n" +
                    "                                </div>");
            })
        }
        if(!clickMessageType){
            countSum++;
            $(".message_num").html(countSum);
        }
        var userMap = {};
        if(message.from == userID){
            conn.fetchUserInfoById([message.from], ['nickname', 'avatarurl']).then((res) => {
                $.each(res.data, (index, itemVal) => {
                    userMap.nickname = itemVal.nickname;
                    userMap.avatarurl = itemVal.avatarurl;
                });
                $(".right_el_scrollbar").append("<div class=\"chat__room-message\"\n" +
                    "                                     cid=\""+ message.id +"\"><img\n" +
                    "                                        src=\""+ userMap.avatarurl +"\"\n" +
                    "                                        alt=\"avatar\" class=\"avatar\"><!---->\n" +
                    "                                    <div class=\"chat__room-message-img\">\n" +
                    "                                        <div class=\"el-image\"><img onclick='clickImg(this)' alt=\"fileImage\"\n" +
                    "                                                                   src=\""+ message.url +"\"\n" +
                    "                                                                   class=\"el-image__inner el-image__preview\"\n" +
                    "                                                                   style=\"object-fit: cover;\"><!--v-if--></div>\n" +
                    "                                        <span>"+ formatNotss(parseInt(message.time)) +"</span></div>\n" +
                    "                                </div>")
            })
        }else{
            var numVal = $(".left_el_scrollbar div[id="+ message.from +"]").find(".chat__room-session-item-unread").html();
            $(".left_el_scrollbar div[id="+ message.from +"]").find(".chat__room-session-item-unread").html(parseInt(numVal) + 1);
            $(".left_el_scrollbar div[id="+ message.from +"]").find(".chat__room-session-item-unread").show();
        }
        var height = $(".right_el_scrollbar")[0].scrollHeight;
        $(".chat__room-content-scroll .el-scrollbar__wrap").scrollTop(height);
        $(".left_el_scrollbar div[id="+ message.from +"]").find(".chat__room-user-title").next().html("[图片]");
        $(".left_el_scrollbar div[id="+ message.from +"]").find(".chat__room-user-title").next().attr("title", message.data);
        $(".left_el_scrollbar div[id="+ message.from +"] .chat__room-user-title").find("span").eq(1).html(format(parseInt(message.time)).split("|")[1]);
    }, //收到图片消息
    onCmdMessage: function ( message ) {},     //收到命令消息
    onAudioMessage: function ( message ) {},   //收到音频消息
    onLocationMessage: function ( message ) {},//收到位置消息
    onFileMessage: function ( message ) {},    //收到文件消息
    onCustomMessage: function ( message ) {},  //收到自定义消息
    onVideoMessage: function (message) {
        var node = document.getElementById('privateVideo');
        var option = {
            url: message.url,
            headers: {
                'Accept': 'audio/mp4'
            },
            onFileDownloadComplete: function (response) {
                var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
                node.src = objectURL;
            },
            onFileDownloadError: function () {
                console.log('File down load error.')
            }
        };
        WebIM.utils.download.call(conn, option);
    },   //收到视频消息
    onPresence: function ( message ) {},       //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
    onRoster: function ( message ) {},         //处理好友申请
    onInviteMessage: function ( message ) {},  //处理群组邀请
    onOnline: function () {},                  //本机网络连接成功
    onOffline: function () {},                 //本机网络掉线
    onError: function ( message ) {},          //失败回调
    onBlacklistUpdate: function (list) {       //黑名单变动
        // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
        console.log(list);
    },
    onRecallMessage: function(message){},      //收到撤回消息回调
    onReceivedMessage: function(message){},    //收到消息送达服务器回执
    onDeliveredMessage: function(message){},   //收到消息送达客户端回执
    onReadMessage: function(message){},        //收到消息已读回执
    onCreateGroup: function(message){},        //创建群组成功回执（需调用createGroupNew）
    onMutedMessage: function(message){},       //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
    onChannelMessage: function(message){}      //收到整个会话已读的回执，在对方发送channel ack时会在这个回调里收到消息
});