var materialRequisitionItem = {
    settings: {
        ajaxUrl: '',
        formUrl: '',
        formActionUrl: '',
        sendUrl: '',
        voidUrl: '',
        viewUrl: '',
        item_autocomplete_url: '',
        location_autocomplete_url: '',
        item_category_autocomplete_url: '',
        materialRequisition_id: null,
        branch_id: null,
        materialRequisitionItemDataList: null,
        item_ajax_list_material_requisition_url: null,
        removeItem_url: null
    },
    init: function() {
        materialRequisitionItem.setModalStyle();
        materialRequisitionItem.initDataTable();
        materialRequisitionItem.bindHrefMaterialRequisitionItemForm();
        materialRequisitionItem.bindHrefMaterialRequisitionItemSend();
        materialRequisitionItem.bindHrefMaterialRequisitionVoid();
    },

    setModalStyle : function() {
        jQ(window).on(
            // 'open.zf.reveal', function () { jQ('.reveal').css({ 'width' : '800px', 'left' : '45px' }); }
        );
    },

    bindHrefMaterialRequisitionItemForm: function() {

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

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

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

                global.ajaxCancel(requestName);

                var settings = {
                    url: materialRequisitionItem.settings.formUrl,
                    type: 'GET',
                    data: {
                        materialRequisition_id: materialRequisitionItem.settings.materialRequisition_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');
                        modal.css('top', (jQ(window).scrollTop() + 50) + 'px').css('margin-top', '0');
                        global.bindFormSubmitted();
                        //global.autocomplete.bind(materialRequisitionItem.settings.item_autocomplete_url, '#materialRequisitionItem_item_description', '#materialRequisitionItem_item_id');
                        global.autocomplete.bind(
                            materialRequisitionItem.settings.location_autocomplete_url,
                            '#default_location_description',
                            '#default_location_id',
                            {
                                onSelect : function(s){
                                    jQ('.item-location-id').val(s.id);
                                    jQ('.item-location-description').val(s.value);

                                }
                            }
                        );

                        global.autocomplete.bind(
                            materialRequisitionItem.settings.item_category_autocomplete_url,
                            '#item_category_description',
                            '#item_category_id',
                            {
                                onSelect : function(){
                                    datalist.draw();
                                }
                            }
                        );
                      //  jQ('#materialRequisitionItem_location_description').devbridgeAutocomplete('setOptions', {params: {branchId: materialRequisitionItem.settings.branch_id}});
                      //  materialRequisitionItem.bindHrefMaterialRequisitionItemAction();


                        var callBackItem = function() {
                            jQ('.href-item-add').unbind('click').bind('click', materialRequisitionItem.doAddItem);
                            jQ('.href-get-item-location').unbind('click').bind('click',function(){
                                global.autocomplete.bind(materialRequisitionItem.settings.location_autocomplete_url, '#item-location-description-' + jQ(this).data('key'), '#item-location-id-' + jQ(this).data('key'));

                            });
                            if(jQ('.amount').length > 0) jQ('.amount').maskMoney();
                            jQ('.item-location-id').val(jQ('#default_location_id').val());
                            jQ('.item-location-description').val(jQ('#default_location_description').val());


                            jQ('#item-datalist').delegate('.itemForm-computeTotalPrice','keyup',function(){
                                console.log(jQ('.itemForm-computeTotalPrice').length);
                                const _this = this,
                                        tr = jQ(_this).parent().parent();
                                let initialPrice = global.parseNum(tr.find('input[id^=addItemForm-initial-price]').val()),
                                    tax = global.parseNum(tr.find('input[id^=addItemForm-tax]').val()),
                                    totalPrice = initialPrice + (initialPrice * (tax/100));
                                tr.find('input[id^=addItemForm-price]').val(global.numWithCommasAndDecimal(totalPrice));
                            });

                        };

                        var datalist = jQ('#item-datalist').DataTable({
                            'processing': true,
                            'serverSide': true,
                            'ajax': {
                                'url': materialRequisitionItem.settings.item_ajax_list_material_requisition_url,
                                'data': function(d) {
                                    d.branchId = materialRequisitionItem.settings.branch_id;
                                    d.itemCategory_id = jQ('#addItemFormFilter-itemCategory').val();
                                    d.supplier_id = jQ('#addItemFormFilter-supplier').val();
                                }
                            },
                            'columnDefs': [
                                { 'orderable': false, 'targets': [2,3,4,5,6,7,8] },
                                { 'searchable': false, 'targets': [2,3,4,5,6,7,8] }
                            ],
                            drawCallback: function() {
                                callBackItem();
                                global.maskInput();
                            },
                            responsive: {
                                details: {
                                    renderer: function( api,rowIdx ) {
                                        return global.dataTableResponsiveCallBack(api, rowIdx, callBackItem);
                                    }
                                }
                            }
                        });

                        jQ('#addItemFormFilter-itemCategory').unbind('change').bind('change', datalist.draw);
                        jQ('#addItemFormFilter-supplier').unbind('change').bind('change', datalist.draw);
                    }
                };

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

        jQ('.href-materialRequisitionItem-action').unbind('click.materialRequisitionItemAction').bind('click.materialRequisitionItemAction', function(){

            var requestName = 'materialRequisitionItemAction',
                modal = jQ('#modal');

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

            var settings = {
                url: materialRequisitionItem.settings.formActionUrl,
                type: 'POST',
                data: jQ('#form-materialRequisitionItem').serialize(),
                success: function(json) {
                    global.formSubmittedReverse();
                    if(json.success) {
                        materialRequisitionItem.settings.materialRequisitionItemDataList.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);
        });
    },
    bindHrefMaterialRequisitionItemSend: function() {

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

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

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

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

                    global.ajaxCancel(requestName);

                    var settings = {
                        url: materialRequisitionItem.settings.sendUrl,
                        type: 'POST',
                        data: {
                            materialRequisition_id: materialRequisitionItem.settings.materialRequisition_id
                        },
                        beforeSend: function() {
                            modalContent.html('').addClass('has-loading');
                            modal.foundation('open');
                        },
                        success: function(json) {
                            if(json.success) {
                                //location.href = global.settings.url + materialRequisitionItem.settings.viewUrl + '/' + materialRequisitionItem.settings.materialRequisition_id;
                                location.href = materialRequisitionItem.settings.viewUrl + '/' + materialRequisitionItem.settings.materialRequisition_id;
                            } 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 = 'materialRequisitionSend',
                modal = jQ('#modal'),
                modalContent = jQ('#modal-content');

            global.ajaxCancel(requestName);

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

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

        if(jQ('#href-materialRequisition-void').length > 0) {

            jQ('#href-materialRequisition-void').unbind('click').bind('click', function(){

                if(confirm('Are you sure you want to void this request?')) {

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

                    global.ajaxCancel(requestName);

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

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

        var callBack = function() {
            materialRequisitionItem.bindHrefMaterialRequisitionItemForm();
            jQ('.href-materialRequisitionItem-remove').unbind('click').bind('click', materialRequisitionItem.doRemoveItem);
            global.maskInput();
        };

        materialRequisitionItem.settings.materialRequisitionItemDataList = jQ('#materialRequisitionItem-datalist').DataTable({
            
            'processing': true,
            'serverSide': true,
            'ajax': {
                'url': materialRequisitionItem.settings.ajaxUrl,
                'data': function(d) {
                    d.materialRequisition_id = materialRequisitionItem.settings.materialRequisition_id;
                }
            },
            'columnDefs': [
                { 'orderable': false, 'targets': 6 },
                { 'searchable': false, 'targets': 6 }
            ],
            drawCallback: function() {
                callBack();
            },
            responsive: {
                details: {
                    renderer: function( api,rowIdx ) {
                        return global.dataTableResponsiveCallBack(api, rowIdx, callBack);
                    }
                }
            }
        });

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

    doAddItem: function() {
        var _self = jQ(this),
            settings = {
                url: materialRequisitionItem.settings.formActionUrl,
                type: 'POST',
                data: {
                    materialRequisition_id:  materialRequisitionItem.settings.materialRequisition_id,
                    id: jQ(this).data('id'),
                    //location: jQ('#item-location-id-' + jQ(this).data('key')).val(),
                    /*itemQuantities: function(){

                        var itemQuantities = [];
                        jQ('.item_quantities-' + _self.data('key')).each(function(){
                            itemQuantities.push({
                               quantity : jQ(this).val(),
                               item_unit_measurement_id : jQ(this).data('item_measurement_id')
                            });
                        });

                        return JSON.stringify(itemQuantities);
                    },*/
                    //unitOfMeasurement: jQ('#item-unit-of-measurement-'+ jQ(this).data('key')).val(),
                    quantity:  jQ('#addItemForm-qty-'+ jQ(this).data('key')).val(),
                    price:  jQ('#addItemForm-price-'+ jQ(this).data('key')).val(),
                    note:  jQ('#addItemForm-note-'+ jQ(this).data('key')).val(),
                    initialPrice:  jQ('#addItemForm-initial-price-'+ jQ(this).data('key')).val(),
                    tax:  jQ('#addItemForm-tax-'+ jQ(this).data('key')).val(),
                    //adjustedCost :  jQ('#item-adjusted-cost-'+ jQ(this).data('key')).val(),
                    //controlNo: jQ('#item-control-no-' + jQ(this).data('key')).val(),
                    //defaultLocation: jQ('#default_location_id').val()
                },
                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 {
                        materialRequisitionItem.settings.materialRequisitionItemDataList.draw();
                        _self.parent().removeClass('autocomplete-loading');
                    }
                }
            };
        global.ajax(settings, 'Do Add Item');
    },


    doRemoveItem: function() {
        var _self = jQ(this),
            settings = {
                url: materialRequisitionItem.settings.removeItem_url,
                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() {
                    materialRequisitionItem.settings.materialRequisitionItemDataList.draw();
                    _self.parent().removeClass('autocomplete-loading');
                }
            };
        global.ajax(settings, 'Do Add Item');
    },
};