/**
 * socket入口脚本文件
 *
 * @author caiaolin
 * @date 2017-05-12
 * @version
 */
import socket from "socket.io";

const socketIO = socket(3300);

// socket.io相关操作
socketIO.on('connection', function(socket) {
    let roomInfo = {};
    console.log("new connection");
    // 加入房间
    socket.on('join', function(data) {
        console.log(data);
        for(let key in data){
            roomInfo[key] = data[key];
            socket.join(data[key]);
        }
    });
    // 数据更改通知
    socket.on('unitFileChangeNotify', function(data) {
        socket.broadcast.to(roomInfo['unitFile']).emit('unitFileChange', data);
        if(data.userID) socket.broadcast.to(data.userID).emit('fileDataChange', data);
    });
    socket.on('feeRateChangeNotify', function(data) {
        socket.broadcast.to(roomInfo['feeRate']).emit('feeRateChange', data);
        if(data.userID) socket.broadcast.to(data.userID).emit('fileDataChange', data);
    });
    socket.on('changeNewRoom', function(data) {
        if(data.projectID){//如果有项目ID，则通知同一个项目在其它地方被打开的页面
            socket.broadcast.to(data.oldRoom).emit('changeFileNotify', data);
            if(data.userID) socket.broadcast.to(data.userID).emit('fileDataChange', data);

        }
        socket.leave(data.oldRoom);
        socket.join(data.newRoom);
        roomInfo[data.name]=data.newRoom;
    });
    socket.on('removeProjectMark', function(data) {
        if(data.projectID && data.userID){
            socket.broadcast.to(data.userID).emit('refreshProjectIcon', data);
        }
    });
    socket.on('multiFileChangeNotify', function(data) {
        console.log(data);
        let projectID = data.projects[0].projectID;
        let userID = data.user_id;
        if(projectID && userID){//通知项目管理页面
            socket.broadcast.to(userID).emit('fileDataChange', {projectID:projectID});
        }
        for(let fileID of data.oldFileIDs){//通知已打开的项目页面
            let messageTitle = data.from == "feeRateFile"?"feeRateChange":"unitFileChange";
            socket.broadcast.to(fileID).emit(messageTitle, data);
        }
    });


    socket.on('disconnect', function () {
        console.log("client disconnect =========="+JSON.stringify(roomInfo));
    });
});
