index.js 28.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
/* global gDomains */
/*
    yoho客服 im: 首页
    @author acgpiano
*/

'use strict';

import appBridge from 'yoho-app';
import {time} from './time';
import {api} from './store';
import {RatingView, LeaveMSGView, OrderListView } from './view';
import tip from 'plugin/tip';

let FastClick = require('yoho-fastclick');

FastClick.attach(document.body);

window.requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        function(callback) {
            window.setTimeout(callback, 1000 / 60);
        };
}());

let qs = require('yoho-qs');

let socket = require('./socket-chat'),
    socketConf = require('./socket-config');

let cmEntity = socketConf.conversationMessage;

// 配置
const msgTypeMap = {
    1: 'text',
    2: 'picture',
    10: 'order'
};

let userName = $('#js-uname').val();
let encryptedUid = cmEntity.encryptedUid = $('#js-eid').val() || 0;
let userAvatar = cmEntity.userHead = socketConf.defaultUserHead;

let imgSrc = $('#js-avatar').val();

function checkUserAvatarValid(src, success) {
    let imgDOM = new Image();

    imgDOM.src = src;
    imgDOM.style.display = 'none';

    imgDOM.onload = function() {
        success(src);

        document.body.removeChild(this);
    };

    imgDOM.onerror = function() {
        document.body.removeChild(this);
    };

    document.body.appendChild(imgDOM);
}

// window.checkUserAvatarValid = checkUserAvatarValid;

checkUserAvatarValid(imgSrc, src => {
    userAvatar = cmEntity.userHead = src;
});

let isAndroid = /YohoBuy-android/i.test(navigator.userAgent);


// 历史消息分页
let msgHistory = {
    conversationId: '', // 会话id
    endTime: null,
    curCount: 0,
    totalCount: null
};


cmEntity.userName = userName;

let chat = {
    $chat: null,
    $chatWin: null,
    $netTip: null,

    unFinshMSGs: {}, // 没有发送出去消息
    $ratingView: $('#chat-comment'),
    canEvalute: true,
    canManualService: true,
    canLeaveMSG: false,


    messageT: require('service/chat/msg.hbs'),

    // 初始化websocket
    init: function() {
        this.$chat = $('#chat-main-wrap');
        this.$header = this.$chat.find('.chat-header');
        this.$chatWin = this.$chat.find('#chat-window');
        this.$netTip = this.$chat.find('.connection-failed');
        this.$historyLoader = this.$chat.find('#chat-history-loader');

        // 组件
        this.leaveMSGView = new LeaveMSGView('#leave-msg');
        this.orderListView = new OrderListView('#order-list');
        this.ratingView = new RatingView('#chat-comment', cmEntity);

        const self = this;


        cmEntity.encryptedUid = encryptedUid;

        self.fetchHistoryMsg().always(function() {

            self.$chatWin.append(time(Date.now()).show());
            self.connect();

            if (msgHistory.curCount < msgHistory.totalCount) { // has more history
                self.$historyLoader
                    .show()
                    .on('click', function() {
                        if (self.$historyLoader.hasClass('chat-history-loading')) {
                            return;
                        }

                        self.$historyLoader.toggleClass('chat-history-loading', true);
                        self.fetchHistoryMsg()
                            .done(function(hasMore) {
                                if (!hasMore) {
                                    self.$historyLoader.remove();
                                }
                            })
                            .always(function() {
                                self.$historyLoader.toggleClass('chat-history-loading', false);
                            });
                    });
            }

        });

        this.bindEvents();
    },

    bootSocket: function() {
        const self = this;

        let actions = {
            onMessage: function(event) {
                let received = JSON.parse(event.data);

                console.log('客户端接收到消息:', received);

                // update 会话id
                cmEntity.conversationId = received.newConversationId > 0 ?
                    received.newConversationId : received.conversationId;

                // 处理消息
                self.handleReceiveMSG(received);
            },

            // onClose: function() {
            //     self._sysInfo('连接已断开');
            // },
            onOpen: $.noop,
            sendFailCallback: function() {
                self._sysInfo('<p>连接断开,请尝试<span class="blue">重连</span></p>')
                    .one('click', function() {
                        self.connect();
                    });
            },

        };

        let config = $.extend(socketConf, actions);

        socket.init(config);
    },

    /**
     *  method: 绑定事件
     */
    bindEvents: function() {
        var self = this;

        this.$chat
            .on('click.Rating.toggle', '[data-trigger=rating]', function() {
                if (self.canEvalute) {
                    self.ratingView.toggle();
                } else {
                    tip.show('您已评价,请勿重复评价');
                }
            })
            .on('click.leaveMSG', '[data-trigger=leave-msg]', function() {
                self.canLeaveMSG && self.leaveMSGView.trigger('show.LeaveMSGView');
            })
            .on('click.orderList', '[data-trigger=order-list]', function() {
                let orderType = $(this).data('type') || '';

                self.orderListView.trigger('show.OderListView', [orderType]);
            })
            .on('click.chat.switchServer', '[data-action=change-human]', function() {
                self.canManualService && self.switchService('human');
            })
            .on('focus.chat.sendText', '.text-in', function() {
                self.toggleMenu(false);

                window.requestAnimFrame(() => {
                    $('#chat-footer')[0].scrollIntoView();
                });
            })
            .on('click', '#chat-window', function() {
                self.toggleMenu(false);
            })
            .on('focus', '.text-in', function() {
                self.chatWinScrollToBottom();

                return false;
            })
            .on('keydown.chat.sendText', '.text-in', function(event) {
                event.stopPropagation();

                window.requestAnimFrame(() => {
                    $('#chat-footer')[0].scrollIntoView();
                });

                if (event.which === 13) {
                    let val = $.trim(event.target.value);

                    if (!val) {
                        return;
                    }

                    let content = {
                        avatar: userAvatar,
                        data: {
                            content: val
                        }
                    };

                    self.sendMSG(content);
                    event.target.value = '';
                }
            });

        this.orderListView
            .on('selectOrder.OrderListView', function(event, data) {
                let msg = {
                    type: 'order',
                    data,
                    style: 'send-msg',
                };

                self.sendMSG(msg);
                self.$chatWin[0].scrollTop = self.$chatWin[0].scrollHeight;
            });

        this.leaveMSGView
            .on('save.LeaveMSGView', function(event, data) {
                self._sysInfo(data);
            });

        this.$ratingView.on('click', '.submit', function() {
            self.ratingView.post({
                encryptedUid,
                conversationId: cmEntity.conversationId,
            });
        }).on('rating-success', function(e, data) {
            self._sysInfo(`您对我们的服务评价为:${data}`);
            self.canEvalute = false;
            cmEntity.type = socketConf.recType.EVALUTE_SUCCESS;
            socket.send(JSON.stringify(cmEntity));

            // resizeFooter();
        });




        window.addEventListener('online', function() {
            self.$netTip.toggleClass('hide', true);
            self.connect();
        });

        window.addEventListener('offline', function() {
            self.$chat.toggleClass('online', false);
            self.$netTip.toggleClass('hide', false);
            self.toggleMenu(false);

            // self.disconnect();
        });


        // app 不支持打开链接
        if (isAndroid || appBridge.isApp) {
            this.$chatWin.on('click', '.link', function(event) {
                event.preventDefault();

                // tip.show('抱歉,暂不支持,长按复制到手机浏览器打开');

                return false;
            });
        }
    },

    /**
     *  当连接时
     */
    connect() {
        cmEntity.type = 1;
        this.bootSocket();
        this.canEvalute = true;

        this.switchService('rebot');
    },

    /**
     * 当断开时
     */
    disconnect(content) {
        var self = this;

        this.canLeaveMSG = true;

        this.$chat.toggleClass('online', false);
        this.toggleMenu(false);
        this._sysInfo(`<p>${content}<span class="blue">连接客服</span></p>`)
            .one('click', function() {
                self.connect();
            });
    },

    /**
     *  method: 在聊天窗口上, 画出信息
     *  @param object msg
     *  {
     *      from: str //来源 ["customer", "robot", "employee", "system"]
     *      type: str //消息类型 see swtich msg.type
     *      data: object //消息数据
     *  }
     *
     *  @param {boolean} noDraw 默认false  渲染并发送
     *
     *  @return {jquery}  $elem
     *
     */
    sendMSG: function(msg, noDraw = false) {
        const self = this;

        if (!msg || !msg.data) {
            return;
        }
        let data = msg.data;
        let uuid = Date.now();
        let arr;

        msg.type = msg.type || 'text';
        msg.from = msg.from || 'customer';
        data.avatar = userAvatar;

        msg.uuid = uuid;
        cmEntity.userHead = msg.avatar = userAvatar;
        cmEntity.uuid = uuid;
        cmEntity.type = socketConf.recType.CU_SEND;

        switch (msg.type) {
            case 'order':
                arr = [
                    '单号:', data.orderCode,
                    '金额: ', data.cost,
                    '下单时间: ', data.createTime,
                    '状态: ', data.orderStatus
                ];


                cmEntity.chatMessage.type = 10;
                cmEntity.chatMessage.content = arr;
                break;
            case 'picture':
                cmEntity.chatMessage.type = 2;
                cmEntity.chatMessage.content = data.content;
                break;
            case 'text':
            default:
                cmEntity.chatMessage.type = 1;
                cmEntity.chatMessage.content = data.content;
        }

        if (!noDraw) {
            let $msg = this._drawMSG(msg);

            self.wrapMSG(cmEntity, $msg)
                .trigger('send.sendEvent');
        } else {
            socket.send(JSON.stringify(cmEntity));
        }
        return this;
    },

    /**
     *  消息发送的生命周期
     *  1. send  Event
     *  2. sucess Event
     *  3. fail Event
     *  @param {object} entity
     *  @param {jquery} $msg
     *  @param {function} sendAction
     *  @return $msg
     */
    wrapMSG(entity, $msg, sendAction) { // eslint-disable-line
        var self = this;

        let uuid = entity.uuid;
        let msgStr = JSON.stringify(entity);

        this.unFinshMSGs[uuid] = $msg;

        $msg.data('msg', msgStr);

        $msg
            .on('fail.sendEvent', function() {
                $msg.removeClass('send-loading')
                    .addClass('send-fail')
                    .one('click', () => {
                        $msg.trigger('send.sendEvent');
                    });
            })
            .on('success.sendEvent', function(event, rec) {
                clearTimeout($msg.data('timeoutId'));
                if (rec.type === 1) {
                    $msg.find('.msg-content').html(rec.chatMessage.newContent);
                }
                $msg.removeClass('send-loading send-fail')
                    .off('sendEvent')
                    .removeData();

            })
            .on('send.sendEvent', function() {
                if (navigator.onLine) {
                    $msg.removeClass('send-fail')
                        .addClass('send-loading');

                    $msg.data('timeoutId', setTimeout(() => {
                        if (self.unFinshMSGs[uuid]) {
                            $msg.trigger('fail.sendEvent');
                        }
                    }, 5000));

                    socket.send($msg.data('msg'));
                } else {
                    $msg.trigger('fail.sendEvent');
                }
            });

        return $msg;
    },

    /**
     *  处理 conversationMessage, 生成 渲染用的数据
     */
    buildViewData: function(cm) {
        var viewData = {};
        var chatMessage = cm.chatMessage;
        var allTypes = socketConf.recType;

        // 设置默认用户头像
        cm.userHead = userAvatar;

        switch (cm.type) {
            case allTypes.CU_SEND:
                viewData.from = 'customer';
                viewData.avatar = cm.userHead;
                break;
            case allTypes.CS_SEND:
                viewData.from = 'employee';
                viewData.avatar = cm.csHead || socketConf.employeHead;
                break;
            case allTypes.ROBOT_SEND:
                viewData.from = 'rebot';
                viewData.avatar = socketConf.rebotUserHead;
                break;

            default:
                return null;
        }

        function emojiHanlder(content) {
            let $div = $('<div></div>').html(content);

            $div.find('img[yohotype=emo]')
                .attr('src', function(i, val) {
                    return window.STATIC_RESOURCE_PATH + '/img/service/emoji/' + val;
                });

            return $div.html();
        }

        switch (chatMessage.type) {
            case 1:
                viewData.type = msgTypeMap[1];
                viewData.data = {
                    content: emojiHanlder(chatMessage.newContent) || chatMessage.content
                };

                break;
            case 2:
                viewData.type = msgTypeMap[2];
                viewData.data = {
                    content: chatMessage.content
                };

                break;
            case 10:
                chatMessage.content = JSON.parse(chatMessage.content);

                viewData.type = msgTypeMap[10];
                viewData.data = {
                    orderCode: chatMessage.content[1],
                    cost: chatMessage.content[3],
                    createTime: chatMessage.content[5],
                    orderStatus: chatMessage.content[7],
                };

                break;

            default:
                return null;
        }

        return viewData;
    },

    /**
     *  处理 接收到的信息
     */
    handleReceiveMSG: function(rec) {
        var recType = rec.type,
            chatMessage = rec.chatMessage,
            msgType = chatMessage.type,
            allTypes = socketConf.recType,
            uuid = rec.uuid;

        if (this.unFinshMSGs[uuid]) {
            let $msg = this.unFinshMSGs[uuid];

            $msg.trigger('success.sendEvent', rec);
        }

        // var uuid = rec.uuid;
        let viewData;

        this.canManualService = true;
        this.canLeaveMSG = false;

        // 服务状态: 离线
        if (
            recType === allTypes.OFFLINE ||
            recType === allTypes.OP_LEAVE ||
            (recType === allTypes.MANUAL_SERVICE && msgType === 0)
        ) {
            this.$chat.toggleClass('online', false);
        }

        switch (recType) {

            // 客服消息
            case allTypes.CS_SEND:
            case allTypes.ROBOT_SEND:
                viewData = this.buildViewData(rec);
                viewData && this._drawMSG(viewData);
                break;

            // 系统消息
            // ------------------------------------------
            // 用户进入
            case allTypes.ENTER:
                chatMessage.newContent && this._sysInfo(chatMessage.newContent);
                break;

            case allTypes.CS_CHATTING:
                if (chatMessage.type === 5) { //  重复登陆
                    this.canManualService = false;
                    this._sysInfo(chatMessage.newContent);
                }
                break;

            case allTypes.BREAK_TIME:
                this._sysInfo(chatMessage.content);
                break;

            // 客服邀请评价
            case allTypes.EVAL_INVITE:
                this._sysInfo('<p data-trigger="rating">请对我们的服务进行<span class="blue">评价</span></p>');
                this.ratingView.toggle(true);
                break;

            // 客服进入
            case allTypes.CS_ENTER:
                this.$chat.toggleClass('online', true);
                this._sysInfo('客服小YO正在为您服务');
                break;
            case allTypes.OP_LEAVE:
            case allTypes.OFFLINE:
                this.disconnect(chatMessage.content);
                break;
            case allTypes.TRANSFER:
                break;
            case allTypes.MANUAL_SERVICE:
                this._manualState(chatMessage.type, rec);
                break;
            case allTypes.IN_QUNEUE:
                this._sysInfo(chatMessage.content);
                break;
            case allTypes.CS_CHANGE_STATE:
                if (msgType === 5) { // 重复登陆
                    this._sysInfo(chatMessage.content);
                }
                break;
            default: break;
        }

        return this;
    },

    // -------------------------------------消息状态 处理------------------------------------------------
    _disconnectState(state, cmEntity) { // eslint-disable-line

    },

    /**
     *  cmEntity.type = 2, 处理人工客服消息
     *  @param {int} state cmEntity.message.type
     *  @param {object} cmEntity cmEntity
     */
    _manualState(state, cmEntity) { // eslint-disable-line
        const self = this;
        const $chatHeader = self.$header;
        const $chat = self.$chat;
        const sysInfo = self._sysInfo.bind(this);
        const chatMessage = cmEntity.chatMessage;


        function noService() {
            $chatHeader.find('.js-service-txt').text('YOHO客服');
            $chat.append(time(Date.now()).show());
        }

        // state: 0 没有人工客服
        function noEmploye() {
            $chatHeader.find('.js-service-txt').text('YOHO客服');

            $chat.append(time(Date.now()).show());
            sysInfo(`${chatMessage.content || ''}您可以选择<span class="blue" data-trigger="leave-msg">留言</span>`);
        }

        // state 1: 排队中
        function inQueue() {
            let info = `${chatMessage.content}您可以<span class="blue" data-trigger="leave-msg">留言</span>`;

            // let info = '您可以选择<span class="blue" data-trigger="leave-msg">留言</span>,客服会以短信形式回复您';

            self.canLeaveMSG = true;

            sysInfo(info);
        }

        // state 2: 人工客服进入
        function linkSuccess() {
            $chatHeader.find('.js-service-txt').text('YOHO客服');

            $chat
                .toggleClass('online', true)
                .append(time(Date.now()).show());

            sysInfo(chatMessage.content);
        }

        switch (state) {
            case 0: noEmploye(); break;
            case 1: inQueue(); break;
            case 2:
            case 3:
                linkSuccess(); break;
            default: noService(); break;
        }
    },

    // -------------------------------------消息状态 处理 end------------------------------------------------

    /**
     *  对话消息
     *  @param 【object|array] viewData 订单消息模版数据
     *  @param {function} cusAction 自定义处理函数
     *    function ($html) {
     *      // $html 模版渲染出来的jquery
     *      // this ----> chat
     *    }
     */
    _drawMSG: function(viewData, cusAction = null) {
        let chatWin = this.$chatWin[0];

        if (viewData.type === 'picture') {
            viewData.data.content = viewData.data.content.replace(/^http:/, '');
        }

        // console.log(viewData);
        let $html = $(this.messageT(viewData));


        this.checkTime();
        if (cusAction) {
            cusAction.apply(this, [$html]);
        } else {
            $html.appendTo(this.$chatWin);
            chatWin.scrollTop = chatWin.scrollHeight;
        }

        return $html;
    },

    /**
     *   系统消息
     */
    _sysInfo: function(msg) {

        let $chatWin = this.$chatWin;
        let chatWin = $chatWin[0];

        if (msg) {
            msg = `<div class="sysinfo change-mm">
                    <div class="leave-msg">${msg}</div>
                </div>`;
        } else {
            msg = `<div class="sysinfo leave-msg-wraper">
                    <div class="leave-msg">您可以选择<a href="javascript:;" data-trigger="leave-msg">留言</a>,客服会以短信形式回复您</div>
                </div>`;
        }

        let $msg = $(msg);

        this.checkTime();
        $msg.appendTo($chatWin);

        chatWin.scrollTop = chatWin.scrollHeight;

        return $msg;
    },

    checkTime: $.noop,

    // 获取10条历史记录
    fetchHistoryMsg: function() {
        const self = this;

        if (msgHistory.totalCount !== null && msgHistory.curCount >= msgHistory.totalCount) {
            return $.Deferred().resolve(false); // eslint-disable-line
        }

        return api.msghistory(encryptedUid, msgHistory.endTime)
            .done(function(result) {
                if (!result || result.code !== 200 || !result.data) {
                    return false;
                }

                result = result.data;
                msgHistory.totalCount = result.totalCount;

                let records = result.records || [];


                // records.reverse();
                let oldFister = self.$chatWin.find('.msg-wrap:first')[0];
                let grap = oldFister ? oldFister.offsetTop : 0;
                let $docFragment = $(document.createDocumentFragment());

                records.forEach((chatMessage, index) => {
                    let nextChat = records[index + 1];
                    let data = self.buildViewData(chatMessage); //eslint-disable-line

                    if (data) {
                        let conversationId = chatMessage.conversationId;
                        let timstamp = Math.ceil(chatMessage.sendTime / 1000); // 原来是微妙 转换成毫秒
                        let $html = self._drawMSG(data);

                        $docFragment.prepend($html);

                        if (index === 0 && !msgHistory.conversationId) {
                            msgHistory.conversationId = conversationId;
                        }

                        if (
                            nextChat &&
                            (nextChat.conversationId !== msgHistory.conversationId)
                        ) {
                            $docFragment.prepend(time(timstamp).show());
                            msgHistory.conversationId = nextChat.conversationId;
                        }

                    }
                });

                self.$historyLoader.after($docFragment);

                oldFister && self.$chatWin.scrollTop(oldFister.offsetTop - grap);




                if (records.length) {
                    msgHistory.endTime = records[records.length - 1].sendTime;
                    msgHistory.curCount += records.length;
                }

                return msgHistory.curCount < msgHistory.total;
            })
            .fail($.noop);
    },

    switchService: function(type) {
        this.renderHeader(type);

        if (type === 'human') {
            cmEntity.type = socketConf.recType.MANUAL_SERVICE;
            socket.send(JSON.stringify(cmEntity));

            // this._sysInfo();
        } else {

            // todo;
        }
    },

    /**
     *  method: 渲染头部
     *  @param {string} type ["robot", "human"]
     */
    renderHeader: function(type) {
        var header = {
            rebot: {
                title: '智能小YO',
                right: '<span data-action="change-human">人工客服</span>'
            },
            human: {
                title: '<i class="chat-status"></i><span class="js-service-txt">正在连接...</span>',
                right: '<span class="chat-rating-trigger" data-trigger="rating">评价</span>'
            }
        };

        header = header[type];

        this.$header
            .find('.title').html(header.title).end()
            .find('.header-right').html(header.right);

        return this;
    },

    toggleMenu: function(willShow) {
        if (willShow === void 0) {
            willShow = !this.$chat.hasClass('menu-open');
        }
        this.$chat.toggleClass('menu-open', willShow);

        this.chatWinScrollToBottom();

        // let chatWin = this.$chatWin[0];
        // let footerH = $('#chat-footer .menu').outerHeight() || 0;

        // if (willShow) {
        //     chatWin.scrollTop += footerH;
        // } else {
        //     chatWin.scrollTop -= footerH;
        // }
    },

    chatWinScrollToBottom: function() {
        let chatWin = chat.$chatWin[0];


        window.requestAnimationFrame(() => {
            chatWin.scrollTop = chatWin.scrollHeight;
        });
    }

};

chat.init();

// 触发菜单
$('.menu-trigger').on('click', function() {
    chat.toggleMenu();

    // let $menu = $('.menu');

    // $menu.toggle();
    // resizeFooter();
});

let $upload = $('.upload-img');

$upload.on('change', function() {
    var input = event.target;
    var files = input.files;
    var formData = new FormData();

    if (!files[0]) {
        return;
    }

    formData.append('files[]', files[0]);


    let msg = {
        type: 'picture',
        from: 'customer',
        avatar: userAvatar,
        data: {
            content: ''
        }
    };
    let $elem = chat._drawMSG(msg);


    let _action = function() {
        $elem.removeClass('send-fail').addClass('send-loading');
        $.ajax({
            type: 'POST',
            url: `${gDomains.imCs}/fileManage/uploadFile`,
            data: formData,
            processData: false,  // 告诉jQuery不要去处理发送的数据
            contentType: false
        })
        .done(function(res) {
            if (res.code === 200) {
                $elem.removeClass('send-loading')
                    .find('.chat-image').attr('src', res.data.filePath)
                    .on('load', function() {
                        chat.chatWinScrollToBottom();
                    });
                msg.data.content = res.data.filePath;
                chat.sendMSG(msg, true); // only send msg, no draw msg;
            }
        })
        .fail(function() {
            chat._sysInfo('图片上传失败,请稍后再试');
            $elem
                .removeClass('send-loading')
                .addClass('send-fail')
                .one('click', _action);
        })
        .always(function() {
            input.value = '';

            chat.chatWinScrollToBottom();
        });
    };

    _action();
});


// 图片放大
$('#chat-window').on('click', '.chat-image', function() {
    let img = $(this),
        fake = $('.fake-img-wrap');

    fake.find('img').attr('src', img.attr('src'));
    fake.fadeIn();

    fake.on('click', function() {
        fake.fadeOut();
    });
});


function tellAppSuccess() {
    window.setTimeout(() => {
        appBridge.invokeMethod('im.page_success', {url: location.href});
    }, 1000);

    window.addEventListener('pageshow', tellAppSuccess);
}


function setChannelColor(channel) {
    var dict = {
        1: 'boys',
        2: 'girls',
        3: 'kids',
        4: 'lifestyle'
    };

    $(document.body)
        .removeClass('boys girls kids lifestyle')
        .addClass(dict[channel]);
}

if (appBridge.isApp && /YohoBuy-iOS/i.test(navigator.userAgent)) {
    document.body.classList.add('app-ios');
}

if (isAndroid) {

    $('#js-back').removeAttr('href').on('click', function(e) {
        e.preventDefault();
        window.im.goBack();
    });

    setChannelColor(qs.yh_channel);
} else if (appBridge.isApp) {
    $('#js-back').removeAttr('href').on('click', function(e) {
        e.preventDefault();
        appBridge.invokeMethod('go.back', {});
    });

    tellAppSuccess();
    setChannelColor(qs.yh_channel);
}




window.channelChanged = function(channel) {
    setChannelColor(channel);
};


window.$ = $;
window.chat = chat;
window.cmEntity = cmEntity;
window.time = time;