index.js 7.03 KB
/*
    yoho客服 im: 首页
    @author acgpiano
*/

'use strict';

import { time } from './time';
import { tip } from './tip';
import { Customer, Employee} from './role';
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);
};

let gg, mm;

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

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


var chat = {
    // 初始化websocket
    init: function() {
        const self = this;

        socketConf.conversationMessage.encryptedUid = encryptedUid;
        $.ajax({
            type: 'GET',
            url: '/service/userinfo',
        }).then(function(result) {
            // 获取用户信息
            gg = new Customer(result.head || cmEntity.userHead);
            mm = new Employee(cmEntity.userHead);
            self.fetchHistoryMsg(function() {
                socket.init(Object.assign(socketConf, {
                    onMessage: function(e) {
                        var received = JSON.parse(e.data);
                        console.log(received);
                        cmEntity.conversationId = received.newConversationId > 0 ?
                                received.newConversationId :
                                received.conversationId;

                        self.getMessage(received);
                    }
                }));
            });
        });
    },

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

        var data = {
            encryptedUid: encryptedUid,
        };

        $.ajax({
            type: 'GET',
            url: '/service/msghistory',
            data: data,
            success: function(result) {
                if (result && result.code === 200) {
                    for (let item of result.data) {
                        self.getMessage(item);
                    }
                }
            }
        });
    },
    // 处理收到的消息
    getMessage: function(rec) {
        var recType = rec.type,
            message = rec.message,
            msgType = message.type,
            allTypes = socketConf.recType;

        switch (recType) {

            case allTypes.ENTER:
                this.enterSuccess(message);
                break;

            case allTypes.LINK_SUCCESS:
                this.linkSuccess(msgType, message);
                break;

            case allTypes.CU_SEND:
                this.handleCusMsg(rec, msgType, message);
                break;

            // case allTypes.BREAK_TIME:
            //     breakCountdown(message);
            //     break;

            case allTypes.ROBOT_SEND:
                rec.csName = rec.csName || '客服机器人';
                append(mm.sendMsg(message.content));
                resizeFooter();

                break;

            case allTypes.CS_SEND:
                // 处理客服消息
                this.handleCsMsg(rec, msgType, message);
                break;

            // case allTypes.EVAL_INVITE:
            //     // 客服发起
            //     processInfo.promoter = 2;
            //     showEvalModal();
            //     break;

            // case allTypes.CS_CHATTING:
            //     // 正在人工会话
            //     csChatting(message);
            //     break;

            case allTypes.OFFLINE:
                append(time(Date.now()).show());
                append(tip().offLine());
                break;

            default:
                break;

        }
    },

    // 刚进入提示
    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) {
        if (msgType === 2) {
            append(gg.sendImg(message.content, true));
        } else {
            append(gg.sendMsg(message.content, true));
        }
        resizeFooter();
    },

    // 客服发消息
    handleCsMsg: function(rec, msgType, message) {
        if (msgType === 2) {
            append(mm.sendImg(message.content));
        } else {
            append(mm.sendMsg(message.content));
        }
        resizeFooter();
    }
};

chat.init();

// 用户发送消息
const sendMsg = function(type, content) {
    if (!content) {
        return;
    } else {
        cmEntity.type = 3;
        cmEntity.message.content = content;
        cmEntity.message.type = type || 1;
        socket.send(JSON.stringify(cmEntity));
    }
};

// 聊天区发送信息
$('.text-in').on('keydown', function(e) {
    if (e.keyCode === 13) {
        sendMsg(1, $(this).val());
        $(this).val('');
    }
});

// 触发菜单
$('.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: 999999,
        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-comment').on('touchend', function() {
    let $comment = $('.comment'),
        box = new RatingView($comment);

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

// 留言
let leaveMsg = new LeaveMSGView();

leaveMsg.init();

// 订单
let orderList = new OrderListView();

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