//菜单点击监听事件
function clickItem(obj){
    if($(obj).hasClass("layui-nav-itemed")){
        $.each($(".layui-nav-item"), (index, item) => {
            $(item).find("a cite img").attr("src",  "/images/indeHome/" + $(item).attr("title") + ".png");
        });
        $(obj).find("a cite img").attr("src",  "/images/indeHome/" + $(obj).attr("title") + "_click.png");
        //个人信息特殊处理
        if($(obj).find("a cite").text() == "个人信息"){
            iframeClick(obj);
        }
    }else{
        $(obj).find("a cite img").attr("src",  "/images/indeHome/" + $(obj).attr("title") + ".png");
    }
}
//iframe选择
function iframeClick(obj){
    //上一级名称
    var parentName = $(obj).parent().parent().prev().find("cite").text();
    //点击名称
    var thisClickName = $(obj).find("cite").text();
    //路径上参数
    var idVal = $(obj).attr("idVal");
    $(".select_button").removeClass("check_div");
    var flag = false;
    $.each($(".select_button"), (index, item) => {
        if(index > 0){
            if($(item).find("span").html().indexOf(thisClickName) != -1){
                flag = true;
                return false;
            }
        }
    });
    if(flag){
        $(".center_top div[name="+ thisClickName +"]").click();
    } else {
        if(parentName == "报价单"){
            $(".center_top").append("<div onClick='switchMenu(this)' name="+ thisClickName +" src='/page/demandForSingleIndex?idVal="+ idVal +"' class=\"select_button check_div\">\n" +
                "                    <span>"+ thisClickName +"</span>\n" +
                "                    <div class=\"close_button\" onclick='removeThis(this)'><i class=\"layui-icon layui-icon-close\"></i></div>\n" +
                "                </div>");
            $("iframe").attr("src", "/page/demandForSingleIndex?idVal=" + idVal);
        }
        if(thisClickName == "个人信息"){
            $(".center_top").append("<div onClick='switchMenu(this)' name='个人信息' src='/page/personalIndex' class=\"select_button check_div\">\n" +
                "                    <span>"+ thisClickName +"</span>\n" +
                "                    <div class=\"close_button\" onclick='removeThis(this)'><i class=\"layui-icon layui-icon-close\"></i></div>\n" +
                "                </div>");
            $("iframe").attr("src", "/page/personalIndex");
        }
    }


}
//头部菜单切换
function switchMenu(obj){
    $(".select_button").removeClass("check_div");
    $(obj).addClass("check_div")
    var srcVal = $(obj).attr("src");
    $("iframe").attr("src", srcVal);

}
//删除顶部选中菜单
function removeThis(obj){
    window.event.cancelBubble = true;//阻止冒泡
    $(obj).parent().prev().click();
    $(obj).parent().remove();
}
//聊天显示
var clickMessageType = false;
function messageShow(){
    countSum = 0;//消息数量;
    $(".message_num").html(countSum);
    clickMessageType = true;
    layer.open({
        type: 1,
        title: false,
        offset: ["1366px","auto"],
        closeBtn: 2,
        anim: 2,
        shadeClose: true,
        content: $(".van-popup"),
        end: () => {
            clickMessageType = false;
        }
    })
}
//注册并登录环信账号
function registerUser(){
    var options = {
        username: username.toLowerCase(),
        password: '123456',
        nickname: nickname,
        appKey: WebIM.config.appkey,
        success: function () { },
        error: function (err) {
            let errorData = JSON.parse(err.data);
        },
    };
    conn.registerUser(options);

    var options1 = {
        user: username.toLowerCase(),
        pwd: '123456',
        appKey: WebIM.config.appkey
    };
    conn.open(options1);
    //
    setTimeout(function (){
        let options = {
            nickname: nickname,
            avatarurl: headImg,
        }
        //修改用户信息
        conn.updateOwnUserInfo(options);
        //查询列表
        conn.getSessionList().then((res) => {
            console.log(res)
            $(".left_el_scrollbar div").remove();//删除所有记录重新渲染
            $.each(res.data.channel_infos, (index, item) => {
                var dataVal = JSON.parse(item.meta.payload);//最新消息
                var time = item.meta.timestamp;//发送消息时间戳
                var timeVal;//时间选择 如果大于当前时间则显示yyyy-mm-dd 如果相等显示mm:ss
                var userMap = {};
                var fromTo = dataVal.from;
                if(dataVal.from == username.toLowerCase()){
                    fromTo = dataVal.to;
                }
                conn.fetchUserInfoById([fromTo], ['nickname', 'avatarurl']).then((res) => {
                    $.each(res.data, (index, itemVal) => {
                        userMap.nickname = itemVal.nickname;
                        userMap.avatarurl = itemVal.avatarurl;
                    });
                    if(format(time).split("|")[0] == format(Date.parse(new Date())).split("|")[0]){
                        timeVal = format(time).split("|")[1]
                    } else {
                        timeVal = format(time).split("|")[0]
                    }
                    //判断是图片还是文字
                    if(dataVal.bodies[0].type == "txt"){
                        $(".left_el_scrollbar").append("<div id='"+ fromTo +"' 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>"+ timeVal +"</span></p>\n" +
                            "                                        <p title=\""+ dataVal.bodies[0].msg  +"\">"+ dataVal.bodies[0].msg +"</p></div>\n" +
                            "                                </div>");
                    } else {
                        $(".left_el_scrollbar").append("<div id='"+ fromTo +"' 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>"+ timeVal +"</span></p>\n" +
                            "                                        <p title=\"[图片]\">[图片]</p></div>\n" +
                            "                                </div>");
                    }
                });
            });
        })
    },2000);
}
// 单聊发送文本消息
function sendPrivateText(textVal) {
    if(userID == null){
        layer.msg("暂未选择聊天对象", {icon: 2});
        return false;
    }
    let id = conn.getUniqueId();                 // 生成本地消息id
    let msg = new WebIM.message('txt', id);      // 创建文本消息
    msg.set({
        msg: textVal,                         // 消息内容
        to: userID,                          // 接收消息对象（用户id）
        chatType: 'singleChat',              // 设置为单聊
        success: function (id, serverMsgId) {
            $(".right_el_scrollbar").append("<div class=\"chat__room-message chat__room-message-reverse\"\n" +
                "                                     cid=\""+ id +"\"><img\n" +
                "                                        src=\""+ headImg +"\"\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>"+ textVal +"</p>\n" +
                "                                                <p style=\"display: none;\"></p><i class=\"arrow\"></i></div>\n" +
                "                                        </div>\n" +
                "                                        <span>"+ formatNotss(Date.parse(new Date())) +"</span></div><!----></div>")
        },
        fail: function(e){
            console.log("失败");
        }
    });
    conn.send(msg.body);
    $(".chat__room-info-input textarea").val("");
}
//消息切换
function clickMessage(obj){
    conn.mr_cache = [];
    var id = $(obj).attr("id");
    var name = $(obj).attr("name");
    var avatarUrl = $(obj).find("img").attr("src");
    userID = id;
    $(".chat__room-info-title h4").html(name);
    $(".right_el_scrollbar div").remove();
    $(obj).find(".chat__room-session-item-unread").html(0);
    $(obj).find(".chat__room-session-item-unread").hide();
    var options = {
        queue: id, //需特别注意queue属性值为大小写字母混合，以及纯大写字母，会导致拉取漫游为空数组，因此注意将属性值装换为纯小写
        isGroup: false,
        count: 10,
        success: function(res){
            //获取拉取成功的历史消息
            $.each(res, (index, item) => {
                var time = item.time;
                if(item.from != username.toLowerCase()){
                    messageLoad(item, avatarUrl, time);
                } else {
                    messageLoad(item, headImg, time);
                }
            });
        },
        fail: function(){}
    }
    conn.fetchHistoryMessages(options);

    var height = $(".right_el_scrollbar")[0].scrollHeight;
    console.log(height)
    $(".right_el_scrollbar").scrollTop(height);
}

//全屏预览图片
function clickImg(obj){
    var imgUrl = $(obj).attr("src");
    layer.open({
        type: 1,
        title: false,
        area: ['80%', '80%'],
        closeBtn: 2,
        anim: 2,
        content: "<img src='"+ imgUrl +"' width='100%' height='100%'/>"
    })
}
//消息渲染
function messageLoad(item, img, time){
    if(item.contentsType == "TEXT"){
        //判断是否是自己的消息
        if(item.from == username.toLowerCase()){
            $(".right_el_scrollbar").append("<div class=\"chat__room-message chat__room-message-reverse\"\n" +
                "                                     cid=\""+ item.id +"\"><img\n" +
                "                                        src=\""+ img +"\"\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>"+ item.data +"</p>\n" +
                "                                                <p style=\"display: none;\"></p><i class=\"arrow\"></i></div>\n" +
                "                                        </div>\n" +
                "                                        <span>"+ formatNotss(parseInt(time)) +"</span></div><!----></div>")
        } else {
            $(".right_el_scrollbar").append("<div class=\"chat__room-message\"\n" +
                "                                     cid=\""+ item.id +"\"><img\n" +
                "                                        src=\""+ img +"\"\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>"+ item.data +"</p>\n" +
                "                                                <p style=\"display: none;\"></p><i class=\"arrow\"></i></div>\n" +
                "                                        </div>\n" +
                "                                        <span>"+ formatNotss(parseInt(time)) +"</span></div><!----></div>")
        }
    } else {
        //判断是否是自己的消息
        if(item.from == username.toLowerCase()){
            $(".right_el_scrollbar").append("<div class=\"chat__room-message chat__room-message-reverse\"\n" +
                "                                     ><img\n" +
                "                                        src=\""+ img +"\"\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=\""+ item.url +"\"\n" +
                "                                                                   class=\"el-image__inner el-image__preview\"\n" +
                "                                                                   style=\"object-fit: cover;\"><!--v-if--></div>\n" +
                "                                        <span>"+ formatNotss(parseInt(time)) +"</span></div>\n" +
                "                                </div>")
        } else {
            $(".right_el_scrollbar").append("<div class=\"chat__room-message\"\n" +
                "                                     ><img\n" +
                "                                        src=\""+ img +"\"\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=\""+ item.url +"\"\n" +
                "                                                                   class=\"el-image__inner el-image__preview\"\n" +
                "                                                                   style=\"object-fit: cover;\"><!--v-if--></div>\n" +
                "                                        <span>"+ formatNotss(parseInt(time)) +"</span></div>\n" +
                "                                </div>")
        }
    }
}