"use strict";

function showLoading() {
    $("#materialLoading").addClass('show');
    $("#materialLoading").removeClass('hide');
}

function hideLoading() {
    $("#materialLoading").addClass('hide');
    $("#materialLoading").removeClass('show');
}
let detailsTable;
let historyTable;

const index = function () {
    const table = document.getElementById('factor-table');
    let dataTable;
    let ajaxRequest;
    let currentPage;
    let toolbarBase;
    let toolbarSelected;
    let selectedCount;
    let modalElement = document.getElementById('modal_change');
    let modalAddElement = document.getElementById('modal_add_new');

    const modalFactorDetailsElement = document.getElementById('factorDetails-modal');
    const modalFactorDetails = new bootstrap.Modal(modalFactorDetailsElement);
    let modalForm = modalElement.querySelector('#modal_change_form');
    let modalAdd = new bootstrap.Modal(modalAddElement);
    let modalFactorHistoryElement = document.getElementById('factorHistory-modal');
    let modalFactorHistory = new bootstrap.Modal(modalFactorHistoryElement);

    let modal = new bootstrap.Modal(modalElement);
    let changingRow;
    let modalShowed = false;
    let modalHtmlMessageCreator = (code, message, cls) => {
        return ` <div class="timeline-label">
                                <div class="timeline-item">
                                    <div class="timeline-label fw-bolder text-gray-800 fs-6">${code}</div>
                                    <!--begin::Badge-->
                                    <div class="timeline-badge">
                                        <i class="fa fa-genderless text-${cls} fs-1"></i>
                                    </div>
                                    <!--end::Badge-->
                                    <!--begin::Text-->
                                    <div class="fw-mormal timeline-content text-muted ps-3">${message}
                                    </div>
                                    <!--end::Text-->
                                </div>
                            </div>`;
    };
    let initTable = () => {
        $.fn.dataTable.ext.errMode = 'none'; // Prevent DataTables from stopping execution

        dataTable = $(table).DataTable({
            language: {
                url: '/media/fa.json'
            },
            ajax: function (data, callback, settings) {
                if (ajaxRequest) {
                    ajaxRequest.abort();
                    ajaxRequest = undefined;
                }
                ajaxRequest = $.ajax({
                    url: "?handler=FactorsList",
                    type: "POST",
                    datatype: "json",
                    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                    data: data,
                    success: function (dataResponse) {
                        const a = dataResponse.model ? dataResponse : JSON.parse(dataResponse);
                        $('#vatLabel').html((a['model'].vat ?? 0).toLocaleString());
                        $('#discountLabel').html((a['model'].discount ?? 0).toLocaleString());
                        $('#invoiceLabel').html((a['model'].invoice ?? 0).toLocaleString());
                        callback(a);
                    },
                    error: function (xhr, textStatus) {
                        if (textStatus === 'abort') return; // prevent noise on client abort
                    },
                    complete: function () {
                        ajaxRequest = undefined;
                    }
                });
            },
            pageLength: 50,
            stateSave: true,
            deferRender: true,
            autoWidth: true,
            processing: true,
            serverSide: true,
            scrollY: "500px",
            scrollX: true,
            scrollCollapse: true,
            fixedHeader: true,
            fixedColumns: {
                left: 1,
                right: 1
            },
            filter: true,
            order: [],
            columnDefs: [
                { orderable: false, targets: 0 }, // Disable ordering on column 0 (checkbox)
                //{orderable: false, targets: 1, visible: false}, // Disable ordering on column 0 (checkbox)
                {
                    targets: 3,
                    createdCell: function (td, cellData, rowData, row, col) {
                        cellData = rowData['status'];
                        if (cellData === 0 || cellData === 1 || cellData === 7) {

                            // $(td.closest('tr')).css('color', '#66CC87');
                            $(td).css('color', '#66CC87');
                        } else if (cellData === 3) {
                            // $(td.closest('tr')).css('color', '#EBBC00');
                            $(td).css('color', '#EBBC00');
                        } else if (cellData === 6) {
                            // $(td.closest('tr')).css('color', '#1F98D3');
                            $(td).css('color', '#1F98D3');

                        } else {
                            // $(td.closest('tr')).css('color', '#FF6D60');
                            $(td).css('color', '#FF6D60');
                        }
                    }
                },
                {
                    targets: 4,
                    createdCell: function (td, cellData, rowData, row, col) {
                        if (rowData['FactorSellId']) {
                            $(td.closest('tr')).css('background', '#B094FF');
                        }

                        let exist = rowData['exist'];
                        console.log(exist);
                        if (!exist) {
                            $(td.closest('tr')).css('background', '#FFCCBC');
                        }


                    }
                }
            ],
            columns: [
                {
                    orderable: false,
                    defaultContent: `
                        <div class="form-check form-check-sm form-check-custom " >
                                        <input class="form-check-input" style="background-color:cadetblue;" type="checkbox" value="1"/>
                                    </div>`
                },
                { data: "id", name: "Id", autoWidth: false, visible: true },
                {
                    data: "idLink", name: "IdLink", autoWidth: false,
                    render: function (data, type, row, meta) {
                        return '<a href="#" style=" text-decoration:underline;" class="link-class" >' + data + '</a>';
                    }
                },
                // {data: "idLink", name: "IdLink", autoWidth: false},
                // {data: "status", name: "Status", visible: false, autoWidth: false},
                { data: "statusText", name: "StatusText", autoWidth: false },
                { data: "invoiceDate", name: "InvoiceDate", autoWidth: false },
                { data: "sendDate", name: "SendDate", autoWidth: false },
                { data: "serialNumber", name: "SerialNumber", autoWidth: false },
                { data: "typeBillText", name: "TypeBill", autoWidth: false },
                { data: "patternText", name: "Pattern", autoWidth: false },
                { data: "subjectBillText", name: "SubjectBillText", autoWidth: false },
                // {data: "cancelled", name: "Cancelled", autoWidth: false,visible: false,
                //     render: function (data, type, row, meta) {
                //         if(!data){
                //             return '';
                //         }else{
                //             return 'ابطال شده';
                //         }

                //     }},
                {
                    data: "taxId", name: "TaxId", autoWidth: false,
                    render: function (data, type, row, meta) {
                        return '<a href="#" style=" text-decoration:underline;" class="link-class-details" >' + data + '</a>';
                    }
                },
                { data: "irTaxId", name: "IrTaxId", autoWidth: false },
                { data: "referenceId", name: "ReferenceId", autoWidth: false, visible: false },
                // {data: "uniqueId", name: "UniqueId", autoWidth: false, visible: false},
                { defaultContent: `<button class="btn btn-link btn-sm message-class">وضعیت</button>`, autoWidth: false },

            ],
        }).search('').state.clear();



        // dataTable.state.clear();
        // dataTable.search(''); // clear the global search filter
        // dataTable.columns().search(''); // clear the column search filters
        // dataTable.order([]); // clear the sorting
        // dataTable.draw(); // redraw the table
        dataTable.columns().every(function () {
            let that = this;
            $('[data-filter-table="search"] input').on('keyup change', function () {
                if (that.search() == this.value) {
                    that.search(this.value).draw();
                }
            });
        });
        dataTable.on('draw', function () {
            initToggleToolbar();
            toggleToolbars();
            handleMessageReader();
        });

        $(table).on('click', '.link-class', function (e) {
            e.preventDefault();
            const value = $(this).data('value');
            //const type = $(this).data('subjectType');
            //const rowIndex = $(this).data('row');
            // var rowData = datatable.row(rowIndex).data();

            let row = $((this).closest('tbody tr'));
            let rowData = dataTable.row(row).data();

            // $('#yourDiv').text(JSON.stringify(rowData)).show();

            $('#factorHistory-title').text("سابقه فاکتور: " + rowData["idLink"]).show();

            console.log(rowData["taxId"]);
            $.ajax({
                url: '?handler=FactorHistory',
                data: { taxId: rowData["taxId"], irTaxId: rowData["irTaxId"] ?? "" },
                success: function (partialViewHtml) {
                    document.querySelector("#factorHistory-data").innerHTML = partialViewHtml;
                    historyTable = $("#factorHistory-table").DataTable({
                        language: {
                            url: '../media/fa.json'
                        },
                        paging: false,
                        scrollX: true,
                        scrollCollapse: true,
                        fixedHeader: true,
                        fixedColumns: false,
                        scrollY: 300,

                    });
                    modalFactorHistory.show();
                },
                error: function (xhr, status, error) {
                    console.error(error);
                }
            });


        });
        $(table).on('click', '.link-class-details', function (e) {
            e.preventDefault();
            const value = $(this).data('value');
            const rowIndex = $(this).data('row');
            // var rowData = datatable.row(rowIndex).data();t

            // Get the data of the clicked row
            const row = $((this).closest('tbody tr'));
            const rowData = dataTable.row(row).data();

            // $('#yourDiv').text(JSON.stringify(rowData)).show();
            $('#factorDetails-title').text("اقلام فاکتور: " + rowData["taxId"]).show();

            $('#myModal').on('shown.bs.modal', function () {
                // $('#myInput').trigger('focus')
            });
            $.ajax({
                url: '?handler=FactorDetails',
                data: { taxId: rowData.taxId },
                success: function (partialViewHtml) {
                    // Inject the generated partial view HTML into your desired element
                    // $('#factorDetails').html(partialViewHtml);
                    document.querySelector("#factorDetails").innerHTML = partialViewHtml;
                    detailsTable = $("#factor-details-table").DataTable({
                        language: {
                            url: '../media/fa.json'
                        },
                        scrollX: true,
                        scrollCollapse: true,
                        autoWidth: true,
                        scrollY: 300,
                        paging: false,
                        columnDefs: [
                            { target: 2, autoWidth: true }
                        ]
                    });
                    handleSearchProductDatatable();
                    modalFactorDetails.show();

                },
                error: function (xhr, status, error) {
                    console.error(error);
                }
            });


        });
        $('#factorHistory-modal').on('shown.bs.modal', function (event) {
            historyTable.columns.adjust(); // Adjust colum
        });

        $('#factorDetails-modal').on('shown.bs.modal', function () {
            detailsTable.columns.adjust(); // Adjust columns after the modal is visible
        });
    };

    const handleMessageReader = () => {
        let links = table.querySelectorAll('tbody button');
        // console.log(links);
        links.forEach(c => {
            c.addEventListener('click', function (e) {
                let row = $(c.closest('tbody tr'));
                // datatable.row().remove().draw();
                let data = dataTable.row(row).data();
                $.ajax({
                    url: '?handler=ReadMessage',
                    type: 'Get',
                    data: { id: data.id },
                    success: function (response) {
                        let msg = '';


                        if (!response) {
                            msg = 'جوابی برای این درخواست ثبت نشده است';
                        } else if (response.success) {
                            msg = 'صورت حساب به صورت صحیح در سامانه ثبت شده است';
                        } else {
                            for (let i = 0; i < response.error.length; i++) {
                                msg += modalHtmlMessageCreator(response.error[i].code, response.error[i].message, 'danger');
                            }
                            for (let i = 0; i < response.warning.length; i++) {
                                msg += modalHtmlMessageCreator(response.warning[i].code, response.warning[i].message, 'warning');
                            }
                        }

                        $('#message-body').html(msg);
                        modal.show();
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });

        });
    }
    // Init toggle toolbar
    const initToggleToolbar = () => {
        // Toggle selected action toolbar   
        // Select all checkboxes
        const checkboxes = document.querySelector(".table-responsive")
            .querySelectorAll('[type="checkbox"]');

        // Select elements
        toolbarBase = document.querySelector('[data-card-toolbar="base"]');
        toolbarSelected = document.querySelector('[data-card-toolbar="selected"]');
        selectedCount = document.querySelector('[data-card-toolbar="selected_count"]');

        // Toggle delete selected toolbar
        checkboxes.forEach(c => {
            // Checkbox on click event
            c.addEventListener('change', function () {
                setTimeout(function () {
                    toggleToolbars();
                }, 50);
            });
        });


    };

    // Toggle toolbars
    const toggleToolbars = () => {
        // Select refreshed checkbox DOM elements 
        const allCheckboxes = table.querySelectorAll('tbody [type="checkbox"]');

        // Detect checkboxes state & count
        let checkedState = false;
        let count = 0;

        // Count checked boxes
        allCheckboxes.forEach(c => {
            if (c.checked) {
                checkedState = true;
                count++;
            }
        });

        // Toggle toolbars
        if (checkedState) {
            selectedCount.innerHTML = count;
            toolbarBase.classList.add('d-none');
            toolbarSelected.classList.remove('d-none');
        } else {
            toolbarBase.classList.remove('d-none');
            toolbarSelected.classList.add('d-none');
        }
    };
    // Search Datatable --- official docs reference: https://datatables.net/reference/api/search()
    const handleSearchDatatable = () => {
        const filterSearch = document.querySelector('[data-filter-table="search"]');
        filterSearch.addEventListener('keyup', function (e) {
            let timeoutId;
            clearTimeout(timeoutId);
            timeoutId = setTimeout(async () => {
                if (ajaxRequest) {
                    ajaxRequest.abort();
                    ajaxRequest = undefined;
                }
                dataTable.search(e.target.value).draw();
            }, 2000);


        });
        const filterSerialNumber = document.querySelector('[data-filter-table="serialNumber"]');
        filterSerialNumber.addEventListener('keyup', function (e) {
            let timeoutId;
            clearTimeout(timeoutId);
            timeoutId = setTimeout(async () => {
                if (ajaxRequest) {
                    ajaxRequest.abort();
                    ajaxRequest = undefined;
                }
                dataTable.column(11).search(e.target.value).draw();
            }, 2000);
        });
    };
    const handleSearchProductDatatable = () => {
        const filterSearch = document.querySelector('[data-filter-table="search-product"]');
        filterSearch.addEventListener('keyup', function (e) {
            detailsTable.search(e.target.value).draw();
        });
    };
    let initComponents = () => {

        jalaliDatepicker.startWatch({
            time: true,
        });
        // selects
        const today = new Date().toLocaleString('fa-IR-u-nu-latn', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', formatMatcher: 'basic' })
        $('#tarikhebtal_input').val(today.replace(',', ''));

        // $('#tarikhebtal_input').on('change', function () {
        //     $('#tarikhebtal_input').val(jalaliDatepicker.toJalali(this.value).format('YYYY/MM/DD'));
        // });
        Inputmask({
            mask: "9999/99/99[ 99:99:99]",
            placeholder: "YYYY/MM/DD HH:MM:SS",
            definitions: {
                'Y': { validator: "[1-2]", cardinality: 1 },
                'M': { validator: "0[1-9]|1[0-2]", cardinality: 2 },
                'D': { validator: "0[1-9]|[12][0-9]|3[01]", cardinality: 2 },
                'H': { validator: "[01][0-9]|2[0-3]", cardinality: 2 },
                'm': { validator: "[0-5][0-9]", cardinality: 2 },
                's': { validator: "[0-5][0-9]", cardinality: 2 }
            },
            keepStatic: true
        }).mask("#tarikhebtal_input");
        Inputmask({
            mask: "9999/99/99",
            placeholder: "YYYY/MM/DD",
            definitions: {
                'Y': { validator: "[1-2]", cardinality: 1 },
                'M': { validator: "0[1-9]|1[0-2]", cardinality: 2 },
                'D': { validator: "0[1-9]|[12][0-9]|3[01]", cardinality: 2 },
                'H': { validator: "[01][0-9]|2[0-3]", cardinality: 2 },
                'm': { validator: "[0-5][0-9]", cardinality: 2 },
                's': { validator: "[0-5][0-9]", cardinality: 2 }
            }
        }).mask("#fromDate");
        Inputmask({
            mask: "9999/99/99",
            placeholder: "YYYY/MM/DD",
            definitions: {
                'Y': { validator: "[1-2]", cardinality: 1 },
                'M': { validator: "0[1-9]|1[0-2]", cardinality: 2 },
                'D': { validator: "0[1-9]|[12][0-9]|3[01]", cardinality: 2 },
                'H': { validator: "[01][0-9]|2[0-3]", cardinality: 2 },
                'm': { validator: "[0-5][0-9]", cardinality: 2 },
                's': { validator: "[0-5][0-9]", cardinality: 2 }
            }
        }).mask("#toDate");
        Inputmask({
            mask: "9999/99/99[ 99:99:99]",
            placeholder: "YYYY/MM/DD HH:MM:SS",
            definitions: {
                'Y': { validator: "[1-2]", cardinality: 1 },
                'M': { validator: "0[1-9]|1[0-2]", cardinality: 2 },
                'D': { validator: "0[1-9]|[12][0-9]|3[01]", cardinality: 2 },
                'H': { validator: "[01][0-9]|2[0-3]", cardinality: 2 },
                'm': { validator: "[0-5][0-9]", cardinality: 2 },
                's': { validator: "[0-5][0-9]", cardinality: 2 }
            },
            keepStatic: true

        }).mask("#newDate_input");

    };
    // Handle status filter dropdown
    let handleStatusFilter = () => {
        // datatable.column(3).search('رد شده').draw();

        const filterStatus = document.querySelector('[data-filter="status"]');
        $(filterStatus).on('change', e => {
            let value = e.target.value;
            if (value === 'all') {
                value = '';
            }
            dataTable.column(9).search(value).draw();

        });
        const filterSubject = document.querySelector('[data-filter="subject"]');
        $(filterSubject).on('change', e => {
            let value = e.target.value;
            if (value === 'all') {
                value = '';
            }
            dataTable.column(10).search(value).draw();

        });
    }

    const modalHandlers = () => {
        let submitBtn = modalAddElement.querySelector('#modal_add_new_submit');
        submitBtn.addEventListener('click', function (e) {
            e.preventDefault();

            let invoiceId = $('#newInvoiceId_input').val();
            let irTaxId = $('#newInvoiceIrTaxId_input').val()
            let date = $('#newDate_input').val()
            if (invoiceId && irTaxId) {
                if ($('#useInvoiceDate_chk').prop('checked')) {
                    date = null;
                } else {
                    if (!date) {
                        toastr.warning('تاریخ به صورت صحیح وارد نشده است');
                        return;
                    }
                }
                modalAdd.hide();
                $.ajax({
                    url: '?handler=AddCancellationInvoice',
                    method: 'post',
                    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                    data: { invoiceId, irTaxId, date },
                    success: function (res) {
                        if (res["isSuccess"]) {
                            toastr.success(res["message"]);
                            document.getElementById('btnFilter').click();
                        } else
                            toastr.error(res["message"]);
                    },
                    error: function (err) {
                        console.log(err);
                        toastr.error(`خطا در انجام عملیات`);
                    }
                });
            } else {
                toastr.warning('اطلاعات را به صورت صحیح وارد نمایید');
            }
        });


    }
    let handlers = () => {

        $('#btnFilter').click(function () {
            dataTable.columns(1).search($('#fromDate').val());
            dataTable.columns(2).search($('#toDate').val());
            if (document.querySelector('[data-filter-table="search"]').value == '')
                dataTable.search('');
            dataTable.draw();
        });
        const calcButton = document.getElementById('calcTotalBtn');
        $('#calcTotalBtn').click(function () {
            calcButton.setAttribute('data-kt-indicator', 'on');
            calcButton.disabled = true;
            $.ajax({
                url: "?handler=Total",
                type: "Get",
                data: { from: $('#fromDate').val(), to: $('#toDate').val() },
                success: function (dataResponse) {
                    $('#vatLabel').html((dataResponse.vat ?? 0).toLocaleString());
                    $('#discountLabel').html((dataResponse.discount ?? 0).toLocaleString());
                    $('#invoiceLabel').html((dataResponse.invoice ?? 0).toLocaleString());
                    calcButton.removeAttribute('data-kt-indicator');
                    calcButton.disabled = false;
                    return dataResponse;

                },
                error: function (err, status) {
                    calcButton.removeAttribute('data-kt-indicator');
                    calcButton.disabled = false;
                    console.log(err);
                },
            })
        });
        $('#btnFilter1').click(function () {
            dataTable.columns(7).search(document.querySelector('input[name="leaveType"]:checked').value.trim());
            dataTable.columns(8).search(document.querySelector('input[name="dateRadio"]:checked').value.trim());
            if ($('#search_checkbox_date').prop('checked')) {
                if ($('#search_start_date').val().trim() === '' && $('#search_end_date').val().trim() == '') {
                    toastr.warning(window.translates.selectDateWarning);
                    return;
                }
                if ($('#search_start_date').val().trim() !== '' && $('#search_end_date').val().trim() !== '') {
                    if ($('#search_start_date').val().trim() > $('#search_end_date').val().trim()) {
                        Swal.fire({
                            text: window.translates.invalidDates,
                            icon: "error",
                            buttonsStyling: false,
                            confirmButtonText: window.translates.ok,
                            customClass: {
                                confirmButton: "btn btn-primary"
                            }
                        });
                        return;
                    }
                }
                dataTable.columns(3).search($('#search_start_date').val().trim());
                dataTable.columns(4).search($('#search_end_date').val().trim());
            } else {
                dataTable.columns(3).search('');
                dataTable.columns(4).search('');
            }
            if ($('#search_checkbox_time').prop('checked')) {

                if ($('#search_start_time').val().trim() === '' && $('#search_end_time').val().trim() == '') {
                    toastr.warning(window.translates.selectTimeWarning);
                    return;
                }
                dataTable.columns(5).search($('#search_start_time').val().trim());
                dataTable.columns(6).search($('#search_end_time').val().trim());
            } else {
                dataTable.columns(5).search('');
                dataTable.columns(6).search('');
            }
            dataTable.draw();
        });
        // Estelam = inquiry
        $('[data-card-toolbar="send_selected"]').click(function () {

            const checkboxes = table.querySelectorAll('[type="checkbox"]');

            // Select elements
            const deleteSelected = document.querySelector('[data-kt-customer-table-select="delete_selected"]');
            let ids = [];
            let uids = [];
            let sendDates = [];
            checkboxes.forEach(c => {
                if (c.checked) {
                    // let row = $(this).closest('tr');
                    let row = $(c.closest('tbody tr'));
                    // datatable.row().remove().draw();
                    let data = dataTable.row(row).data();
                    if (data) {
                        ids.push(data.referenceId);
                        uids.push(data.uniqueId);
                        sendDates.push(data.sendDate);
                    }
                }
            });
            // var selectedIds = datatable.columns().checkboxes.selected()[0];
            currentPage = dataTable.page();
            showLoading();
            $.ajax({
                url: '?handler=Inquiry',
                method: 'POST',
                data: { referenceId: ids, uids, sendDates },
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (response) {
                    document.getElementById('btnFilter').click();
                    dataTable.page(currentPage).draw('page');
                    toastr.success('روی نمایش پیام کلیک کنید', 'استعلام موارد انتخاب شده انجام شد');
                    hideLoading();
                },
                error: function (x) {
                    console.log(x);
                    hideLoading();
                    toastr.error(x.responseText);


                }
            });
        });
        $('#useInvoiceDate_chk').on('change', e => {
            let value = e.target.checked;
            $('#newDate_input').prop('disabled', value);
        });

        $('#useInvoiceDate_ebtal_chk').on('change', e => {
            let value = e.target.checked;
            $('#tarikhebtal_input').prop('disabled', value);
        });
        $('[data-card-toolbar="delete"]').click(async function () {
            if (!await confirmAction()) {
                return;
            }
            const checkboxes = table.querySelectorAll('[type="checkbox"]');

            // Select elements
            const deleteSelected = document.querySelector('[data-kt-customer-table-select="delete_selected"]');
            let ids = [];
            let taxIds = [];
            checkboxes.forEach(c => {
                if (c.checked) {
                    // let row = $(this).closest('tr');
                    let row = $(c.closest('tbody tr'));
                    // datatable.row().remove().draw();
                    let data = dataTable.row(row).data();
                    if (data) {
                        taxIds.push(data.taxId);
                        ids.push(data.id);
                    }
                }
            });
            // var selectedIds = datatable.columns().checkboxes.selected()[0];

            showLoading();
            $.ajax({
                url: '?handler=deleteInvoice',
                method: 'POST',
                data: { taxIds: taxIds, ids },
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (response) {
                    if (response && response.length > 0) {
                        let msg = '';
                        if (!response) {
                            msg = 'جوابی برای این درخواست ثبت نشده است';
                        } else {
                            for (let factorIndex = 0; factorIndex < response.length; factorIndex++) {
                                for (let i = 0; i < response[factorIndex].errors.length; i++) {
                                    msg += modalHtmlMessageCreator(response[factorIndex].id, response[factorIndex].errors[i], 'danger');
                                }

                            }
                            for (let factorIndex = 0; factorIndex < response.length; factorIndex++) {
                                for (let i = 0; i < response[factorIndex].warnings.length; i++) {
                                    msg += modalHtmlMessageCreator(response[factorIndex].id, response[factorIndex].warning[i], 'warning');
                                }

                            }
                        }

                        $('#message-body').html(msg);
                        modal.show();
                        hideLoading()
                        return;
                    }
                    //reload datatable
                    document.getElementById('btnFilter').click();
                    toastr.success('روی نمایش پیام کلیک کنید', 'حذف موارد انتخاب شده انجام شد');
                    hideLoading();
                },
                error: function (x) {
                    console.log(x);
                    hideLoading();
                    toastr.error('امکان ارسال صورت حساب انتخاب شده وجود ندارد');
                    // swal.fire({
                    //     text: x.responseText,
                    //     title: 'امکان ارسال صورت حساب انتخاب شده وجود ندارد',
                    //     icon: 'error',
                    //     confirmButtonText: 'باشه',
                    //     customClass: {
                    //         confirmButton: "btn fw-bold btn-danger",
                    //     }
                    // });

                }
            });
        });
        $('[data-card-toolbar="send_eslah"]').click(async function (event) {
            const $btn = $(this);
            if ($btn.prop('disabled')) {
                return;
            }
            $btn.prop('disabled', true); // Disable button to prevent double click
            if (!await confirmAction()) {
                $btn.prop('disabled', false);
                return;
            }
            let date = $('#tarikhebtal_input').val();
            if ($('#useInvoiceDate_ebtal_chk').prop('checked')) {
                date = null;
            } else {
                if (!date) {
                    toastr.error('تاریخ تعیین شده برای ارسال ابطالی یا اصلاحی اشتباه است');
                    $btn.prop('disabled', false);
                    return;
                }
            }
            const checkboxes = table.querySelectorAll('[type="checkbox"]');
            const deleteSelected = document.querySelector('[data-kt-customer-table-select="delete_selected"]');
            let selectedInvoices = [];
            checkboxes.forEach(c => {
                if (c.checked) {
                    let row = $(c.closest('tbody tr'));
                    let data = dataTable.row(row).data();
                    if (data)
                        selectedInvoices.push({
                            referenceId: data['referenceId'],
                            uniqueId: data['uniqueId'],
                            idLink: data['idLink'],
                            id: data['id'],
                            taxId: data['taxId'],
                            typeLink: data['typeLink'],
                            subjectBill: data['subjectBill'],
                            sendDate: data['sendDate'],
                        });
                }
            });
            showLoading();
            $.ajax({
                url: '?handler=SendCorrection',
                method: 'POST',
                data: { invoices: selectedInvoices, subject: 2, userInvoiceDate: date },
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (response) {
                    if (response && response.length > 0) {
                        let msg = '';
                        if (!response) {
                            msg = 'جوابی برای این درخواست ثبت نشده است';
                        } else {
                            for (let factorIndex = 0; factorIndex < response.length; factorIndex++) {
                                for (let i = 0; i < response[factorIndex].errors.length; i++) {
                                    msg += modalHtmlMessageCreator(response[factorIndex].id, response[factorIndex].errors[i], 'danger');
                                }
                            }
                            for (let factorIndex = 0; factorIndex < response.length; factorIndex++) {
                                for (let i = 0; i < response[factorIndex].warnings.length; i++) {
                                    msg += modalHtmlMessageCreator(response[factorIndex].id, response[factorIndex].warning[i], 'warning');
                                }
                            }
                        }
                        $('#message-body').html(msg);
                        modal.show();
                        hideLoading();
                        $btn.prop('disabled', false);
                        return;
                    }
                    document.getElementById('btnFilter').click();
                    toastr.success('روی نمایش پیام کلیک کنید', 'اصلاح موارد انتخاب شده انجام شد');
                    hideLoading();
                    $btn.prop('disabled', false);
                },
                error: function (x) {
                    console.log(x);
                    hideLoading();
                    toastr.error(x.responseText);
                    $btn.prop('disabled', false);
                }
            });
        });
        $('[data-card-toolbar="send_ebtal"]').click(async function () {
            const $btn = $(this);
            if ($btn.prop('disabled')) {
                return;
            }
            $btn.prop('disabled', true); // Disable button to prevent double click
            if (!await confirmAction()) {
                $btn.prop('disabled', false);
                return;
            }
            let date = $('#tarikhebtal_input').val();
            if ($('#useInvoiceDate_ebtal_chk').prop('checked')) {
                date = null;
            } else {
                if (!date) {
                    toastr.error('تاریخ تعیین شده برای ارسال ابطالی یا اصلاحی اشتباه است');
                    $btn.prop('disabled', false);
                    return;
                }
            }
            const checkboxes = table.querySelectorAll('[type="checkbox"]');
            const deleteSelected = document.querySelector('[data-kt-customer-table-select="delete_selected"]');
            let selectedInvoices = [];
            checkboxes.forEach(c => {
                if (c.checked) {
                    // let row = $(this).closest('tr');
                    let row = $(c.closest('tbody tr'));
                    // datatable.row().remove().draw();
                    let data = dataTable.row(row).data();
                    if (data)
                        selectedInvoices.push({
                            referenceId: data['referenceId'],
                            uniqueId: data['uniqueId'],
                            idLink: data['idLink'],
                            id: data['id'],
                            taxId: data['taxId'],
                            typeLink: data['typeLink'],
                            subjectBill: data['subjectBill'],
                            sendDate: data['sendDate'],
                        });
                }
            });
            // var selectedIds = datatable.columns().checkboxes.selected()[0];

            showLoading();
            $.ajax({
                url: '?handler=SendCorrection',
                method: 'POST',
                data: { invoices: selectedInvoices, subject: 3, userInvoiceDate: date },
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (response) {
                    if (response && response.length > 0) {
                        let msg = '';
                        if (!response) {
                            msg = 'جوابی برای این درخواست ثبت نشده است';
                        } else {
                            for (let factorIndex = 0; factorIndex < response.length; factorIndex++) {
                                for (let i = 0; i < response[factorIndex].errors.length; i++) {
                                    msg += modalHtmlMessageCreator(response[factorIndex].id, response[factorIndex].errors[i], 'danger');
                                }

                            }
                            for (let factorIndex = 0; factorIndex < response.length; factorIndex++) {
                                for (let i = 0; i < response[factorIndex].warnings.length; i++) {
                                    msg += modalHtmlMessageCreator(response[factorIndex].id, response[factorIndex].warning[i], 'warning');
                                }

                            }

                            $('#message-body').html(msg);
                        }
                        modal.show();
                        hideLoading();
                        $btn.prop('disabled', false);
                        return;
                    }
                    document.getElementById('btnFilter').click();
                    toastr.success('روی نمایش پیام کلیک کنید', 'ابطال موارد انتخاب شده انجام شد');
                    hideLoading();
                    $btn.prop('disabled', false);
                },
                error: function (x) {
                    console.log(x);
                    hideLoading();
                    toastr.error(x.responseText);
                    $btn.prop('disabled', false);
                }
            });
        });

        $('[data-card-toolbar="send_again"]').click(async function () {
            const $btn = $(this);
            if ($btn.prop('disabled')) {
                return;
            }
            $btn.prop('disabled', true); // Disable button to prevent double click
            if (!await confirmAction()) {
                $btn.prop('disabled', false);
                return;
            }
            let date = $('#tarikhebtal_input').val();
            if ($('#useInvoiceDate_ebtal_chk').prop('checked')) {
                date = null;
            } else {
                if (!date) {
                    toastr.error('تاریخ تعیین شده برای ارسال ابطالی یا اصلاحی اشتباه است');
                    $btn.prop('disabled', false);
                    return;
                }
            }
            const checkboxes = table.querySelectorAll('[type="checkbox"]');
            let selectedInvoices = [];
            checkboxes.forEach(c => {
                if (c.checked) {
                    // let row = $(this).closest('tr');
                    let row = $(c.closest('tbody tr'));
                    // datatable.row().remove().draw();
                    let data = dataTable.row(row).data();
                    if (data)
                        selectedInvoices.push({
                            referenceId: data['referenceId'],
                            uniqueId: data['uniqueId'],
                            idLink: data['idLink'],
                            id: data['id'],
                            taxId: data['taxId'],
                            typeLink: data['typeLink'],
                            subjectBill: data['subjectBill'],
                            sendDate: data['sendDate'],
                        });
                }
            });
            // var selectedIds = datatable.columns().checkboxes.selected()[0];

            showLoading();
            $.ajax({
                url: '?handler=SendCorrection',
                method: 'POST',
                data: { invoices: selectedInvoices, subject: 5, userInvoiceDate: date },
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (response) {
                    if (response && response.length > 0) {
                        let msg = '';
                        if (!response) {
                            msg = 'جوابی برای این درخواست ثبت نشده است';
                        } else {
                            for (let factorIndex = 0; factorIndex < response.length; factorIndex++) {
                                for (let i = 0; i < response[factorIndex].errors.length; i++) {
                                    msg += modalHtmlMessageCreator(response[factorIndex].id, response[factorIndex].errors[i], 'danger');
                                }

                            }
                            for (let factorIndex = 0; factorIndex < response.length; factorIndex++) {
                                for (let i = 0; i < response[factorIndex].warnings.length; i++) {
                                    msg += modalHtmlMessageCreator(response[factorIndex].id, response[factorIndex].warning[i], 'warning');
                                }

                            }

                            $('#message-body').html(msg);
                        }
                        modal.show();
                        hideLoading()
                        $btn.prop('disabled', false);

                        return;
                    }
                    $btn.prop('disabled', false);
                    document.getElementById('btnFilter').click();
                    toastr.success('روی نمایش پیام کلیک کنید', 'ارسال موارد انتخاب شده انجام شد');
                    hideLoading();
                },
                error: function (x) {
                    console.log(x);
                    hideLoading();
                    toastr.error(x.responseText);
                    $btn.prop('disabled', false);


                }
            });
        });

        $('[data-card-toolbar="send_bargasht"]').click(async function () {

            const $btn = $(this);
            if ($btn.prop('disabled')) {
                return;
            }
            $btn.prop('disabled', true); // Disable button to prevent double click
            if (!await confirmAction()) {
                $btn.prop('disabled', false);
                return;
            }

            const checkboxes = table.querySelectorAll('[type="checkbox"]');

            // Select elements
            const deleteSelected = document.querySelector('[data-kt-customer-table-select="delete_selected"]');
            let selectedInvoices = [];
            checkboxes.forEach(c => {
                if (c.checked) {
                    // let row = $(this).closest('tr');
                    let row = $(c.closest('tbody tr'));
                    // datatable.row().remove().draw();
                    let data = dataTable.row(row).data();
                    if (data)
                        selectedInvoices.push({
                            referenceId: data['referenceId'],
                            uniqueId: data['uniqueId'],
                            idLink: data['idLink'],
                            id: data['id'],
                            taxId: data['taxId'],
                            typeLink: data['typeLink'],
                            subjectBill: data['subjectBill'],
                            sendDate: data['sendDate'],
                        });
                }
            });
            // var selectedIds = datatable.columns().checkboxes.selected()[0];

            showLoading();
            $.ajax({
                url: '?handler=SendCorrection',
                method: 'POST',
                data: { invoices: selectedInvoices, subject: 4 },
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (response) {
                    if (response && response.length > 0) {
                        let msg = '';


                        if (!response) {
                            msg = 'جوابی برای این درخواست ثبت نشده است';
                        } else {
                            for (let factorIndex = 0; factorIndex < response.length; factorIndex++) {
                                for (let i = 0; i < response[factorIndex].errors.length; i++) {
                                    msg += modalHtmlMessageCreator(response[factorIndex].id, response[factorIndex].errors[i], 'danger');
                                }

                            }
                            for (let factorIndex = 0; factorIndex < response.length; factorIndex++) {
                                for (let i = 0; i < response[factorIndex].warnings.length; i++) {
                                    msg += modalHtmlMessageCreator(response[factorIndex].id, response[factorIndex].warning[i], 'warning');
                                }

                            }

                            $('#message-body').html(msg);
                        }
                        modal.show();
                        hideLoading()
                        $btn.prop('disabled', false);
                        return;
                    }
                    document.getElementById('btnFilter').click();
                    toastr.success('روی نمایش پیام کلیک کنید', 'برگشت موارد انتخاب شده انجام شد');
                    hideLoading();
                    $btn.prop('disabled', false);
                },
                error: function (x) {
                    console.log(x);
                    hideLoading();
                    toastr.error(x.responseText);
                    $btn.prop('disabled', false);
                }
            });
        });
        const calcBtn = $('#calculateOldInvoicesBtn');
        calcBtn.on('click', async function () {
            const txt = ajaxRequest ? "آیا مطمئنید میخواهید عملیات را متوقف کنید؟" : "پس از شروع عملیات نباید صفحه را بازسازی یا تغییر دهید، ادامه میدهید؟ "
            const result = await Swal.fire({
                title: 'آیا اطمینان دارید؟',
                text: txt,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'بله',
                cancelButtonText: 'خیر'
            });
            if (!result.isConfirmed)
                return;
            if (ajaxRequest) {
                calcBtn.text('محاسبه صورت حساب های قبلی');
                toastr.warning('توقف عملیات');
                ajaxRequest.abort();
                ajaxRequest = undefined;
                return;
            }
            calcBtn.text('توقف');
            ajaxRequest = $.ajax({
                url: '?handler=CalcDetails',
                method: 'post',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (response) {
                    toastr.info(response['message']);
                    ajaxRequest = undefined;
                    calcBtn.text('محاسبه صورت حساب های قبلی');
                }, error: function (error, status, errorThrown) {
                    if (status === 'abort')
                        toastr.warning('توقف عملیات');
                    else {
                        toastr.error('خطا هنگام پردازش');

                    }
                    calcBtn.text('محاسبه صورت حساب های قبلی');
                }
            })
        });
        $(modalElement).on('hidden.bs.modal',
            function () {
                modalShowed = false;
            });
    };
    async function confirmAction() {
        const result = await Swal.fire({
            title: 'آیا اطمینان دارید؟',
            text: "عملیات انجام شده قابل بازیابی نیست",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'بله',
            cancelButtonText: 'خیر'
        });
        return result.isConfirmed;
    }
    return {
        // Public functions  
        init: function () {
            if (!table) {
                return;
            }
            initComponents();
            initTable();
            handlers();
            handleStatusFilter();
            handleSearchDatatable();
            modalHandlers();


        }
    };
}();

// On document ready
KTUtil.onDOMContentLoaded(function () {
    index.init();
});
//
//
// var calcDataTableHeight = function() {
//     return $(window).height() * 55 / 100;
// };
//
// var oTable = $('#reqAllRequestsTable').dataTable({
//     "sScrollY": calcDataTableHeight();
// });
//
// $(window).resize(function() {
//     var oSettings = oTable.fnSettings();
//     oSettings.oScroll.sY = calcDataTableHeight();
//     oTable.fnDraw();
// });