// datatablesSimple

"use strict";

//updateDatabase(dbs[j]).then(function (data) {
//    insertStringTo(name, 'fa-check');
//    console.log(data);
//}).catch(function (err) {
//    insertStringTo(name, 'fa-times');

//    // Run this when promise was rejected via reject()
//    console.log(err);
//});
//const updateDatabase = (id) => {
//    return new Promise(function (resolve, reject) {
//        $.ajax({
//            url: window.urls.ensureOtherDatabaseUpdate,
//            method: 'Get',
//            data: { id },
//            success: function (data) {
//                resolve(data); // Resolve promise and go to then()
//            },
//            error: function (err) {
//                reject(err); // Reject the promise and go to catch()
//            }
//        });
//    });
//}

const materialLoadingElement = $("#materialLoading");

function showLoading() {
    materialLoadingElement.addClass('show');
    materialLoadingElement.removeClass('hide');
}

function hideLoading() {
    materialLoadingElement.addClass('hide');
    materialLoadingElement.removeClass('show');
}

let detailsTable;
const index = function () {
    const table = document.getElementById('factor-table');
    let datatable;
    let toolbarBase;
    let timeout;

    let toolbarSelected;
    let selectedCount;
    const modalElement = document.getElementById('modal_change');
    const modalFactorDetailsElement = document.getElementById('factorDetails-modal');
    const modalFactorDetails = new bootstrap.Modal(modalFactorDetailsElement);
    const modalMessageElement = document.getElementById('modal_message');
    const modalForm = modalElement.querySelector('#modal_change_form');
    const modal = new bootstrap.Modal(modalElement);
    const modalResultElement = document.getElementById('modal_result');
    const modalResult = new bootstrap.Modal(modalResultElement);
    const modalMessage = new bootstrap.Modal(modalMessageElement);
    let changingRow;
    let modalShowed = false;
    let validationResults = [];
    let submitting = false;
    const initTable = () => {
        // const tableRows = table.querySelectorAll('tbody tr');
        // tableRows.forEach(row => {
        //     const dateRow = row.querySelectorAll('td');
        //     const lastLogin = dateRow[3].innerText.toLowerCase(); // Get last login time
        //     let timeCount = 0;
        //     let timeFormat = 'minutes';
        //
        //     // Determine date & time format -- add more formats when necessary
        //     if (lastLogin.includes('yesterday')) {
        //         timeCount = 1;
        //         timeFormat = 'days';
        //     } else if (lastLogin.includes('mins')) {
        //         timeCount = parseInt(lastLogin.replace(/\D/g, ''));
        //         timeFormat = 'minutes';
        //     } else if (lastLogin.includes('hours')) {
        //         timeCount = parseInt(lastLogin.replace(/\D/g, ''));
        //         timeFormat = 'hours';
        //     } else if (lastLogin.includes('days')) {
        //         timeCount = parseInt(lastLogin.replace(/\D/g, ''));
        //         timeFormat = 'days';
        //     } else if (lastLogin.includes('weeks')) {
        //         timeCount = parseInt(lastLogin.replace(/\D/g, ''));
        //         timeFormat = 'weeks';
        //     }
        //
        //     // Subtract date/time from today -- more info on moment datetime subtraction: https://momentjs.com/docs/#/durations/subtract/
        //     const realDate = moment().subtract(timeCount, timeFormat).format();
        //
        //     // Insert real date to last login attribute
        //     dateRow[3].setAttribute('data-order', realDate);
        //
        //     // Set real date for joined column
        //     const joinedDate = moment(dateRow[5].innerHTML, "DD MMM YYYY, LT").format(); // select date from 5th column in table
        //     dateRow[5].setAttribute('data-order', joinedDate);
        // });

        // Init datatable --- more info on datatables: https://datatables.net/manual/
        datatable = $(table).DataTable({
            language: {
                url: '../media/fa.json'
            },
            ajax: {
                url: "?handler=FactorsList",
                type: "POST",
                datatype: "json",
                headers: {"RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()},
                data: function (outData) {
                    // what is being sent to the server
                    // console.log(outData);
                    return outData;
                },
                dataFilter: function (inData) {
                    // what is being sent back from the server (if no error)
                    console.log(JSON.parse(inData));
                    const obj = JSON.parse(inData);
                    validationResults = [];
                    for (let i = 0; i < obj.data.length; i++) {
                        validationResults.push({
                            id: obj.data[i].idFactor,
                            messages: obj.data[i].validationResult.errors
                        });
                    }
                    return inData;
                },
                error: function (err, status) {
                    // what error is seen(it could be either server side or client side.
                    console.log(err);
                },
            },
            stateSave: false,
            autoWidth: true,
            processing: true,
            serverSide: true,
            // scroller: true,
            scrollY: "500px",
            scrollX: true,
            scrollCollapse: true,
            fixedHeader: true,
            fixedColumns: {
                right: 1,
                left: 1
            },
            filter: true,
            columnDefs: [
                {orderable: false, targets: 0},

                {
                    targets: 3,
                    createdCell: function (td, cellData, rowData, row, col) {

                        cellData = rowData['validationResult'];
                        if (cellData['errors'].length === 0) {
                            //$(td.closest('tr')).css('color', '#66CC87');
                            $(td).css('color', '#66CC87');
                        } else {
                            //$(td.closest('tr')).css('color', '#FF6D60');
                            $(td).css('color', '#FF6D60');

                        }
                    }
                },
                {
                    targets:6,
                    createdCell : function (td, cellData, rowData, row, col) {
                        cellData = rowData['status'];
                        let exist = rowData['exist'];
                        if (exist) {

                           // $(td.closest('tr')).css('color', '#66CC87');
                            
                        } else {
                            $(td.closest('tr')).css('color', '#FF6D60');

                        }
                        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');
                        }
                    }
                }
            ],
            columns: [
                {
                    orderable: false,
                    defaultContent: `
                        <div class="form-check form-check-sm">
                                        <input class="form-check-input" style="background-color:cadetblue;" type="checkbox" value="1"/>
                                    </div>`
                },
                // {data: "id", name: "Id", autoWidth: false},
                {
                    data: "idFactor", name: "IdFactor", autoWidth: false,
                    render: function (data, type, row, meta) {
                        // Render the link
                        if (row["idFactorSell"] == "0")
                            return '<a href="#" style="text-decoration: underline;" class="link-class" data-value="' + data + '">' + data + '</a>';
                        return '<a href="#" style="text-decoration: underline;" class="link-class" data-value="' + row["idFactorSell"] + '">' + row["idFactorSell"] + '</a>';
                    }
                },
                {
                    data: "idFactorSell", name: "IdFactorSell", autoWidth: false,
                    render: function (data, type, row, meta) {
                        // Render the link
                        if (row["idFactorSell"] == "0")
                            return 0;
                        return row["idFactor"];
                    }
                },
                
                // {data: "successedM", name: "SuccessedM", autoWidth: false},
                {data: "d_date", name: "D_date", autoWidth: false},
                {data: "customInvoiceDate", name: "CustomInvoiceDate", autoWidth: false},
                {data: "taxId", name: "TaxId", autoWidth: false},
                {data: "statusText", name: "StatusText", autoWidth: false,},
                // {data: "date_Sent", name: "DateSent", autoWidth: false},
                // {data: "serialNumber", name: "SerialNumber", autoWidth: false},
                // {data: "uniqueId", name: "uniqueId", autoWidth: false},
                {data: "typeBillText", name: "TypeBill", autoWidth: false},
                {data: "patternText", name: "Pattern", autoWidth: false},
                {data: "subjectBillText", name: "SubjectBill", autoWidth: false},
                {data: "profileTitle", name: "ProfileTitle", autoWidth: false},
                {data: "kindFroshFactor", name: "KindFroshFactor", autoWidth: true},
                {data: "kind", name: "Kind", autoWidth: true},
                // { data: "monFac", name: "MonFac", autoWidth: false },
                {
                    data: "monFac", name: "MonFac", autoWidth: false,
                    render: function (data, type, full, meta) {
                        return data.toLocaleString();
                    }
                },
                // { data: "discountKol", name: "DiscountKol", autoWidth: true },

                {
                    data: "discountKol", name: "DiscountKol", autoWidth: true,
                    render: function (data, type, full, meta) {
                        return data.toLocaleString();
                    }
                },

                {data: "mon_After_Discount", name: "Mon_After_Discount", autoWidth: true},
                {data: "monAddedValue", name: "MonAddedValue", autoWidth: true},
                {data: "monPayFac", name: "MonPayFac", autoWidth: true},
                {data: "cash", name: "Cash", autoWidth: false},
                {data: "lendMon", name: "LendMon", autoWidth: false},
                {data: "companyEconomicCode", name: "CompanyEconomicCode", autoWidth: false},
                {data: "pname", name: "pname", autoWidth: false},
                {data: "taxTypeText", name: "TaxTypeText", autoWidth: false},
                {data: "taxType", name: "TaxType", autoWidth: false,visible:false},
                {data: "melliCode", name: "MelliCode", autoWidth: false},
                {data: "economicCode", name: "MelliCode", autoWidth: false},
                {data: "postalCode", name: "PostalCode", autoWidth: false},
                {defaultContent: `<button class="btn btn-link btn-sm">وضعیت</button>`, autoWidth: true},


            ],
        }).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

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

            // 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("اقلام فاکتور: " + value).show();

            $('#myModal').on('shown.bs.modal', function () {
                // $('#myInput').trigger('focus')
            });
            $.ajax({
                url: '?handler=FactorDetails',
                data: {idFactor: rowData.idFactor, idFactorSell: rowData.idFactorSell, kindFactor: rowData.kindFactor},
                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: false,
                        scrollY: 200,
                        columnDefs: [
                            {target: 2, autoWidth: true}
                        ]
                    });
                    modalFactorDetails.show();
                },
                error: function (xhr, status, error) {
                    console.error(error);
                }
            });


        });
        $(modalFactorDetailsElement).on('show.bs.modal', function (event) {
            detailsTable.order([0, 'asc']).draw();
        });
        // open modal for editing the row
        $(".factor-card").on('dblclick', 'table tr', function () {
            var rowId = $(this).closest('tr').attr('data-edit-item');
            let row = $(this).closest('tr');
            changingRow = row;
            let data = datatable.row(row).data();
            if (!data)
                return;
            let typeBillOption = new Option(data.typeBillText, data.typeBill, false, true);
            let typeBillSelect = $('#typeBillSelect');

            // Check if the option already exists
            let existingOption = typeBillSelect.find('option[value="' + data.typeBill + '"]');
            if (existingOption.length) {
                // If the option exists, select it and trigger the change event
                existingOption.prop('selected', true);
                typeBillSelect.trigger('change');
            } else {
                // If the option doesn't exist, append it and select it
                typeBillSelect.append(typeBillOption);
                typeBillOption.prop('selected', true);
            }
            let patternOption = new Option(data.patternText, data.pattern, false, true);
            let subjectOption = new Option(data.subjectBillText, data.subjectBill, false, true);
            let profileOption = new Option(data.profileTitle, data.settingId, false, true);
            let factorIdInput = modalForm.querySelector('[name="id"]');
            let taxIdInput = modalForm.querySelector('[name="taxId"]');
            let kindFactorInput = modalForm.querySelector('[name="kindFactor"]');
            let factorIdBargashtiInput = modalForm.querySelector('[name="idBargashti"]');
            let invoiceDateInput = modalForm.querySelector('[name="invoice_date"]');

            let factorPatternSelect = $('#factorPatternSelect');
            let factorSubjectSelect = $('#factorSubjectSelect');
            let profileSelect = $('#profileSelect');
            let idTaxResponse = $('#idTaxResponse');

            // Check if the pattern option already exists
            let existingPatternOption = factorPatternSelect.find('option[value="' + data.pattern + '"]');
            if (existingPatternOption.length) {
                // If the option exists, select it and trigger the change event
                existingPatternOption.prop('selected', true);
                factorPatternSelect.trigger('change');
            } else {
                // If the option doesn't exist, append it and select it
                factorPatternSelect.append(patternOption);
                patternOption.prop('selected', true);
            }

            // Check if the subject option already exists
            let existingSubjectOption = factorSubjectSelect.find('option[value="' + data.subjectBill + '"]');
            if (existingSubjectOption.length) {
                // If the option exists, select it and trigger the change event
                existingSubjectOption.prop('selected', true);
                factorSubjectSelect.trigger('change');
            } else {
                // If the option doesn't exist, append it and select it
                factorSubjectSelect.append(subjectOption);
                subjectOption.prop('selected', true);
            }
            let existingProfileOption = profileSelect.find('option[value="' + data.settingId + '"]');
            if (existingProfileOption.length) {
                // If the option exists, select it and trigger the change event
                existingProfileOption.prop('selected', true);
                profileSelect.trigger('change');
            }
            // else {
            //     // If the option doesn't exist, append it and select it
            //     let a = profileSelect.find('option[value="0"]');
            //     a.prop('selected',true);
            //     profileSelect.trigger('change');
            //    
            // }

            // Set the value of the id input field
            factorIdInput.value = data.idFactorSell == "0" ? data.idFactor : data.idFactorSell;
            taxIdInput.value = data.taxId;
            factorIdBargashtiInput.value = data.idFactorSell == "0" ? data.idFactorSell : data.idFactor;
            kindFactorInput.value = data["kindFactor"];
            invoiceDateInput.value = data["customInvoiceDate"];
            idTaxResponse.value = data["idTaxResponse"];

            modal.show();
        });

        // datatable.buttons(0, null).container().insertAfter($('#button_container'));
        datatable.columns().every(function () {
            const that = this;
            $('[data-filter-table="search"] input').on('keyup change', function () {
                if (that.search() == this.value) {
                    that.search(this.value).draw();
                }
            });
        });

        // Re-init functions on every table re-draw -- more info: https://datatables.net/reference/event/draw
        datatable.on('draw', function () {
            initToggleToolbar();
            toggleToolbars();
            const links = table.querySelectorAll('tbody button');
            const html = (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>`;
            };
            links.forEach(c => {
                c.addEventListener('click', function (e) {
                    const row = $(c.closest('tbody tr'));
                    // datatable.row().remove().draw();
                    const data = datatable.row(row).data();
                    for (let i = 0; i < validationResults.length; i++) {
                        if (validationResults[i].id == data.idFactor) {

                            let msg = '';

                            if (validationResults[i].messages.length > 0) {
                                for (let j = 0; j < validationResults[i].messages.length; j++) {
                                    msg += html('', validationResults[i].messages[j], 'danger');
                                }

                                $('#message-body').html(msg);
                                modalMessage.show();
                            }
                            break;

                        }
                    }
                });

            });
            // Comment this code because the page will hangs
            //let messagesAll = '';
            //$('#messages_all').html('');
            //for (let i = 0; i < validationResults.length; i++) {
            //    for (let j = 0; j < validationResults[i].messages.length; j++) {
            //        messagesAll += html(validationResults[i].id, validationResults[i].messages[j], 'danger');
            //    }
            //}
            //$('#messages_all').html(messagesAll);
        });
    };
    // 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('click', 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');
            const elementCollapse = document.getElementById('kt_advanced_search_form');
            if (elementCollapse.classList.contains('show')) {
                elementCollapse.classList.toggle('show');
                elementCollapse.blur();
            }
        } 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) {
            clearTimeout(timeout);
            timeout = setTimeout(function () {
                datatable.search(e.target.value).draw();

            }, 800);
        });
    };
    const initComponents = () => {
        //datepicker
        // const dtp1Instance = new mds.MdsPersianDateTimePicker(document.getElementById('datepicker'), {
        //     targetDateSelector: '[data-name="datepicker"]',
        //     isGregorian:false,
        //     persianNumber:true,
        //     rangeSelector:true
        // });


        jalaliDatepicker.startWatch({time: true});

        // $('#visitor-selector').select2({
        //     ajax: {
        //         url: '?handler=getVisitor',
        //         processResults: function (data) {
        //             return {
        //                 results: data
        //             };
        //         }
        //     }
        // })

        const date = new Date();
        const options = {year: 'numeric', month: '2-digit', day: '2-digit', numberingSystem: 'latn'}; // numberingSystem: 'persian' 
        const shamsiDate = date.toLocaleDateString('fa-IR', options);

        const firstDayShamsiDate = date.toLocaleDateString('fa-IR', options);

        const [shamsiyear, shamsimonth, shamsiday] = shamsiDate.split('/');
        const gregorianDate = new Date(`${shamsiyear}-${shamsimonth}-${shamsiday}`);
        gregorianDate.setMonth(gregorianDate.getMonth() + 2);

        // const monthDiff = 0; // difference in months
        // const year = date.getFullYear();
        // const month = date.getMonth() + monthDiff;
        // const firstDay = new Date(year, month - 3, 1);
        // const lastDay = new Date(year, month, 0);
        // const today = new Date();
        // today.setMonth(today.getMonth() - 3);
        // //$('#fromDate').val(shamsiyear+'/01/01');
        // $('#fromDate').val(today.toLocaleDateString('fa-IR', options));
        // //$('#toDate').val(shamsiyear+'/12/29');
        // $('#toDate').val(date.toLocaleDateString('fa-IR', options));
    };
    const handlers = () => {

        const filterProfile = document.querySelector('[data-filter="profile"]');
        $(filterProfile).on('change', e => {
            let value = e.target.value;
            if (value === 'all') {
                value = '';
            }
            datatable.column(10).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(11).search(value).draw();

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

        });
        $('#btnFilter').click(function () {
            datatable.columns(1).search($('#fromDate').val());
            datatable.columns(2).search($('#toDate').val());
            datatable.columns(3).search(document.querySelector('#visitor-selector').value.trim() ?? '');
            datatable.columns(4).search(document.querySelector('#customer-selector').value.trim() ?? '');
            datatable.columns(5).search(document.querySelector('#user-selector').value.trim() ?? '');
            datatable.columns(6).search(document.querySelector('#AzMablaghInput').value.trim() ?? 0);
            datatable.columns(7).search(document.querySelector('#TaMablaghInput').value.trim() ?? 0);
            datatable.columns(8).search(document.querySelector('#factorNumberInput').value.trim() ?? '');
            datatable.columns(9).search(document.querySelector('#officialFactor').checked);
            datatable.columns(12).search(document.querySelector('#noVatInvoiceCheck').checked);

            if (document.querySelector('[data-filter-table="search"]').value == '')
                datatable.search('');
            datatable.draw();
        });
        $('#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();
        });
        $('[data-card-toolbar="send_selected"]').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"]');
            const selectedInvoices = [];
            const backsellIds = [];
            checkboxes.forEach(c => {
                if (c.checked) {
                    const row = $(c.closest('tbody tr'));
                    // datatable.row().remove().draw();
                    const data = datatable.row(row).data();
                    selectedInvoices.push({
                        idFactor: data['idFactor'],
                        idTaxResponse:data['idTaxResponse'],
                        taxId: data['taxId'],
                        idFactorSell: data['idFactorSell'],
                        kindFactor: data['kindFactor'],
                        subjectBill: data['subjectBill']
                    });
                }
            });
            // var selectedIds = datatable.columns().checkboxes.selected()[0];
            showLoading();

            $.ajax({
                url: '?handler=SendingFactor',
                method: 'POST',
                data: {invoices: selectedInvoices},
                headers: {"RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()},
                success: function (response) {
                    const html = (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 msg = "";
                    console.log(response);
                    for (let i = 0; i < response.length; i++) {
                        msg += html(response[i]['factorId'], response[i]['hasError'] ? 'ارسال ناموفق' : 'ارسال موفق', response[i]['hasError'] ? 'danger' : 'success');
                    }
                    document.getElementById('result-body').innerHTML = msg;
                    modalResult.show();
                    hideLoading();
                },
                error: function (x) {
                    console.log(x);
                    hideLoading();

                    swal.fire({
                        title: 'خطا در ارسال',
                        text: x.responseText,
                        icon: 'error',
                        confirmButtonText: 'باشه',
                        customClass: {
                            confirmButton: "btn fw-bold btn-danger",
                        }
                    });

                }
            });
        });


        $(modalElement).on('hidden.bs.modal',
            function () {
                modalShowed = false;
            });
        const submitBtn = modalElement.querySelector('#modal_change_submit');
        submitBtn.addEventListener('click', function (e) {
            e.preventDefault();

            const typeBillSelectId = $('#typeBillSelect').select2('data')[0].id;
            const subjectSelectId = $('#factorSubjectSelect').select2('data')[0].id;
            const patternSelectId = $('#factorPatternSelect').select2('data')[0].id;
            const profileSelectId = $('#profileSelect').select2('data')[0].id;

            if (patternSelectId > 0 && subjectSelectId >> 0 && typeBillSelectId > 0 && profileSelectId > 0) {
                if (!changingRow)
                    return;
                // let text = $('#taxTypeSelect').select2('data')[0].text;
                // datatable.cell(changingRow, 3).data(text).draw();
                // datatable.cell(changingRow, 1).data(id).draw();
                if (submitting)
                    return;
                submitting = true;

                submitBtn.setAttribute('data-kt-indicator', 'on');
                submitBtn.disabled = true;

                modal.hide();
                modalShowed = false;
                $.ajax({
                    url: '?handler=UpdateBill',
                    method: 'post',
                    headers: {"RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()},
                    data: {
                        taxId: modalForm.querySelector('[name="taxId"]').value,
                        factorId: modalForm.querySelector('[name="id"]').value,
                        idTaxResponse: modalForm.querySelector('[name="idTaxResponse"]').value,
                        idBargashti: modalForm.querySelector('[name="idBargashti"]').value,
                        kindFactor: modalForm.querySelector('[name="kindFactor"]').value,
                        invoiceDate: document.getElementById('invoice_date').value,
                        typeBill: typeBillSelectId,
                        pattern: patternSelectId,
                        subject: subjectSelectId,
                        profile: profileSelectId,
                    },
                    success: function (res) {
                        submitting = false;
                        submitBtn.removeAttribute('data-kt-indicator');
                        submitBtn.disabled = false;
                        if (res == true) {
                            toastr.success('تغییرات اعمال شد');
                            document.getElementById('btnFilter').click();
                        } else
                            toastr.error('عدم ثبت تغییرات');
                    },
                    error: function (err) {
                        submitting = false;
                        submitBtn.removeAttribute('data-kt-indicator');
                        submitBtn.disabled = false;
                        toastr.error(err.responseText);

                    }
                });
                //submit to server
            }
        });
    };

    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();
            handleSearchDatatable();
        }
    };
}();


// On document ready
KTUtil.onDOMContentLoaded(function () {
    index.init();
});