index.js 12.1 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
/*
    yoho客服 im: 首页
    @author acgpiano
*/

'use strict';

import {
    time
} from './time';
import {
    tip
} from './tip';
import {
    RatingView,
    LeaveMSGView,
    OrderListView
} from './view';

require('../../home/jquery.upload');
var saveImage = require('../../home/save-image');

var socket = require('./socket-chat'),
    socketConf = require('./socket-config'),
    cmEntity = socketConf.conversationMessage;

const chatBox = $('#chat-window'),
    encryptedUid = $('#encrypteduid').val();

const append = (html) => {
    chatBox.append(html);
};


// 聊天调整footer位置
const resizeFooter = () => {
    let bottom = $('#chat-footer').height();

    chatBox.css('bottom', `${bottom}px`);
    chatBox[0].scrollTop = chatBox[0].scrollHeight;
};

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


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

    msgArr: [],

    state: {
        lastMSGTime: ''
    },

    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.leaveMSGView = new LeaveMSGView('#leave-msg');
        this.orderListView = new OrderListView('#order-list');
        this.ratingView = new RatingView('#chat-comment');

        const self = this;

        this.bindEvents();

        cmEntity.encryptedUid = encryptedUid;
        $.ajax({
            type: 'GET',
            url: '/service/userinfo',
        }).then(function(result) {
            // 获取用户信息
            cmEntity.userHead = result.head || cmEntity.userHead;
            self.fetchHistoryMsg(function() {
                self.bootSocket();
            });
        });
    },

    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);
            },
            onOpen: $.noop,
            onClose: $.noop
        };

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

        socket.init(config);
    },

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

        this.$chat
            .on('click.Rating.toggle', '[data-trigger=rating]', function() {
                self.ratingView.toggle();
            })
            .on('click.leaveMSG', '[data-trigger=leave-msg]', function() {
                self.leaveMSGView.trigger('show.LeaveMSGView');
            })
            .on('click.orderList', '[data-trigger=order-list]', function() {
                self.orderListView.trigger('show.OderListView');
            })
            .on('click.chat.switchServer', '[data-action=change-human]', function(){
                self.switchService('human');
            })
            .on('keydown.chat.sendText', '.text-in', function(event) {
                if (event.which === 13) {
                    let content = {
                        data: {
                            content: $.trim(event.target.value)
                        }
                    };

                    self.sendMSG(content);
                }
            });


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

                self.sendMSG(msg);
            });

        window.addEventListener('online', function() {
            self._networkSick(false);
        });

        window.addEventListener('offline', function() {
            self._networkSick(true);
        });

        // TODO
    },

    /**
     *  method: 在聊天窗口上, 画出信息
     *  @param object msg
     *  {
     *      from: str //来源 ["customer", "robot", "employee", "system"]
     *      type: str //消息类型 see swtich msg.type
     *      data: object //消息数据
     *  }
     *
     *  测试数据:
         chat.sendMSG({
             type: 'order',
             data: {
                 data: '123123',
                 imgSrc: '123123123123',
                    orderCode: '123123123123',
                    cost: '123123123123',
                    createTime: '123123123123',
                    orderStatus: '123123123123'
                }
        })
     *
     */
    sendMSG: function(msg) {
        if (!msg || !msg.data) {
            return;
        }
        let data = msg.data;
        let uuid = Date.now();
        let arr;

        msg.type = msg.type || 'text';

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

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


        // TODO 时间

        let $msg = this._drawMSG(msg);

        this.msgArr.push($msg);
        socket.send(JSON.stringify(cmEntity));

        return this;
    },

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

        switch (cm.type) {
            case allTypes.CU_SEND:
                viewData.from = 'customer';
                break;
            case allTypes.CS_SEND:
                viewData.from = 'employee';
                break;
            case allTypes.ROBOT_SEND:
                viewData.from = 'rebot';
                break;

            default:
                return null;
        }

        switch (message.type) {
            case 1:
                viewData.type = msgTypeMap[1];
                viewData.data = {
                    content: message.content
                };

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

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

                break;

            default:
                return null;
        }

        return viewData;
    },

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

        var uuid = rec.uuid;

        switch (recType) {

        }

        return this;
    },

    /**
     *  订单消息
     *  @param 【object|array] viewData 订单消息模版数据
     */
    _drawMSG: function(viewData) {
        let chatWin = this.$chatWin[0];
        let $html = $(this.messageT(viewData));

        $html.appendTo(this.$chatWin);
        chatWin.scrollTop = chatWin.scrollHeight;

        return $html;
    },

    /**
     *  method: 根据网络状态 处理动作
     *  @param {boolean} isSick
     */
    _networkSick: function(isSick) {
        this.$netTip.toggleClass('hide', !isSick);

        return this;
    },

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

        var data = {
            encryptedUid: encryptedUid,
        };

        $.ajax({
            type: 'GET',
            url: '/service/msghistory',
            data: data,
            success: function(result) {
                var arr = [];

                result.forEach(message => {
                    let data = self.buildViewData(message);

                    if (data) {
                        arr.push(data);
                    }
                });

                self._drawMSG(arr);
                cb();
            }
        });
    },

    /**
     *  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>YOHO!客服</span>',
                right: '<span data-trigger="rating">评价</span>'
            },
            link: {
                title: '正在连接...',
                right: ''
            }
        };

        header = header[type];

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

        return this;
    },

    // 刚进入提示
    enterSuccess: function(message) {
        append(time(Date.now()).show());
        append(tip().offLine());
        append(tip(message.content).onLine());
    },

    // 连线人工客服
    linkSuccess: function(type, message) {
        var status = $('.chat-status'),
            name = $('.service-name'),
            comment = $('.chat-comment');

        if (type === 2 || type === 3) {
            status.css('background', '#85be4a');
            name.text('YOHO!客服');
            comment.css('display', 'inline-block');
            append(tip(message.content).onLine());
        } else {
            name.text('YOHO!客服');
        }
    },

    // 用户发消息
    handleCusMsg: function(rec, msgType, message) {
        // 消去状态
    },

    // 客服发消息
    handleCsMsg: function(rec, msgType, message) {
        let cfg = {
            style: 'recevied-msg',
            avatar: cmEntity.userHead,
        };

        if (msgType === 2) {
            cfg.type = 'picture';
            cfg.data = {
                src: message.content,
            };
        } else {
            cfg.type = 'text';
            cfg.data = {
                msg: message.content,
            };
        }
        this._drawMSG(cfg);
        resizeFooter();
    }
};

chat.init();

// 触发菜单
$('.menu-trigger').on('touchend', function() {
    let $menu = $('.menu');

    if ($menu.css('display') === 'none') {
        $menu.show();
        resizeFooter();
    } else {
        $menu.hide();
        resizeFooter();
    }

    $('.upload-img').upload({
        auto: true,
        fileType: 'image/*',
        uploadScript: '/api/upload/image',
        fileObjName: 'filename',
        fileSizeLimit: 5000000,
        height: '100%',
        width: '100%',
        multi: false,
        formData: {
            bucket: 'suggest'
        },
        onUploadComplete: function(file, data) {
            let url;

            data = saveImage.saveImage(data);
            url = data.imgList[0].imgRelUrl + '?imageView2/2/w/640/q/90';
            url = 'http://img11.static.yhbimg.com/suggest' + url;
            sendMsg(2, url);
        }
    });
    $('.uploadifive-button').css('position', 'absolute');
});


// 图片放大
$('#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();
    });
});


window.$ = $;
window.chat = chat;