"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;
    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 = () => {

        // Init datatable --- more info on datatables: https://datatables.net/manual/
        datatable = $(table).DataTable({
            language: {
                url: '/media/fa.json'
            },
            ajax: {
                url: "?handler=StuffList",
                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(err);
                },
            },
            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}, // Disable ordering on column 0 (checkbox)
                {
                    targets: 3,
                    data: 'isDifferent',
                    render: function (data) {
                        if (data) {
                            return '<span class="badge badge-danger"><i class="fas fa-times-circle text-white"></i>&nbsp;&nbsp;بله</span>';
                        } else {
                            return '<span class="badge badge-success"><i class="fas fa-check-circle text-white"></i>&nbsp;&nbsp;خیر</span>';
                        }
                    }
                },

            ],
            columns: [

                {data: "id", name: "Id", autoWidth: false},
                {data: "editDateFa", name: "EditDateFa", autoWidth: false},
                {data: "typeStuffId", name: "TypeStuffId", autoWidth: true},
                {data: "isDifferent", name: "IsDifferent", autoWidth: false},
                {data: "descript", name: "Descript", autoWidth: false},

                {data: "vatRate", name: "VatRate", autoWidth: false},
                //{data: "special", name: "Special", autoWidth: false},
                // {data: "vatCustomPurpose", name: "VatCustomPurpose", autoWidth: false,visible: 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 () {
            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();
                    return;
                    $.ajax({
                        url: '?handler=change',
                        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


    // 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) {
            datatable.search(e.target.value).draw();
        });
    };

    // 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(3).search(value).draw();
        });
    }
    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();
        });
        $(modalElement).on('hidden.bs.modal',
            function () {
                modalShowed = false;
            });
    };
    return {
        // Public functions  
        init: function () {
            if (!table) {
                return;
            }
            initTable();
            handlers();
            // handleStatusFilter();
            handleSearchDatatable();
        }
    };
}();


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