(function ($) {
    if (!window.Excel) {
        window.Excel = {};
    }

    window.Excel.ExportToFile = function (tableId) {
        this.tableId = tableId;
        this.tableContext = $('.' + this.tableId);
        this.tableBodyContext = $('tbody', this.tableContext);
        this.data = [];
        this.dateCellIndex = 0;
        this.formatCode = 'dd.mm.yy';
        this.summaryRow = $('.total', this.tableContext);
        this.init();
    };

    window.Excel.ExportToFile.prototype.init = function () {
        this.collectTable();
    };

    window.Excel.ExportToFile.prototype.collectTable = function () {
        this.collectHeaders();
        this.collectData();
    };

    window.Excel.ExportToFile.prototype.collectHeaders = function () {
        var rowSpans = [];
        var $this = this;
        $('tr.table-headers', this.tableContext).each(function (line, tr) {
            var row = [];
            var realIndexAddition = 0;
            $('th', tr).each(function (index, cellData) {
                var realIndex = realIndexAddition + index;

                while (rowSpans[realIndex] !== 0) {
                    if (rowSpans[realIndex] === undefined) {
                        rowSpans[realIndex] = 0;
                        break;
                    }
                    row.push('');
                    rowSpans[realIndex]--;
                    realIndex++;
                    realIndexAddition++;
                }

                row.push($(cellData).text().trim());
                var rowSpan = 0;
                if (cellData.hasAttribute('rowspan')) {
                    rowSpan = parseInt(cellData.getAttribute('rowspan')) - 1;
                    if (rowSpan < 0) {
                        rowSpan = 0;
                    }
                }
                rowSpans[realIndex] = rowSpan;

                if (cellData.hasAttribute('colspan')) {
                    var colSpan = parseInt(cellData.getAttribute('colspan')) - 1;
                    if (colSpan < 0) {
                        colSpan = 0;
                    }

                    for (var i = 0; i < colSpan; i++) {
                        row.push('');
                        realIndexAddition++;
                        realIndex++;
                        rowSpans[realIndex] = rowSpan;
                    }
                }

            });
            $this.data.push(row);
        });
    };

    window.Excel.ExportToFile.prototype.collectData = function () {
        var $this = this;
        $('tr', this.tableBodyContext).each(function (index, rowContext) {
            $this.data.push($this.collectRow(rowContext))
        });
        $this.data.push($this.collectSummary());
    };

    window.Excel.ExportToFile.prototype.collectRow = function (rowContext) {
        var rowData = [];
        var $this = this;
        $('td', rowContext).each(function (index, cellData) {

            var exportData = $(this).data('export');

            var cellObject = {
                value: exportData ? exportData : $(cellData).text().trim()
            };

            rowData.push(cellObject);
        });
        return rowData;
    };


    window.Excel.ExportToFile.prototype.collectSummary = function () {
        var rowData = [];
        $('th', this.summaryRow).each(function (index, cellData) {
            var cellObject = {
                value: $(cellData).text().trim()
            };
            rowData.push(cellObject);
        });
        return rowData;
    };

    window.Excel.ExportToFile.prototype.parseDateCell = function (dateString) {

        return dateString;
//        var dateParts = dateString.split('.');
//        return new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
    };

    window.Excel.ExportToFile.prototype.doExport = function (fileName) {
        var file = {
            worksheets: [
                {
                    'data': this.data
                }
            ], // worksheets has one empty worksheet (array)
            creator: 'Author', created: new Date(),
            lastModifiedBy: 'Author', modified: new Date(),
            activeWorksheet: 0
        };
        this.initiateDownload(this.createFileName(fileName), xlsx(file).href());
    };

    window.Excel.ExportToFile.prototype.initiateDownload = function (name, dataBase64) {
        var link = document.createElement('a');
        $(link).attr('download', name);
        $(link).attr('href', dataBase64);
        $(link).text(name);
        $(link).attr('id', 'd-link');
        $(link).hide();
        $(link).click(function () {
        });
        var e = document.createEvent('MouseEvents');
        e.initEvent('click', true, true);
        $(link).appendTo('body');
        link.dispatchEvent(e);
        $(link).remove();
    };

    window.Excel.ExportToFile.prototype.createFileName = function (fileName) {
        return fileName + '.xlsx';
    };

    $(function () {
        $('#export-sheet').on('click', function (e) {
            e.preventDefault();
            var exportToFile = new Excel.ExportToFile('table-export');
            exportToFile.doExport($(this).data('file-name') ? $(this).data('file-name') : 'Export');
        });
    })

})(jQuery);