'use strict';

/**
 *
 *
 * @author Mai
 * @date
 * @version
 */

window.onload = function() {
    // init
    const socket = io('/lib', {

        // 实际使用中可以在这里传递参数
        query: {
            room: 'lib',
            userId: `client_${Math.random()}`,
        },

        transports: ['websocket']
    });

    socket.on('connect', () => {
        const id = socket.id;

        console.log('#connect,', id, socket);

        // 监听自身 id 以实现 p2p 通讯
        socket.on(id, msg => {
            console.log('#receive,', msg);
        });
    });

    socket.on('refreshed', msg => {
        if (msg.success) {
            $('tr[lib_id="' + msg.id + '"]').removeClass('table-active');
            toastr.success('造价文件"' + msg.filename + '"刷新完成');
        } else {
            $('tr[lib_id="' + msg.id + '"]').find('td:first').append('<a class="fa fa-refresh text-primary" href="/lib/refresh?id=' + msg.id + '" title="再次刷新"></a>');
            toastr.error('造价文件"' + msg.filename + '"刷新失败，请重试');
        }

        if (msg.count === 0) {
            $('#refresh-btn').show();
            $('#refresh-hint').hide();
        } else if (msg.count > 0) {
            $('#refresh-btn').hide();
            $('#refresh-hint').show().html('正在刷新全部造价文件，未刷新完成的造价文件，暂时无法查看(待刷新：' + msg.count + ')');
        }
    });

    // 系统事件
    socket.on('disconnect', msg => {
        console.log('#disconnect', msg);
    });

    socket.on('disconnecting', () => {
        console.log('#disconnecting');
    });

    socket.on('error', () => {
        console.log('#error');
    });

    window.socket = socket;
};