"use strict";

const index = function () {
    const table = document.getElementById('factor-table');
    let datatable;
    let toolbarBase;
    let toolbarSelected;
    let selectedCount;
    let modalElement = document.getElementById('modal_change');
    let modalForm = modalElement.querySelector('#modal_change_form');
    let modal = new bootstrap.Modal(modalElement);
    let changingRow;
    let modalShowed = false;
    const materialLoadingElement = $("#materialLoading");

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

    function hideLoading() {
        materialLoadingElement.addClass('hide');
        materialLoadingElement.removeClass('show');
    }
    let initTable = () => {

        // Init datatable --- more info on datatables: https://datatables.net/manual/
        datatable = $(table).DataTable({
            language: {
                url: '/media/fa.json'
            },
            ajax: {
                url: "?handler=InvoiceList",
                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));
                    return inData;
                },
                error: function (err, status) {
                    // what error is seen(it could be either server side or client side.
                    console.log('Error: ' + err.responseText);
                },
            },
            pageLength: 50,
            stateSave: true,
            autoWidth: true,
            processing: true,
            serverSide: true,
            scrollY: "70vh",
            scrollX: true,
            scrollCollapse: true,
            fixedHeader: true,
            fixedColumns: {
                left: 1,
                right: 1
            },
            filter: true,
            order: [],
            columnDefs: [
                {
                    orderable: false,
                    targets: 0
                },

                {
                    targets: 4,
                    data: 'statusText',
                    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');
                        }
                    }
                },

            ],
            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, visible: false},
                {data: "idLink", name: "IdLink", autoWidth: false},
                {data: "taxId", name: "TaxId", autoWidth: false},
                {data: "statusText", name: "StatusText", autoWidth: true},
                {data: "invoiceDate", name: "InvoiceDate", autoWidth: false},
                {data: "sendDate", name: "SendDate", autoWidth: false},
                {data: "idFactor", name: "IdFactor", autoWidth: false},
                {defaultContent: `<button class="btn btn-link btn-sm">اعمال تغییر</button>`, autoWidth: false},
            ],
        });

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

        // Re-init functions on every table re-draw -- more info: https://datatables.net/reference/event/draw
        datatable.on('draw', function () {
            initToggleToolbar();
            toggleToolbars();
            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();


                });

            });
        });
    };
    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');
        } else {
            toolbarBase.classList.remove('d-none');
            toolbarSelected.classList.add('d-none');
        }
    };
    let handlers = () => {
        const filterSearch = document.querySelector('[data-filter-table="search"]');
        filterSearch.addEventListener('keyup', function (e) {
            if (datatable)
                datatable.search(e.target.value).draw();
        });
        $('#btnFilter').click(function () {
            datatable.columns(1).search($('[data-filter="database"]').val());
            if (document.querySelector('[data-filter-table="search"]').value == '')
                datatable.search('');
            datatable.draw();
        });
        $(modalElement).on('hidden.bs.modal',
            function () {
                modalShowed = false;
            });
        // const filterStatus = document.querySelector('[data-filter="database"]');
        // $(filterStatus).on('change', e => {
        //     let value = e.target.value;
        //     if (!value) {
        //         return;
        //     }
        //     if (datatable)
        //         datatable.column(3).search(value).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 taxIds = [];

            checkboxes.forEach(c => {
                if (c.checked) {
                    const row = $(c.closest('tbody tr'));
                    // datatable.row().remove().draw();
                    const data = datatable.row(row).data();
                    taxIds.push(data['taxId']);
                }
            });
            const request = {
                taxIds: taxIds,
                database: $('[data-filter="database"]').val()
            }
            // var selectedIds = datatable.columns().checkboxes.selected()[0];
            showLoading();

            $.ajax({
                url: '?handler=CopyInvoiceList',
                method: 'POST',
                data: {request},
                headers: {"RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()},
                success: function (response) {
                   
                    if (response.length > 0) {
                        document.getElementById('btnFilter').click();
                    } else {
                        toastr.warning('پاسخی دریافت نشد');
                    }
                    hideLoading();
                },
                error: function (x) {
                    console.log(x);
                    hideLoading();

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

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


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