layui.use(["layer", "form", "upload"], function(){
    $ = layui.$;
    form = layui.form;
    layer = layui.layer;
    upload = layui.upload;
    if(localStorage.getItem("token") == null){
        layer.msg("请先登录", {icon: 2}, function (){
            window.location.href="/";
        })
    }

    //默认隐藏
    $(".layui-nav-tree li").hide();
    $(".layui-nav-child dd").hide();

    //禁用鼠标右击
    $(".el-scrollbar__view").bind("contextmenu", (e) => {
        return false;
    });
    $(".char__room-content-menu").bind("contextmenu", (e) => {
        return false;
    });

    //回车发送信息
    $(".chat__room-info-input textarea").keydown(function (e){
        // 当 keyCode 是13时,是回车操作
        if (e.keyCode == 13){
            var textVal = $(".chat__room-info-input textarea").val();
            sendPrivateText(textVal);
            e.preventDefault();
        }
    });
    //聊天框鼠标右击
    $('body').delegate('.chat__room-message-text-wrapper','mousedown', function(e){
        var key = e.which
        if(key == 3){
            clickEven = $(this);//点击当前元素
            //获取右键点击坐标
            var x = e.clientX;
            var y = e.clientY;
            $(".char__room-content-menu").css("transform", "translate3d("+ x +"px, "+ y +"px, 0px)");
            $(".char__room-content-menu").show();
        }
    });
    //点击任意部位隐藏右键
    $(document).click(function(){
        $(".char__room-content-menu").hide();
        clickEven = null;//清空当前元素
    })
    //监听滚动条事件
    $(".chat__room-content-scroll .el-scrollbar__wrap").scroll(function(e){
        var scrollHeight = $(".chat__room-content-scroll .el-scrollbar__wrap").scrollTop();
        if(scrollHeight == 0){
            var uuid = $(".right_el_scrollbar .chat__room-message").eq(0).attr("cid");
            var options = {
                queue: userID, //需特别注意queue属性值为大小写字母混合，以及纯大写字母，会导致拉取漫游为空数组，因此注意将属性值装换为纯小写
                isGroup: false,
                start: uuid,
                count: 10,
                success: function(res){
                    //获取拉取成功的历史消息
                    $.each(res.reverse(), (index, item) => {
                        var time = item.time;
                        if(item.from != username.toLowerCase()){
                            messageLoadOld(item, avatarUrlParty, time);
                        } else {
                            messageLoadOld(item, headImg, time);
                        }
                    });
                },
                fail: function(){}
            }
            conn.fetchHistoryMessages(options);
        }
    })

    $(".chat__room-info-control").on("click", (e) => {
        $("#uploadImg").click();
    });
    //关闭聊天框
    $(".chat__room-info-title svg").on("click", (e) => {
        layer.closeAll();
    });


    const input = document.querySelector("#uploadImg");
    input.addEventListener('change',function(){
        // 通过onchange事件获取files,函数要使用function定义,箭头函数this指向父级作用域
        if(userID == null){
            layer.msg("暂未选择聊天对象", {icon: 2});
            return false;
        }

        let id = conn.getUniqueId();                 // 生成本地消息id
        let msg = new WebIM.message('img', id);      // 创建图片消息

        var input = document.getElementById('uploadImg');  // 选择图片的input
        var fileVal = WebIM.utils.getFileUrl(input);      // 将图片转化为二进制文件
        var allowType = {
            'jpg': true,
            'gif': true,
            'png': true,
            'bmp': true
        };
        var imgUrl = fileVal.url; //用户上传的图片
        if (fileVal.filetype.toLowerCase() in allowType) {
            var option = {
                file: fileVal,
                length: '3000',                       // 视频文件时，单位(ms)
                ext: {
                    file_length: fileVal.data.size       // 文件大小
                },
                to: userID,                       // 接收消息对象
                chatType: 'singleChat',               // 设置为单聊
                onFileUploadError: function () {      // 消息上传失败
                    console.log('onFileUploadError');
                },
                onFileUploadProgress: function (e) { // 上传进度的回调
                    console.log(e)
                },
                onFileUploadComplete: function (e) {   // 消息上传成功
                    console.log('onFileUploadComplete');
                    console.log(e)
                },
                success: function (e) {                // 消息发送成功
                    console.log('Success');
                    console.log(e)
                    $(".right_el_scrollbar").append("<div class=\"chat__room-message chat__room-message-reverse\"\n" +
                        "                                     ><img\n" +
                        "                                        src=\""+ headImg +"\"\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=\""+ imgUrl +"\"\n" +
                        "                                                                   class=\"el-image__inner el-image__preview\"\n" +
                        "                                                                   style=\"object-fit: cover;\"><!--v-if--></div>\n" +
                        "                                        <span>"+ formatNotss(parseInt(Date.parse(new Date()))) +"</span></div>\n" +
                        "                                </div>")
                },
                fail: function(e){
                    console.log("Fail");              //如禁言、拉黑后发送消息会失败
                },
                flashUpload: WebIM.flashUpload
            };
            msg.set(option);
            conn.send(msg.body);
        }

    },false);

    getSupplierUser();
    //语言移入移出
    $('.language').hover(function() {
        // 鼠标移入时添加hover类
        $(".language-selector").show();
     }, function() {
         // 鼠标移出时移出hover类
        $(".language-selector").hide();
     });
    //头像移入移出
    $('.head_portrait_hove').hover(function() {
        // 鼠标移入时添加hover类
        $(".head_hove").show();
    }, function() {
        // 鼠标移出时移出hover类
        $(".head_hove").hide();
    });
    //联系我们
    $(".contact_us").on("click", (e) => {
        userID = "tuya_2";
        $(".chat__room-info-title h4").html("平台客服");
        $(".right_el_scrollbar div").remove();
    });
    translationVal(type);
    getQuotation();
});