/*global $*/
function Table() {
    const TClass = {};
    const Tool = {};
    const DataStore = {};
    const Option = {};
    Tool.createHeader = function(htmls, option) {
        const columns = option.columns;
        const dataSource = option.dataSource;
        const selectedRowKeys = option.selectedRowKeys;
        const disabledFun = option.disabled;
        htmls.push('<table>');

        Tool.createColgroup(htmls, option);

        htmls.push('<thead><tr>');
        // 复选框
        if (selectedRowKeys) {
            const checked = selectedRowKeys.length === dataSource.length;
            let disabled = true;
            if (typeof disabledFun === 'function') {
                for (let i = 0; i < dataSource.length; i++) {
                    if (!disabledFun(dataSource[i])) {
                        disabled = false;
                        break;
                    }
                }
            }
            htmls.push(`<th><input data-type="all" type="checkbox" ${checked ? 'checked' : ''} ${disabled ? 'disabled' : ''} /></th>`);
        }
        for (const i in columns) {
            let style = '';
            if (columns[i].align) style = 'text-align: ' + columns[i].align;
            htmls.push('<th style="' + style + '">' + columns[i].title + '</th>');
        }
        htmls.push('</tr></thead></table>');
    };
    Tool.createColgroup = function(htmls, option) {
        const columns = option.columns;
        const selectedRowKeys = option.selectedRowKeys;
        // 宽度
        htmls.push('<colgroup>');
        if (selectedRowKeys) {
            htmls.push('<col style="width: 40px; min-width: 40px"></col>');
        }
        for (const i in columns) {
            htmls.push('<col style="width: ' + (columns[i].width || '') + 'px; min-width: ' + (columns[i].width || '') + 'px;"></col>');
        }
        htmls.push('</colgroup>');
    };
    Tool.createRow = function(htmls, index, option) {
        htmls.push('<tr>');
        const columns = option.columns;
        const dataSource = option.dataSource[index];
        const rowKey = option.rowKey;
        const selectedRowKeys = option.selectedRowKeys;
        const disabledFun = option.disabled;
        if (selectedRowKeys) {
            const checked = selectedRowKeys.indexOf(dataSource[rowKey]) !== -1;
            let disabled = false;
            if (typeof disabledFun === 'function') disabled = disabledFun(dataSource);
            htmls.push(`<td><input data-index="${index}" type="checkbox" ${checked ? 'checked' : ''} ${disabled ? 'disabled' : ''} /></td>`);
        }
        for (const i in columns) {
            let val = columns[i].dataIndex ? dataSource[columns[i].dataIndex] : index;
            let style = '';
            let title = '';
            if (columns[i].align) style = 'text-align: ' + columns[i].align;
            if (typeof columns[i].render === 'function') val = columns[i].render(val, dataSource, index);
            if (columns[i].ellipsis) title = (val + '').replace(/<[^>]+>/g, '').trim();
            htmls.push(`<td class="truncateText" style="${style}" title="${title}">${val}</td>`);
        }
        htmls.push('</tr>');
    };
    Tool.render = function(id, tag) {
        const htmls = [];
        const option = Option[id];

        // 标题
        if (option.title != null) {
            htmls.push('<div class="title">' + option.title + '</div>');
        }

        if (DataStore[id].scroll.y) {
            htmls.push('<div class="hide-scrollbar" style="overflow-y: scroll">');
        }
        // 头部
        Tool.createHeader(htmls, DataStore[id]);

        if (DataStore[id].scroll.y) {
            htmls.push('</div>');
            htmls.push('<div class="workbench-scroll" style="height: ' + DataStore[id].scroll.y + 'px; overflow-y: scroll; margin: -1px 0">');
        }

        htmls.push(`<table rules="rows" style="border: 1px solid ${Option[id].headerBgColor}; margin: -1px 0">`);
        // 宽度
        Tool.createColgroup(htmls, DataStore[id]);
        for (const i in DataStore[id].dataSource) {
            Tool.createRow(htmls, i, DataStore[id]);
        }
        htmls.push('</table>');

        if (DataStore[id].scroll.y) {
            htmls.push('</div>');
        }
        // 合计
        if (DataStore[id].showTotal) {
            if (DataStore[id].scroll.y) {
                htmls.push('<div class="hide-scrollbar" style="overflow-y: scroll">');
            }
            htmls.push(`<table rules="rows" style="border: 1px solid ${Option[id].headerBgColor};">`);
            // 宽度
            Tool.createColgroup(htmls, DataStore[id]);

            htmls.push('<tr>');

            if (DataStore[id].selectedRowKeys) {
                htmls.push('<td></td>');
            }
            for (const i in DataStore[id].columns) {
                const obj = DataStore[id].columns[i];
                let style = '';
                let val = '';
                if (obj.align) style = 'text-align: ' + obj.align;
                if (obj.totalName) val = obj.totalName;
                htmls.push(`<td class="truncateText" style="${style}" title="${val}">${val}</td>`);
            }

            htmls.push('</tr>');

            htmls.push('</table>');
            if (DataStore[id].scroll.y) {
                htmls.push('</div>');
            }
        }

        tag.empty().append(htmls.join(''));
        Tool.setStyle(id, tag);
    };
    Tool.setStyle = function(id, tag) {
        const option = Option[id];
        tag.find('.title').css({
            'font-weight': 'bold',
            'text-align': 'center',
            'color': option.titleColor,
            'font-size': option.titleSize
        });
        tag.find('table').css({
            'width': '100%',
            'border-spacing': '0'
        });
        tag.find('thead').css({
            'color': option.headerColor,
            'background-color': option.headerBgColor,
            'font-size': option.headerSize
        });
        tag.find('tbody').css({
            'color': option.color,
            'font-size': option.size,
            'text-align': option.align
        });
        tag.find('tbody tr:even').css({
            'background-color': option.evenBgColor
        });
        tag.find('tbody tr:odd').css({
            'background-color': option.oddBgColor
        });
        if (option.rowHeight != null) {
            tag.find('tr').css('height', option.rowHeight);
        }
        if (option.scroll) {
            tag.find('.thead').css('overflow', 'scroll');
            const style = {};
            if (option.scroll.x) {
                style.width = option.scroll.x + 'px';
                style['overflow-x'] = 'auto';
            }
            if (option.scroll.y) {
                style.height = option.scroll.y + 'px';
                style['overflow-y'] = 'auto';
            }
            tag.find('.tbody').css(style);
        }
    };
    Tool.getValue = function(value, defalutValue) {
        if (typeof value == 'undefined') {
            return defalutValue;
        } else {
            return value;
        }
    };
    TClass.init = function(option) {
        const id = option.id;
        const tag = $('#' + id);
        const columns = option.columns;
        const dataSource = option.dataSource;
        const rowKey = option.rowKey;
        const selectedRowKeys = option.selectedRowKeys || false;
        const disabled = option.disabled || false;
        const scroll = option.scroll || {};
        const showTotal = option.showTotal || false;
        DataStore[id] = {
            columns: columns,
            dataSource: dataSource,
            rowKey: rowKey,
            selectedRowKeys: selectedRowKeys,
            disabled: disabled,
            scroll: scroll,
            showTotal: showTotal
        };
        Option[id] = {
            title: Tool.getValue(option.title, null),
            titleColor: Tool.getValue(option.titleColor, 'black'),
            titleSize: Tool.getValue(option.titleSize, 16),
            headerColor: Tool.getValue(option.headerColor, '#333'),
            headerBgColor: Tool.getValue(option.headerBgColor, '#f3f3f5'),
            headerSize: Tool.getValue(option.headerSize, 12),
            color: Tool.getValue(option.color, '#666'),
            size: Tool.getValue(option.size, 12),
            align: Tool.getValue(option.align, 'center'),
            evenBgColor: Tool.getValue(option.evenBgColor, 'transparent'),
            oddBgColor: Tool.getValue(option.oddBgColor, 'transparent'),
            rowHeight: Tool.getValue(option.rowHeight, 34)
        };
        Tool.render(id, tag);
    };
    TClass.getValue = function(id, row, column) {
        return DataStore[id].dataSource[row - 1][column - 1];
    };
    TClass.setValue = function(id, row, column, value) {
        DataStore[id].dataSource[row - 1][column - 1] = value;
    };
    TClass.getValues = function(id) {
        return DataStore[id].dataSource;
    };
    TClass.addRow = function(id, data) {
        DataStore[id].dataSource.push(data);
    };
    TClass.deleteRow = function(id, row) {
        DataStore[id].dataSource.splice(row - 1, 1);
    };
    TClass.getRowCount = function(id) {
        return DataStore[id].dataSource.length;
    };
    TClass.render = function(id) {
        Tool.render(id, $('#' + id));
    };
    return TClass;
}