var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
define(["require", "exports", "jquery", "../../../Modal", "xlsx", "./index", "xlsx/dist/cpexcel.full.mjs"], function (require, exports, jquery_1, Modal_1, XLSX, index_1, cptable) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    jquery_1 = __importDefault(jquery_1);
    Modal_1 = __importStar(Modal_1);
    XLSX = __importStar(XLSX);
    cptable = __importStar(cptable);
    XLSX.set_cptable(cptable);
    /** @class Excel load excel file to table without upload to server */
    class Excel {
        static create(props) {
            return new Excel(props);
        }
        constructor(props) {
            this.props = props;
            Modal_1.default.open(this.props.title, Modal_1.ModalSize.lg);
            this.getTableProps().then(() => {
                this.makeWindowFileLoader();
            });
        }
        getTableProps() {
            return new Promise((resolve) => {
                jquery_1.default.get(this.props.url, (data) => {
                    this.tableProps = data;
                    resolve();
                });
            });
        }
        makeWindowFileLoader() {
            const html = '<div class="px-5"><div class="custom-file">' +
                '<input type="file" class="custom-file-input" id="input_dom_element" accept=".xls,.xlsx,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">' +
                '<label class="custom-file-label" for="customFile">Обрати файл</label>' +
                '</div></div>';
            Modal_1.default.setBody(html);
            Modal_1.default.setFooter('');
            Modal_1.default.getBody().find('#input_dom_element').on('change', this.handleFileLoader.bind(this));
        }
        handleFileLoader(ev) {
            const targetFile = ev.target;
            const file = targetFile.files && targetFile.files[0];
            const reader = new FileReader();
            reader.onload = (e) => {
                const data = e.target && e.target.result;
                /* reader.readAsArrayBuffer(file) -> data will be an ArrayBuffer */
                this.workbook = XLSX.read(data);
                this.makeWindowPreview();
            };
            // @ts-ignore
            reader.readAsArrayBuffer(file);
        }
        makeWindowPreview() {
            //console.log(this.workbook);
            const firstSheetName = this.workbook.SheetNames[0];
            const sheet = this.workbook.Sheets[firstSheetName];
            let html = XLSX.utils.sheet_to_html(sheet);
            html = html.substring(html.indexOf('<table>') + 7, html.indexOf('</table>'));
            const colsCount = ((html.substring(0, html.indexOf('</tr>'))).match(/<td/g) || []).length;
            const colSelect = '<select class="form-control"><option></option>' + this.tableProps.columns.map((item) => `<option value='${item.target}'>${item.name}</option>`) + '</select>';
            let columns = '<th></th>';
            for (let i = 0; i < colsCount; i++) {
                columns += '<th>' + colSelect + '</th>';
            }
            let row = 1;
            html = html.replace(/<tr>/g, () => {
                return `<tr><td><input type='checkbox' value='${row++}' checked></td>`;
            });
            html = '<thead><tr>' + columns + '</tr></thead><tbody>' + html + '</tbody>';
            html = '<table class="table table-bordered">' + html + '</table>';
            html = '<div class="table-responsive">' + html + '</div>';
            const buttonContainer = (0, jquery_1.default)('<div/>');
            const button1 = (0, jquery_1.default)('<button type="button" class="btn btn-light">Назад</button>').appendTo(buttonContainer);
            button1.on('click', this.makeWindowFileLoader.bind(this));
            const button2 = (0, jquery_1.default)('<button type="button" class="btn btn-primary ml-2">Завантажити</button>').appendTo(buttonContainer);
            button2.on('click', this.finishSelect.bind(this));
            (0, jquery_1.default)('<button type="button" class="btn btn-light ml-2" data-bs-dismiss="modal">Закрити</button>').appendTo(buttonContainer);
            //console.log(html);
            Modal_1.default.setBody(html);
            Modal_1.default.setFooter(buttonContainer);
        }
        finishSelect() {
            const table = Modal_1.default.getBody().find('table');
            const cols = table.find('thead select').map((_index, item) => {
                return (0, jquery_1.default)(item).val();
            }).get();
            const target = document.querySelector(this.tableProps.target);
            if (!target) {
                throw 'finishSelect.target is no defined';
            }
            table.find('input[type=checkbox]:checked').each((_index, item) => {
                const td = (0, jquery_1.default)(item).closest('tr').find('td');
                (0, index_1.appendRow)(target, (templateNode) => {
                    cols.forEach((target, index) => {
                        if (target != '') {
                            const val = td.eq(index + 1).html();
                            const inputNode = templateNode.find(target);
                            if (inputNode.is('input')) {
                                inputNode.attr('value', val);
                            }
                            else {
                                inputNode.html(val);
                            }
                        }
                    });
                });
            });
            Modal_1.default.close();
        }
    }
    exports.default = Excel;
});
