<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="viewport"
          content="width=device-width, maximum-scale=1.0, initial-scale=1.0,initial-scale=1.0,user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <title>智能客服</title>

    <link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico?t=1489039620156"/>
    <link rel="stylesheet" type="text/css" href="/im/css/ukefu.css">
    <link rel="stylesheet" id="skin" type="text/css" href="/im/css/default/ukefu.css">

    <!-- kindeditor -->
    <link rel="stylesheet" type="text/css" href="/im/js/kindeditor/themes/default/default.css">

    <script type="text/javascript" src="/js/jquery-1.10.2.min.js"></script>
    <script src="/js/jquery.form.js"></script>

    <script type="text/javascript" src="/im/js/kindeditor/kindeditor.js"></script>
    <script type="text/javascript" src="/im/js/kindeditor/lang/zh-CN.js"></script>
    <style>
        * {
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
            outline: none;
        }
        *:not(input,textarea) {
            -webkit-touch-callout: none;
        }
    </style>

    <script src="/im/js/socket.io.js"></script>
    <script src="/im/js/dayjs.min.js"></script>
    <script type="text/javascript">
        var editor , words , textheight , wordinx = 0 ;

        /**
         * 文本框根据输入内容自适应高度
         * @param                {HTMLElement}        输入框元素
         * @param                {Number}                设置光标与输入框保持的距离(默认0)
         * @param                {Number}                设置最大高度(可选)
         */
        var autoTextarea = function (elem, extra, maxHeight) {
            extra = extra || 0;
            var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
                isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
                addEvent = function (type, callback) {
                    elem.addEventListener ?
                        elem.addEventListener(type, callback, false) :
                        elem.attachEvent('on' + type, callback);
                },
                getStyle = elem.currentStyle ? function (name) {
                    var val = elem.currentStyle[name];

                    if (name === 'height' && val.search(/px/i) !== 1) {
                        var rect = elem.getBoundingClientRect();
                        return rect.bottom - rect.top -
                            parseFloat(getStyle('paddingTop')) -
                            parseFloat(getStyle('paddingBottom')) + 'px';
                    };

                    return val;
                } : function (name) {
                    return getComputedStyle(elem, null)[name];
                },
                minHeight = parseFloat(getStyle('height'));


            elem.style.resize = 'none';

            var textchange = function(){
                changeTextArea(0);
            }

            var change = function () {
                changeTextArea(0);
                wordinx = getPositionForTextArea(document.getElementById('message'));
            };

            addEvent('propertychange', textchange);
            addEvent('input', textchange);
            addEvent('focus', function(){
                changeTextArea(0);
            });
            change();
        };
        //多行文本框
        function getPositionForTextArea(ctrl) {
            var CaretPos = 0;
            if (document.selection) { // IE Support
                ctrl.focus();
                var Sel = document.selection.createRange();
                var Sel2 = Sel.duplicate();
                Sel2.moveToElementText(ctrl);
                var CaretPos = -1;
                while (Sel2.inRange(Sel)) {
                    Sel2.moveStart('character');
                    CaretPos++;
                }
            } else if (ctrl.selectionStart || ctrl.selectionStart == '0') { // Firefox support
                CaretPos = ctrl.selectionStart;
            }
            return (CaretPos);
        }

        function openFaceDialog(){
            if(document.getElementById("faceindex").style.display == "none"){
                document.getElementById("faceindex").style.display= "block";
                document.getElementById("bottom").style.height = $('#message').height()+ 20 + document.getElementById("faceindex").offsetHeight + "px" ;
                document.getElementById("above").style.height = "calc(100% - "+($('#bottom').height())+"px)"
            }else{
                closeFaceDialog(0);
            }
            return false ;
        }

        function closeFaceDialog(height){
            document.getElementById("faceindex").style.display= "none";
            document.getElementById("bottom").style.height = $('#message').height() + height + "px" ;
            document.getElementById("above").style.height = "calc(100% - "+($('#message').height())+"px)" ;
        }

        function changeTextArea(height){
            if(document.getElementById("faceindex").style.display == "none"){
                $('#bottom').height($('#message').height() + height);
                document.getElementById("above").style.height = "calc(100% - "+($('#message').height())+"px)"
            }else{
                $('#bottom').height($('#message').height() + $('#faceindex').height());
                document.getElementById("above").style.height = "calc(100% - "+($('#message').height())+"px)"
            }
        }
        function insertImg(obj){
            if(wordinx >= 0){
                var text = $('#message').val();
                var value = text.substring(0 , wordinx) + "["+obj+"]" + text.substring(wordinx , text.length);
                $('#message').val(value);
                wordinx = wordinx + 2 + obj.length ;
            }
        }
        $(document).ready(function(){
            window.addEventListener('resize', function () {
                if (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA') {
                    window.setTimeout(function () {
                        document.activeElement.scrollIntoViewIfNeeded()
                    }, 0)
                }
            });
            // 在输入框获取焦点, 键盘弹起后, 真的是一行代码

            $(document).on('submit.form.data-api','[data-toggle="ajax-form"]', function ( e ) {
                var formValue = $(e.target) ;
                $(this).ajaxSubmit({
                    url:formValue.attr("action"),
                    success: function(data){

                    },
                    error:function(xhr, type, s){
                        //notification("",false);	//结束
                    }
                });
                return false;
            });
        });
    </script>
    <style>
        .msg-btn {
            border: #4598ee 1px solid;
            padding: 5px;
            margin: 5px;
            min-width: 125px;
            text-align: center;
            display: inline-block;
            background-color: #e6f2ff;
            cursor: default;
        }    

        .msg-list {
            color: #4598ee
        }

        .msg-card {
            display: inline-block;
            color: #000000;
        }

        .msg-crad-right {
            position: relative;
            left: 10px;
            width: 170px;
            height: 60px;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .card-box{
            cursor: default;
            width: 250px;
            height: 72px;
            padding: 6px;
            line-height:20px;
        }
    </style>
    <!-- kindeditor -->
</head>
<body class="ukefu-im-theme" style="width:100%;overflow:hidden;height:100%;max-height:100%;position:fixed;overflow-y: atuo;/* 或者scroll */-webkit-overflow-scrolling: touch;/* 解决ios滑动不流畅问题 */" class="ukefu-point-text">
<div id="header" class="theme${inviteData.consult_dialog_color!''}">
    <img
            src="<#if inviteData?? && inviteData.consult_dialog_logo??>/res/image.html?id=${inviteData.consult_dialog_logo?url}<#else>/images/logo.png</#if>"
            style="height:50px;padding:10px;">

    <div class="ukefu-func-tab">
        <ul>
            <#if models?seq_contains("chatbot") && inviteData.ai && aiid??>
                <#if !exchange?? || exchange == "true">
                <li><a href="/im/index.html?appid=${appid!''}&orgi=${orgi!''}&ai=false<#if aiid??>&aiid=${aiid}</#if><#if client??>&client=${client!''}</#if><#if type??>&type=text</#if><#if skill??>&skill=${skill!''}</#if><#if agent??>&agent=${agent!''}</#if><#if traceid??>&traceid=${traceid}</#if>&userid=${userid!''}&sessionid=${sessionid!''}&t=${.now?long}">人工坐席</a></li>
                </#if>
                <li class="cur"><a href="javascript:void(0)">智能客服</a></li>
            <#else>
                <li class="cur"><a href="javascript:void(0)">智能客服</a></li>
            </#if>
        </ul>
    </div>
</div>
<div id="cooperation" class="ukefu-cooperation" style="display:none;z-index: 100;background-color: #ffffff;position: fixed;left: 0px;width: 100%;top: 0px;top:0px;height: 100%;">
    <div class='ukefu-image-canvas' id='ukefu-image-content' style="margin-top:2px;">
        <img id="ukefu_img_ctx" style="max-width: 100%;max-height: 100%;">
    </div>
    <div class='drawBoard' style="position: absolute;left: 0;top: 0;margin-top:2px;z-index: 998;">
        <canvas id="canvas-borad" class="brushBorad">你的浏览器不支持 canvas 绘图</canvas>
    </div>
    <div style="position: absolute;bottom: 10px;width: 100%;text-align: center;z-index:10000">
        <button id="offcoop-btn" style="border-color:#009688 !important;color:#FFFFFF;display: inline-block;height: 38px;line-height: 38px;padding: 0 18px;background-color: #009688;color: #fff;white-space: nowrap;text-align: center;font-size: 14px;margin-right:10px;border: none;border-radius: 2px;cursor: pointer;opacity: .9;filter: alpha(opacity=90);background-color: #377FED !important;border:1px solid #FFFFFF;" onclick="offCoop();">退出协作</button>
    </div>
</div>
<div class="chat-above" id="above" style="height:calc(100% - 60px);padding-bottom:100px;">
    <div class="clearfix message  welcome">
        <span id="welcome-message">${(inviteData.dialog_message!'欢迎您来咨询！欢迎使用春松客服！如需帮助请联系 info@chatopera.com')?no_esc}</span>
    </div>
    <#if chatMessageList?? && chatMessageList.content??>
    <#list chatMessageList.content?reverse as chatMessage>
    <#if chatMessage.userid?? && userid?? && chatMessage.calltype?? && chatMessage.calltype = "呼入">
    <div class="clearfix chat-block">
        <div class="chat-right">
            <img class="user-img" src="/im/img/user.png" alt="">
            <div class="chat-message">
                <label class="time">${chatMessage.createtime!''}</label> <label
                    class="user">${chatMessage.username!''}</label>
            </div>
            <div class="chatting-right">
                <i class="arrow arrow${inviteData.consult_dialog_color!''}"></i>
                <div
                        class="chat-content theme${inviteData.consult_dialog_color!''}"><#include
                    "/apps/im/media/message.html"></div>
            </div>
        </div>
    </div>
    <#else>
    <div class="clearfix chat-block">
        <div class="chat-left">
            <img class="user-img"
                 src="<#if inviteData?? && inviteData.consult_dialog_headimg??>/res/image.html?id=${inviteData.consult_dialog_headimg?url}<#else>/images/agent.png</#if>"
                 alt="">
            <div class="chat-message">
                <label class="user">${chatMessage.username!''}</label> <label
                    class="time">${chatMessage.createtime!''}</label>
            </div>
            <div class="chatting-left">
                <i class="arrow"></i>
                <div class="chat-content"><#include	"/apps/im/media/message.html"></div>
            </div>
        </div>
    </div>
</#if> </#list> </#if>
</div>

<div class="mobile-chat-bottom" id="bottom">
    <!--<form id="imgForm" action="/im/image/upload.html?userid=${userid!''}&appid=${appid!''}&username=${username!''}&orgi=${orgi!''}" data-toggle="ajax-form"" enctype="multipart/form-data">-->
    <!--<a href="javascript:;" class="imgFile" onclick="closeFaceDialog(0)">-->
        <!--<img src="/im/img/img.png" class="chat-type" style="width:32px;height:32px;">-->
        <!--<input type="file" name="imgFile" id="imgFile" accept="image/*" onChange="$('#imgForm').submit();$(this).val('');">-->
    <!--</a>-->
    <!--</form>-->
    <textarea id="message" name="content" maxlength="<#if inviteData.maxwordsnum gt 0>${inviteData.maxwordsnum}<#else>300</#if>"></textarea>
    <div class="btn-push clearfix" class="tools">
        <img id="facedialog" onclick="return openFaceDialog()" src="/im/img/face.png" style="width:32px;height:32px;"></a>
        <a href="javascript:void(0)" onClick="sendMessage();return false;"><img src="/im/img/send.png" style="width:32px;height:32px;"></a>
    </div>

    <div id="faceindex" style="display:none;height:200px;position: absolute;bottom: 0px;width:100%;overflow-x:auto;">
        <table class="ke-table" cellpadding="0" cellspacing="0" border="0" style="min-width:100%;">
            <tbody>
            <#list 0..4 as row>
            <tr>
                <#list 0..20 as col>
                <td class="ke-cell"><span class="ke-img"><img
                        src="/im/js/kindeditor/plugins/emoticons/images/${row*20 + col}.png"
                        border="0" alt="" onClick="insertImg('${row*20 + col}')"></span></td>
            </#list>
            </tr>
            </#list>
            </tbody>
        </table>
    </div>
</div>
</div>

<script>
    var service_end = false;
    // 调查问卷
    var diaShade = document.getElementById('diaShade');
    var dialogWrap = document.getElementById('dialogWrap');
    function popup(para) {
        diaShade.style.display = para;
        dialogWrap.style.display = para;
    }
    document.getElementById('above').scrollTop = document
        .getElementById('above').scrollHeight; //滚动到 对话内容的 底部
    // 参数连接
    // 参数连接
    var hostname = location.hostname ;
    var protocol = window.location.protocol.replace(/:/g,'');
    var username = encodeURIComponent("${username}");
    var socket = io(protocol + '://'+hostname+':${port}/im/chatbot?userid=${userid!''}&orgi=${orgi!''}&session=${sessionid!''}&appid=${appid!''}&osname=${(osname!'')?url}&browser=${(browser!'')?url}<#if skill??>&skill=${skill}</#if><#if username??>&nickname='+username+'</#if><#if agent??>&agent=${agent}</#if><#if title??>&title=${title?url}</#if><#if traceid??>&url=${url?url}</#if><#if traceid??>&traceid=${traceid}</#if><#if aiid??>&aiid=${aiid}</#if>', {transports: ['websocket', 'polling']});
    socket.on('connect',function(){
        //service.sendRequestMessage();
        //output('<span id="callOutConnect-message">'+ new Date().format("yyyy-MM-dd hh:mm:ss") + ' 开始沟通' +'</span>' , 'message callOutConnect-message');
    })
    socket.on("agentstatus",function(data){
        document.getElementById('connect-message').innerHTML=data.message;
    })
    socket.on("status",function(data){
        output('<span id="connect-message">'+data.message+'</span>' , 'message connect-message');
        if(data.messageType == "end"){
            service_end = true ;
            //editor.readonly();
        }
    })
    socket.on('message', function(data) {
        var chat=document.getElementsByClassName('chatting-left').innerText;
        data.createtime = dayjs(data.createtime).format('YYYY-MM-DD HH:mm:ss');
        chat = data.message;
        if(data.msgtype == "image"){
            chat = "<a href='"+data.message+"&original=true' target='_blank'><img src='"+data.message+"' class='ukefu-media-image'/></a>" ;
        }else if(data.msgtype == "cooperation"){
            chat = "<a href='javascript:void(0)' onclick='acceptInvite(\""+data.message+"\", \""+data.attachmentid+"\")'>您收到一个协作邀请，点击进入协作</a>" ;
        }else if(data.msgtype == "action"){
            //检查访客是否在协作页面上，如果在协作页面上，就开始执行重绘，否则不做处理
            drawCanvasImage(data.attachmentid) ;
        }
        if(data.calltype == "呼入"){
            output('<div class="chat-right"> <img class="user-img" src="/im/img/user.png" alt=""><div class="chat-message"><label class="time">'+data.createtime+'</label><label  class="user">'+data.username+'</label> </div><div class="chatting-right"><i class="arrow arrow${inviteData.consult_dialog_color!''}"></i><div class="chat-content theme${inviteData.consult_dialog_color!''}">'+chat+'</div></div>' , "chat-block");
        }else if(data.calltype == "呼出"){
            if(data.expmsg){
                showExtmsg(data.username, data.createtime,data.message ,data.expmsg);
            }
            else{
                output('<div class="chat-left"> <img class="user-img" src="<#if inviteData?? && inviteData.consult_dialog_headimg??>/res/image.html?id=${inviteData.consult_dialog_headimg?url}<#else>/images/agent.png</#if>" alt=""><div class="chat-message"><label  class="user">'+data.username+'</label><label class="time">'+data.createtime+'</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content">'+chat+'</div></div>' , "chat-block");
            }

        }
    });

    function showExtmsg(username,createtime,message,json) {
        var expmsg = JSON.parse(json);
        
        var type = expmsg[0].type;
        var content;
        if (type == 'button') {
            content = createButton(message,expmsg);
        } else if (type == 'qlist') {
            content = createQList(message,expmsg);
        } else if (type == 'card') {
            content = createCard(message,expmsg);
        }

        var box = $('<div class="chat-left"> <img class="user-img" src="<#if inviteData?? && inviteData.consult_dialog_headimg??>/res/image.html?id=${inviteData.consult_dialog_headimg?url}<#else>/images/agent.png</#if>" alt=""><div class="chat-message"><label  class="user">'+username+'</label><label class="time">'+createtime+'</label> </div><div class="chatting-left"><i class="arrow"></i><div class="chat-content"></div></div>');

        box.find('.chat-content').append(content);

        output(box,'chat-block')
    }

    function createButton(message, data) {
        var element = $('<div><p>' + message + '</p><div class="button-box"></div></div>')
        var list = element.find('.button-box');
        for (let i = 0; i < data.length; i++) {
            var item = data[i];
            var allowClick = true;
            var btn = $('<div class="msg-btn" style="background-color: #e6f2ff !important;">' + item.label + '</div>');
            var regClick = function (key) {
                btn.click(function () {
                    if (allowClick) {
                        allowClick = false;
                        socket.emit('message', {
                            appid: "${appid!''}",
                            userid: "${userid!''}",
                            type: "message",
                            session: "${sessionid!''}",
                            orgi: "${orgi!''}",
                            message: key
                        });
                    }
                });
            }
            regClick(item.text);
            list.append(btn);
        }

        return element;
    }

    function createQList(message,data){
        var element = $('<div><p>' + message + '</p><div class="button-box"></div></div>')
        var list = element.find('.button-box');
        for (let i = 0; i < data.length; i++) {
            var item = data[i];
            var btn = $('<div class="msg-list">' + item.label + '</div>');
            var regClick = function (key) {
                btn.click(function () {
                    socket.emit('message', {
                        appid: "${appid!''}",
                        userid: "${userid!''}",
                        type: "message",
                        session: "${sessionid!''}",
                        orgi: "${orgi!''}",
                        message: key
                    });
                });
            }
            regClick(item.text);
            list.append(btn);
        }

        return element;
    }

    function createCard(message,data){
        let item = data[0];

        let html = '<div class="card-box" style="background-color: #fff !important;"><div class="msg-card" style="background-color: #fff !important;"><img src="' + item.thumbnail + '" style="width: 60px;height: 60px;"></div><div class="msg-card msg-crad-right" style="background-color: #fff !important;"><h4 style="background-color: #fff !important;">' + item.title + '</h4><p style="background-color: #fff !important;">' + item.summary + '</p></div></div>'

        var element = $(html);
        element.click(function(){
            window.open(item.hyperlink);
        })

        return element;
    }

    socket.on('disconnect',function() {
        output('<span id="connect-message">连接坐席失败，在线咨询服务不可用</span>' , 'message connect-message');
    });
    function sendDisconnect(){
        socket.disconnect();
    }
    function acceptInvite(msgid,fileid){
        document.getElementById("cooperation").style.display = "block" ;
        document.getElementById("ukefu_img_ctx").src = "/res/image.html?id="+fileid + "&cooperation=true&original=true";

        $("#ukefu_img_ctx").load(function() {
            var height = document.getElementById("ukefu-image-content").offsetHeight;
            var width = document.getElementById("ukefu-image-content").offsetWidth;
            var canvas = document.getElementById("canvas-borad") ;
            if(canvas.getContext){
                canvas.width = width;
                canvas.height = height;

                drawCanvasImage(fileid) ;
            }

        });
    }
    function drawCanvasImage(fileid){
        var canvas = document.getElementById("canvas-borad") ;

        if (canvas.getContext && document.getElementById("cooperation").style.display == "block") {
            var ctx = canvas.getContext("2d");

            //创建新的图片对象
            var img = new Image();
            //指定图片的URL
            img.src = "/res/image.html?id=" + fileid + "&cooperation=true&original=true";
            //浏览器加载图片完毕后再绘制图片
            img.onload = function() {
                ctx.clearRect(0,0,canvas.width,canvas.height);
                //以Canvas画布上的坐标(10,10)为起始点，绘制图像
                ctx.drawImage(img, 0, 0 , canvas.width,canvas.height);
            };
        }
    }
    function offCoop(){
        document.getElementById("cooperation").style.display = "none" ;
    }
    function sendMessage() {
        var count = document.getElementById('message').value.length;
        if (count > 0 && service_end == false) {
            var message = $("#message").val();
            sendMessageText(message);
            $("#message").val("");
            wordinx = 0;
        } else if (service_end == true) {
            alert("服务器已断开和您的对话");
        }
        closeFaceDialog(0);
    }
    function sendMessageText(message) {
        if (message != "") {
            socket.emit('message', {
                appid : "${appid!''}",
                userid : "${userid!''}",
                username : "${username!''}",
                channel : "webim",
                type : "message",
                contextid : "${sessionid!''}",
                orgi : "${orgi!''}",
                message :  message
            });
        }
    }
    function output(message, clazz) {
        if (clazz == "message connect-message") {
            var messages = document.getElementsByClassName("connect-message");
            for (inx = 0; inx < messages.length;) {
                document.getElementById('above').removeChild(messages[inx]);
                inx++;
            }
        }
        var element = $("<div class='clearfix "+clazz+"'></div>");
        element.append(message);
        $('#above').append(element);
        document.getElementById('above').scrollTop = document.getElementById('above').scrollHeight ;
        //$("#welcome-message").html(document.getElementById('above').scrollHeight);
    }
    function update(id, message) {
        document.getElementById(id).innerHTML = message;
    }
    autoTextarea(document.getElementById("message"));// 调用
    $('#message').click(function() {
        wordinx = getPositionForTextArea(document.getElementById('message'));
        closeFaceDialog(0);
    });

    var message = {
        // text:data.message,
        // picture:function(){

        // }
        // file:function(){

        // }
        // lang:function(){

        // }
        // goods:function(){

        // }
        // POI:function(){

        // }

    }
</script>
</body>
</html>
