var transferInventoryItem = {
    settings: {
        canApprove: '',
        ajaxUrl: '',
        ajaxUrlItemDelivery: '',
        formUrl: '',
        formActionUrl: '',
        doAddUrl: '',
        ajaxUrlDelivery: '',
        formUrlDelivery: '',
        formActionUrlDelivery: '',
        sendUrl: '',
        inventory_autocomplete_url: '',
        ajaxUrlItem: null,
        transferInventory_id: null,
        transferInventoryDeliveryDataList: null,
        transferInventoryItemDataList: null,
        branch_id: null,
        branchTo_id: null,
        transferInventoryItemDeliveryFormAll_url: '',
        transferInventoryItemDeliveryFormAllAction_url: '',
        transferInventoryItemDeliveryForm_url: '',
        transferInventoryItemDeliveryFormAction_url: '',
        itemIdQtys: ''
    },
    init: function() {
        transferInventoryItem.initDataTable();
        transferInventoryItem.bindHrefTransferInventoryItemSend();
        transferInventoryItem.bindHrefTransferInventoryItemForm();
        transferInventoryItem.bindHrefTransferInventoryDeliveryForm();
        transferInventoryItem.bindHrefTransferInventoryItemDeliveryFormAll();
    },
    bindHrefTransferInventoryItemForm: function() {

        if(jQ('.href-transferInventoryItem-form').length > 0) {

            jQ('.href-transferInventoryItem-form').unbind('click').bind('click', function(){

                var requestName = 'transferInventoryItemForm',
                    modal = jQ('#modal'),
                    modalContent = jQ('#modal-content');

                global.ajaxCancel(requestName);

                var settings = {
                    url: transferInventoryItem.settings.formUrl,
                    type: 'GET',
                    data: {
                        transferInventory_id: transferInventoryItem.settings.transferInventory_id,
                        action: jQ(this).data('action'),
                        id: jQ(this).data('id')
                    },
                    beforeSend: function() {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open');
                    },
                    success: function(json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        modal.foundation('open');
                        global.bindFormSubmitted();
                        global.autocomplete.bind(transferInventoryItem.settings.inventory_autocomplete_url, '#transferInventoryItem_inventory_item_description', '#transferInventoryItem_inventory_id');
                        jQ('#transferInventoryItem_inventory_item_description').devbridgeAutocomplete('setOptions', {params: {status: 'Stock On Hand', branch_id: transferInventoryItem.settings.branch_id}});
                        transferInventoryItem.bindHrefTransferInventoryItemAction();
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindHrefTransferInventoryItemAction: function() {

        jQ('.href-transferInventoryItem-action').unbind('click.transferInventoryItemAction').bind('click.transferInventoryItemAction', function(){

            var requestName = 'transferInventoryItemAction',
                modal = jQ('#modal'),
                modalContent = jQ('#modal-content');

            global.formSubmitted();
            global.ajaxCancel(requestName);

            var settings = {
                url: transferInventoryItem.settings.formActionUrl,
                type: 'POST',
                data: jQ('#form-transferInventoryItem').serialize(),
                success: function(json) {
                    global.formSubmittedReverse();
                    if(json.success) {
                        transferInventoryItem.settings.transferInventoryItemDataList.draw();
                        global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'success', json.successMessages);
                        modal.foundation('close');
                    } else {
                        global.parseFlashMessages('#flash-messages-content-modal', 'alert', json.errorMessages);
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindHrefTransferInventoryItemSend: function() {

        /*if(jQ('#href-transferInventory-send').length > 0) {

            jQ('#href-transferInventory-send').unbind('click').bind('click', function(){

                if(confirm('Are you sure you want to send this transaction?')) {

                    var requestName = 'transferInventorySend',
                        modal = jQ('#modal'),
                        modalContent = jQ('#modal-content');

                    global.ajaxCancel(requestName);

                    var settings = {
                        url: transferInventoryItem.settings.sendUrl,
                        type: 'POST',
                        data: {
                            transferInventory_id: transferInventoryItem.settings.transferInventory_id
                        },
                        beforeSend: function() {
                            modalContent.html('').addClass('has-loading');
                            modal.foundation('open');
                        },
                        success: function(json) {
                            if(json.success) {
                                location.reload();
                            } else {
                                global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'alert', json.errorMessages);
                                modal.foundation('close');
                            }
                        }
                    };

                    global.ajax(settings, requestName);
                }
            });
        }*/

        jQ('#btn-send-ask-modal-continue').unbind('click').bind('click', function(){

            var requestName = 'transferInventorySend',
                modal = jQ('#modal'),
                modalContent = jQ('#modal-content'),
                _form = jQ('#form-transferInvItem');
            global.ajaxCancel(requestName);

            var settings = {
                url: transferInventoryItem.settings.sendUrl,
                type: 'POST',
                data: {
                    form: _form.serializeArray(),
                    transferInventory_id: transferInventoryItem.settings.transferInventory_id
                },
                beforeSend: function() {
                    modalContent.html('').addClass('has-loading');
                    modal.foundation('open');
                },
                success: function(json) {
                    if(json.success) {
                        location.reload();
                    } else {
                        global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'alert', json.errorMessages);
                        modal.foundation('close');
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindHrefTransferInventoryDeliveryForm: function() {

        if(jQ('.href-transferInventoryDelivery-form').length > 0) {

            jQ('.href-transferInventoryDelivery-form').unbind('click').bind('click', function(){

                var requestName = 'transferInventoryDeliveryForm',
                    modal = jQ('#modal'),
                    modalContent = jQ('#modal-content');

                global.ajaxCancel(requestName);

                var settings = {
                    url: transferInventoryItem.settings.formUrlDelivery,
                    type: 'GET',
                    data: {
                        transferInventory_id: transferInventoryItem.settings.transferInventory_id,
                        action: jQ(this).data('action'),
                        id: jQ(this).data('id')
                    },
                    beforeSend: function() {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open');
                    },
                    success: function(json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        modal.foundation('open');
                        global.bindFormSubmitted();
                        global.draggableReveal();
                        global.maskInput();
                        jQ('#transferInventoryItem-datalist-forDelivery').DataTable({
                            paging: false,
                            ordering: false,
                            searching: false,
                            info: false
                        });
                        transferInventoryItem.bindHrefTransferInventoryDeliveryAction();
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindHrefTransferInventoryDeliveryAction: function() {

        jQ('.href-transferInventoryDelivery-action').unbind('click.transferInventoryDeliveryAction').bind('click.transferInventoryDeliveryAction', function(){

            var requestName = 'transferInventoryDeliveryAction',
                modal = jQ('#modal'),
                modalContent = jQ('#modal-content');

            global.formSubmitted();
            global.ajaxCancel(requestName);

            var settings = {
                url: transferInventoryItem.settings.formActionUrlDelivery,
                type: 'POST',
                data: jQ('#form-transferInventoryDelivery').serialize(),
                success: function(json) {
                    global.formSubmittedReverse();
                    if(json.success) {
                        //transferInventoryItem.settings.transferInventoryDeliveryDataList.draw();
                        //transferInventoryItem.settings.transferInventoryItemDataList.draw();
                        global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'success', json.successMessages);
                        modal.foundation('close');
                        location.reload();
                    } else {
                        global.parseFlashMessages(global.settings.vars.flashMessagesContentId, 'alert', json.errorMessages);
                        //global.parseFlashMessages('#flash-messages-content-modal', 'alert', json.errorMessages);
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindHrefTransferInventoryItemDeliveryFormAll: function() {

        if(jQ('#href-transferInventoryItemDelivery-formAll').length > 0) {

            jQ('#href-transferInventoryItemDelivery-formAll').unbind('click').bind('click', function(){

                var requestName = 'transferInventoryItemDeliveryFormAll',
                    modal = jQ('#modal'),
                    modalContent = jQ('#modal-content');

                global.ajaxCancel(requestName);

                var settings = {
                    url: transferInventoryItem.settings.transferInventoryItemDeliveryFormAll_url,
                    type: 'GET',
                    data: {
                        transferInventory_id: transferInventoryItem.settings.transferInventory_id
                    },
                    beforeSend: function() {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open');
                    },
                    success: function(json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        global.bindFormSubmitted();
                        transferInventoryItem.bindHrefTransferInventoryItemDeliveryActionAll();
                        jQ('#transferInventoryItemList-datalist').DataTable({
                            'searching': false,
                            'paging': false,
                            'columnDefs': [
                                {'orderable': false, 'targets': [0, 1, 2, 3]}
                            ]
                        });
                        global.maskInput();
                        modal.foundation('open');
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindHrefTransferInventoryItemDeliveryActionAll: function() {

        jQ('#href-transferInventoryItemDelivery-actionAll').unbind('click.transferInventoryItemDeliveryActionAll').bind('click.transferInventoryItemDeliveryActionAll', function(){

            var requestName = 'transferInventoryItemDeliveryActionAll';

            global.formSubmitted();
            global.ajaxCancel(requestName);

            var settings = {
                url: transferInventoryItem.settings.transferInventoryItemDeliveryFormAllAction_url,
                type: 'POST',
                data: jQ('#form-transferInventoryItemDelivery').serialize(),
                success: function(json) {
                    if(json.success) {
                        location.reload();
                    } else {
                        global.parseFlashMessages('#flash-messages-content-modal', 'alert', json.errorMessages);
                        global.formSubmittedReverse();
                    }
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                }
            };

            global.ajax(settings, requestName);
        });
    },
    bindHrefTransferInventoryItemDeliveryForm: function() {

        if(jQ('.href-transferInventoryItemDelivery-form').length > 0) {

            jQ('.href-transferInventoryItemDelivery-form').unbind('click').bind('click', function(){

                var requestName = 'transferInventoryFormItemDelivery',
                    modal = jQ('#modal'),
                    modalContent = jQ('#modal-content');

                global.ajaxCancel(requestName);

                var settings = {
                    url: transferInventoryItem.settings.transferInventoryItemDeliveryForm_url,
                    type: 'GET',
                    data: {
                        transferInventoryItem_id: jQ(this).data('ref-id'),
                        action: jQ(this).data('action'),
                        id: jQ(this).data('id')
                    },
                    beforeSend: function() {
                        modalContent.html('').addClass('has-loading');
                        modal.foundation('open');
                    },
                    success: function(json) {
                        modal.foundation('close');
                        modalContent.removeClass('has-loading').html(json.html);
                        global.bindFormSubmitted();
                        modal.foundation('open');
                        transferInventoryItem.bindHrefTransferInventoryItemDeliveryAction();
                    }
                };

                global.ajax(settings, requestName);
            });
        }
    },
    bindHrefTransferInventoryItemDeliveryAction: function() {

        jQ('.href-transferInventoryItemDelivery-action').unbind('click.transferInventoryItemDeliveryAction').bind('click.transferInventoryItemDeliveryAction', function(){

            var requestName = 'transferInventoryItemDeliveryAction';

            global.formSubmitted();
            global.ajaxCancel(requestName);

            var settings = {
                url: transferInventoryItem.settings.transferInventoryItemDeliveryFormAction_url,
                type: 'POST',
                data: jQ('#form-transferInventoryItemDelivery').serialize(),
                success: function(json) {
                    if(json.success) {
                        location.reload();
                    } else {
                        global.parseFlashMessages('#flash-messages-content-modal', 'alert', json.errorMessages);
                        global.formSubmittedReverse();
                    }
                }
            };

            global.ajax(settings, requestName);
        });
    },
    doAddItem: function() {
        var _self = jQ(this),
            settings = {
                url: transferInventoryItem.settings.doAddUrl,
                type: 'POST',
                data: {
                    transferInventory_id:  transferInventoryItem.settings.transferInventory_id,
                    id: jQ(this).data('id'),
                    quantity:  jQ('#addItemForm-qty-'+ jQ(this).data('key')).val(),
                    note:  jQ('#addItemForm-note-'+ jQ(this).data('key')).val(),
                    consumable:  jQ('#addItemForm-consumable-'+ jQ(this).data('key')).is(":checked"),
                },
                beforeSend: function() {
                    _self.parent().addClass('autocomplete-loading');
                },
                error: function() {
                    alert('Something went wrong. Please try again or contact the administrator.');
                    _self.parent().removeClass('autocomplete-loading');
                },
                success: function(result) {
                    if(!result.success){
                        alert(result.messages);
                        _self.parent().removeClass('autocomplete-loading');
                    } else {
                        transferInventoryItem.settings.transferInventoryItemDataList.draw();
                        _self.parent().removeClass('autocomplete-loading');
                    }
                }
            };
        global.ajax(settings, 'Do Add Item');
    },
    doRemoveItem: function() {
        var _self = jQ(this),
            settings = {
                url: transferInventoryItem.settings.doRemoveUrl,
                type: 'POST',
                data: {
                    id: jQ(this).data('id')
                },
                beforeSend: function() {
                    _self.parent().addClass('autocomplete-loading');
                },
                error: function() {
                    alert('Something went wrong. Please try again or contact the administrator.');
                    _self.parent().removeClass('autocomplete-loading');
                },
                success: function() {
                    transferInventoryItem.settings.transferInventoryItemDataList.draw();
                    _self.parent().removeClass('autocomplete-loading');
                }
            };
        global.ajax(settings, 'Do Remove Item');
    },
    initDataTable: function() {

        var callBack = function() {
            // transferInventoryItem.bindHrefTransferInventoryItemForm();
            jQ('.href-transferInventoryItem-remove').unbind('click').bind('click', transferInventoryItem.doRemoveItem);
        };

        transferInventoryItem.settings.transferInventoryItemDataList = jQ('#transferInventoryItem-datalist').DataTable({
            'processing': true,
            'serverSide': true,
            'ajax': {
                'url': transferInventoryItem.settings.ajaxUrl,
                'data': function(d) {
                    d.transferInventory_id = transferInventoryItem.settings.transferInventory_id;
                }
            },
            'columnDefs': [
                { 'orderable': false, 'targets': jQ('#transferInventoryItem-datalist th').length - 1 },
                { 'searchable': false, 'targets':  jQ('#transferInventoryItem-datalist th').length - 1 }
            ],
            drawCallback: callBack,
            responsive: {
                details: {
                    renderer: function(api, rowIdx) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBack);
                    }
                }
            },
            createdRow: function(tr, data) {
                const jqTr = jQ(tr);
                jQ(jqTr.children()[1]).addClass('text-right');
                jQ(jqTr.children()[2]).addClass('text-right');
                jQ(jqTr.children()[3]).addClass('text-right');
                jQ(jqTr.children()[4]).addClass('text-right');
                jQ(jqTr.children()[jQ('#transferInventoryItem-datalist th').length - 1]).addClass('text-center');
            }
        });

        jQ('#materialRequisition-datalist').DataTable({
            paging: false,
            ordering: false,
            searching: false,
            info: false
        });

        jQ('#transferInventoryStatusHistory-datalist').DataTable({
            paging: false,
            ordering: false,
            searching: false,
            info: false
        });

        if(jQ('#transferInventoryDelivery-datalist').length) {

            const callBackDelivery = function() {
                transferInventoryItem.bindHrefTransferInventoryDeliveryForm();
            };

            transferInventoryItem.settings.transferInventoryDeliveryDataList = jQ('#transferInventoryDelivery-datalist').DataTable({
                'processing': true,
                'serverSide': true,
                'ajax': {
                    'url': transferInventoryItem.settings.ajaxUrlDelivery,
                    'data': function(d) {
                        d.transferInventory_id = transferInventoryItem.settings.transferInventory_id;
                    }
                },
                'columnDefs': [
                    { 'orderable': false, 'targets': [1, 2, 3] },
                    { 'searchable': false, 'targets': [1, 2, 3] }
                ],
                order: [[1, 'desc']],
                drawCallback: callBackDelivery,
                responsive: {
                    details: {
                        renderer: function(api, rowIdx) {
                            return global.dataTableResponsiveCallBack(api, rowIdx, callBackDelivery);
                        }
                    }
                },
                createdRow: function(tr) {
                    //jQ(jQ(tr).children()[1]).addClass('text-right');
                }
            });
        }

        if(jQ('#transferInventoryItemDelivery-datalist').length > 0) {

            var callBackItemDelivery = function() {
                transferInventoryItem.bindHrefTransferInventoryItemDeliveryForm();
            };

            transferInventoryItem.settings.transferInventoryItemDeliveryDataList = jQ('#transferInventoryItemDelivery-datalist').DataTable({

                'processing': true,
                'serverSide': true,
                'ajax': {
                    'url': transferInventoryItem.settings.ajaxUrlItemDelivery,
                    'data': function(d) {
                        d.transferInventory_id = transferInventoryItem.settings.transferInventory_id;
                    }
                },
                'columnDefs': [
                    { 'orderable': false, 'targets': 3 },
                    { 'searchable': false, 'targets': 3 }
                ],
                drawCallback: callBackItemDelivery,
                responsive: {
                    details: {
                        renderer: function( api,rowIdx ) {
                            return global.dataTableResponsiveCallBack(api, rowIdx, callBackItemDelivery);
                        }
                    }
                },
                createdRow: function(tr) {
                    jQ(jQ(tr).children()[2]).addClass('text-right');
                }
            });
        }

        const callBackItem = function() {
            jQ('.href-item-add').unbind('click').bind('click', transferInventoryItem.doAddItem);
            global.maskInput();
        };

        const datalistItem = jQ('#item-datalist').DataTable({
            'processing': true,
            'serverSide': true,
            'ajax': {
                'url': transferInventoryItem.settings.ajaxUrlItem,
                'data': function(d) {
                    d.branchId = transferInventoryItem.settings.branchTo_id;
                    d.itemCategory_id = jQ('#addItemFormFilter-itemCategory').val();
                    d.itemIdQtys = JSON.parse(transferInventoryItem.settings.itemIdQtys);
                }
            },
            'columnDefs': [
                { 'orderable': false, 'targets': [1,2,3] },
                { 'searchable': false, 'targets': [1,2,3] }
            ],
            //ordering: false,
            drawCallback: callBackItem,
            responsive: {
                details: {
                    renderer: function( api,rowIdx ) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBackItem);
                    }
                }
            }
        });

        jQ('#addItemFormFilter-itemCategory').unbind('change').bind('change', datalistItem.draw);

        jQ('.content-container').removeClass('has-loading'); jQ('.content-container-content').removeClass('hide');
    }
};