//菜单点击监听事件
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("titleVal") + ".png");
        });
        $(obj).find("a cite img").attr("src",  "/images/indeHome/" + $(obj).attr("titleVal") + "_click.png");
        //个人信息特殊处理
        if($(obj).find("a cite").attr("name") == "账户信息"){
            $(".layui-nav-child dd").removeClass("layui-this");
            iframeClick(obj);
        }else if($(obj).find("a cite").attr("name") == "路线发布"){//路线发布特殊处理
            $(".layui-nav-child dd").removeClass("layui-this");
            iframeClick(obj);
        }
    }else{
        $(obj).find("a cite img").attr("src",  "/images/indeHome/" + $(obj).attr("titleVal") + ".png");
    }
}
//iframe选择
function iframeClick(obj){
    //上一级名称
    var parentName = $(obj).parent().parent().prev().find("cite").attr("name");
    //点击名称
    var thisClickName = $(obj).find("cite").attr("name");
    //点击名称防止翻译无效
    var thisName = $(obj).find("cite").text();
    //路径上参数
    var idVal = $(obj).attr("idVal");
    //翻译字段
    var locale = $(obj).attr("locale");
    $(".select_button").removeClass("check_div");
    var flag = false;
    $.each($(".select_button"), (index, item) => {
        if(index > 0){
            if($(item).attr("name").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 data-locale=\""+ locale +"\">"+ thisName +"</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 data-locale=\""+ locale +"\">"+ thisName +"</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");
        }
        if(thisClickName == "路线发布"){
            $(".center_top").append("<div onClick='switchMenu(this)' name='路线发布' src='/page/releaseIndex' class=\"select_button check_div\">\n" +
                "                    <span data-locale=\""+ locale +"\">"+ thisName +"</span>\n" +
                "                    <div class=\"close_button\" onclick='removeThis(this)'><i class=\"layui-icon layui-icon-close\"></i></div>\n" +
                "                </div>");
            $("iframe").attr("src", "/page/releaseIndex");
        }
        if(parentName == "退款申请"){
            $(".center_top").append("<div onClick='switchMenu(this)' name="+ thisClickName +" src='/page/refundIndex?idVal="+ idVal +"' class=\"select_button check_div\">\n" +
                "                    <span data-locale=\""+ locale +"\">"+ thisName +"</span>\n" +
                "                    <div class=\"close_button\" onclick='removeThis(this)'><i class=\"layui-icon layui-icon-close\"></i></div>\n" +
                "                </div>");
            $("iframe").attr("src", "/page/refundIndex?idVal=" + idVal);
        }
    }


}
//头部菜单切换
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;//阻止冒泡
    var name = $(obj).parent().attr("name");//当前模块名称
    var prevName = $(obj).parent().prev().attr("name");//上一个模块名称
    if(prevName == "首页"){
        $(obj).parent().prev().click();
    }
    // $(".iframe_div").find("iframe").attr("src", "");
    $(obj).parent().remove();

    $.each($(".layui-nav-tree li"), function(index, item){
        //自动关闭第一级
        let eleName = $(item).attr("name");
        //点击上一个模块
        if(eleName == prevName){
            $(item).click();
        }
        if(eleName == name){
            //删除选中状态
            $(item).removeClass("layui-nav-itemed");
            $(item).find("cite img").attr("src", "/images/indeHome/" + $(item).attr("title") + ".png");
            return false;
        }
        //如果不是第一级那进入第二级
        $.each($(item).find("dl dd"), (index, ele) => {
            let eleVal = $(ele).find("cite").html();
            //点击上一个模块
            if(eleVal == prevName){
                $(ele).find("a").click();
            }
            //删除选中状态
            if(eleVal == name){
                $(ele).removeClass("layui-this");
                return false;
            }
        });
    });
}
//聊天显示
var clickMessageType = false;
function messageShow(){
    countSum = 0;//消息数量;
    $(".message_num").html(countSum);
    $(".message_num").hide();
    clickMessageType = true;
    layer.open({
        type: 1,
        title: false,
        offset: ["1366px","auto"],
        closeBtn: 2,
        anim: 2,
        shadeClose: true,
        content: $(".van-popup"),
        end: () => {
            clickMessageType = false;
        }
    })
    var height = $(".right_el_scrollbar")[0].scrollHeight;
    $(".chat__room-content-scroll .el-scrollbar__wrap").scrollTop(height);
}
//注册并登录环信账号
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) => {
            $(".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>")
            var height = $(".right_el_scrollbar")[0].scrollHeight;
            $("#" + userID).find(".chat__room-user p").eq(1).html(textVal);
            $("#" + userID).find(".chat__room-user p").eq(1).attr("title", textVal);
            $("#" + userID).find(".chat__room-user-title span").eq(1).html(formatNotss(Date.parse(new Date())).split(" ")[1].substring(0, 5));
            $(".chat__room-content-scroll .el-scrollbar__wrap").scrollTop(height);
        },
        fail: function(e){
            console.log("失败");
        }
    });
    conn.send(msg.body);
    $(".chat__room-info-input textarea").val("");
}
//消息切换
function clickMessage(obj){
    var id = $(obj).attr("id");
    console.log(id)
    var name = $(obj).attr("name");
    avatarUrlParty = $(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();
    conn.mr_cache = [];
    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, avatarUrlParty, time);
                } else {
                    messageLoad(item, headImg, time);
                }
                var height = $(".right_el_scrollbar")[0].scrollHeight;
                $(".chat__room-content-scroll .el-scrollbar__wrap").scrollTop(height);
            });
        },
        fail: function(){}
    }
    conn.fetchHistoryMessages(options);

    var height = $(".right_el_scrollbar")[0].scrollHeight;
    $(".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>")
        }
    }
}

function messageLoadOld(item, img, time){
    if(item.contentsType == "TEXT"){
        //判断是否是自己的消息
        if(item.from == username.toLowerCase()){
            $(".right_el_scrollbar .char__room-content-menu").after("<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 .char__room-content-menu").after("<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 .char__room-content-menu").after("<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 .char__room-content-menu").after("<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>")
        }
    }
}
//翻译
function translation(){

}
//复制
function copyVal(){
    var value = clickEven.text().trim();
    var clipboard = new Clipboard('.copy_li', {
        text: function() {
            return value;
        }
    });
    clipboard.on('success', function(e) {
        // alert("复制成功");
    });
    clipboard.on('error', function(e) {
        // alert(e);
    });
}
//查询供应商内容
function getSupplierUser(){
    $.ajax({
        url: "/personal/getPresonalMessage",
        type: "get",
        data: {},
        headers: {"token": localStorage.getItem("token")},
        dataType: "json",
        success: (data) => {
            if(data.msg == "200"){
                username = data.data.code;
                nickname = data.data.name;
                headImg = data.data.headpir;
                $(".head_portrait").attr("src", headImg);
                $(".user_font").html("Hi，" + nickname);
                registerUser();//登录即时通讯
            }
            layer.closeAll("loading");
        },
        error: () => {
            layer.alert(paramReturn("服务器异常，请联系管理员", parent.type), {icon: 2});
            layer.closeAll("loading");
        }
    });
}
//聊天搜索框
function getValue(obj){
    var sessionSearch = $(obj).val();
    $(".left_el_scrollbar .chat__room-session-item").hide().filter(":contains("+ sessionSearch.trim() +")").show();
}
//语言选择
function languageSelese(obj){
    var name = $(obj).attr("name");
    var typeVal = $(obj).attr("type");
    type = typeVal;
    translationVal(typeVal);
    $(".iframe_div").find("iframe")[0].contentWindow.translationVal(typeVal)
    $(".language").find("p").html(name);
}
//头像悬浮
function clickHeadHove(obj){
    var name = $(obj).text();
    if(name == "退出"){
        localStorage.clear(); //清空缓存
        conn.close();
        window.location.href="/page/Login";
    } else {
        $(".layui-nav-item").eq(3).addClass("layui-nav-itemed");
        $(".layui-nav-item").eq(3).click();
    }
}