var SalesFormView = Backbone.View.extend({
    itemMapping: {},
    itemMapping2: {},
    itemMapping3: {},
    itemTypeModal: {},
    prefillState: false,
    itemsAutocomplete: {},
    that: this,

    styles: [
        'ap-blue',
    ],

    salesStyleMapping: {},

    events: {
        //'click .card-panel-entity': 'highlightCard',
        'click #byItem': 'byItem',
        'click #byType': 'byType',
        'click #byCategory': 'byCategory',
        'click #everyDay': 'everyDay',
        'click #certainDays': 'certainDays',
        'click #allDay': 'allDay',
        'click #certainTimes': 'certainTimes',
        'click .select-item-type': 'selectItemType',
        'click .select-item-category': 'selectItemCategory',
        'click .item-type-card' : 'chooseItemType',
        'click .item-category-card' : 'chooseItemCategory',
        'click .autocomplete-content li': 'selectItemFromAutocompleteList',
        'keyup #items': 'searchItemBySearchTerm',
        'click .remove-quantity-price': 'removeQuantityPriceRow',
        'click .add-quantity-price': 'addQuantityPriceRow',
        'change #sale-type-dropdown' : 'onSaleTypeChange'
    },

    initialize: async function (options) {
        this.options = options;
        this.template = _.template(options.template);
        this.model = options.model;
        this.sales = options.sales;
        this.qualifyingQtyType = options.qualifyingQtyType;
        this.dataType = options.dataType;
        this.isNew = options.isNew;
        await this.getItemTypesFull();
        await this.getItemCategoriesFull();
        this.renderItemTypes();

    },

    render: function () {
        var that = this;
        this.$el.detach();


        $(document).ready(function() {
            $('.tooltipped').tooltip();       
            $('select').formSelect();
            var pickerElement = document.querySelectorAll('.datepicker');
            var instances = M.Datepicker.init(pickerElement, {
                autoClose: true,
                container: 'body',
                i18n: App.i18n,
                isRTL: App.rtl,
                format: 'yyyy-mm-dd'
            });
            that.datepicker = instances;
        });
        
        return this;
    },

    highlightCard: function (e) {
        this.$el.find('.edit').hide();
        this.$el.find('.card-panel-entity').removeClass('active');
        var element = $(e.currentTarget);
        var selected = $(element).attr('data-selected') === '1';
        if (selected) {
            $(element).removeAttr('data-selected');
            $(element).removeClass('active');
            $(element).find('.edit').hide();
        } else {
            $(element).removeAttr('data-selected');
            $(element).attr('data-selected', '1');
            $(element).find('.edit').css('display','block');
            $(element).addClass('active');
        }
    },

    searchItemBySearchTerm: function(element) {
        var element = $(element.currentTarget);
        var searchTerm = $(element).val();
        var that = this;
        if (searchTerm.trim().length > 0) {
            if (this.timer) {
                clearTimeout(this.timer);
            }
            this.timer = setTimeout(function() { 
                that.getItemsBySearchTerm(searchTerm); 
            }, 400);
        }
        // that.$el.find("input.autocomplete").trigger("click");
    },

    selectItemFromAutocompleteList: function (selection) {
        var that = this;
        var itemId = document.getElementById('items');
        var itemDescription = document.getElementById('itemDescription');

        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };
        
        for (var i = 0; i < Object.size(that.itemMapping); i++) {
            if (Object.entries(that.itemMapping)[i][0] == selection) {
                itemId.value = Object.entries(that.itemMapping)[i][1].id;
                itemDescription.value = Object.entries(that.itemMapping)[i][1].description;
            }
        }
    },

    getItemsBySearchTerm: function(searchTerm) {
        var that = this;
        var sessionToken = this.getCookie();
        if (App.israCardBuild) {
            searchTerm = CryptoJS.enc.Utf8.parse(searchTerm);
        }
        $.ajax({
            url: '/data/get-items-by-search-term',
            data: {
                searchTerm: searchTerm,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                var results = data.results;
                var items = {};
                for (var i = 0; i < results.length; i++) {
                    items[results[i].itemCode] = null;
                    that.itemMapping[results[i].itemCode] = { description: results[i].itemDescription, id: results[i].itemCode };
                }
                that.itemsAutocomplete.updateData(items);
                that.itemsAutocomplete.open();
                // that.$el.find("input.autocomplete").trigger("click");
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },

    getCookie: function() {
        var nameEQ = "sessionCookie" + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
    },

    // initItemTypes: async function () {
    //     this.fullItemTypes = this.getItemTypesFull();
    // },
    
    getItemTypesFull: async function () {
        var that = this;
        var sessionToken = this.getCookie();
        return $.ajax({
            url: '/data/get-item-types',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.itemTypes = data.results;
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({
                        html: '{Literal}There was a problem fetching data from the server{/Literal}'
                    });
                }
            }
        });
    },

    getItemCategoriesFull: async function () {
        var that = this;
        var sessionToken = this.getCookie();
        return $.ajax({
            url: '/data/get-category',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                that.itemCategories = data.results;
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({
                        html: '{Literal}There was a problem fetching data from the server{/Literal}'
                    });
                }
            }
        });
    },


    renderItemTypes: function () {
        var that = this;
        var itemCollection = new SalesCollection();
        var data = this.itemTypes;
        for (var i = 0; i < data.length; i++) {
            var currentItemType = data[i];
            currentItemType.cardStyleClass = that.salesStyleMapping[data[i].name];
            itemCollection.add(new Sales(currentItemType));
        }

        this.itemTypesFullCollection = itemCollection;

        this.$el.html(that.template({
            sales: that.model.toJSON(),
            itemTypes: that.itemTypesFullCollection.toJSON(),
            itemCategories: that.itemCategories,
            qualifyingQtyType: this.qualifyingQtyType,
            dataType: this.dataType,
            isNew: this.isNew
        }));

        var elems = document.querySelector('#items');
        this.itemsAutocomplete = M.Autocomplete.init(elems, {
            minLength: 1,
            limit: 20,
            sortFunction: function (a, b, inputString) {
                return a.indexOf(inputString) - b.indexOf(inputString);
            },
            onAutocomplete: function (selection) { that.selectItemFromAutocompleteList(selection); }
        });

        if (that.model.attributes['start'] != null || that.model.attributes['start'] != undefined || that.model.attributes['start'] != '') {
            var startDate = new Date(that.model.attributes['start']);
            var endDate = new Date(that.model.attributes['end']);

            var setStartTime = this.$el.find('#startTime');
            var setEndTime = this.$el.find('#endTime');
            setStartTime.value = startDate.toLocaleTimeString("en-US");
            setEndTime.value = endDate.toLocaleTimeString("en-US");

            var setStartDate = this.$el.find('#startDay');
            var setEndDate = this.$el.find('#endDay');
            setStartDate.value = startDate.toLocaleDateString("en-US");
            setEndDate.value = endDate.toLocaleDateString("en-US");
        };

        var setSaleType = document.getElementById('sale-type-dropdown');
        if(this.isNew) {
            setSaleType.value = 0;
            this.byItem();
            this.onSaleTypeChange();
        }
        if(this.dataType == undefined || this.dataType == 'salePrice') {
            if (that.model.attributes['forPrice'] > 0 && that.model.attributes['quantity'] > 0) {
                setSaleType.value = 1;
            }
            else if (that.model.attributes['quantityLevel'] > 0 && that.model.attributes['quantityPrice'] > 0) {
                setSaleType.value = 2;
            }
            else if (that.model.attributes['initialQuantity'] > 0 && that.model.attributes['nextDiscountPct'] > 0) {
                setSaleType.value = 3;
            }
            else if (that.model.attributes['nextDiscountPrice'] > 0 && that.model.attributes['initialQuantity'] > 0) {
                setSaleType.value = 4;
            }
            else {
                setSaleType.value = 0;
            }
        }
        else
            setSaleType.value = 6;
        

        var saleType = this.$el.find('#sale-type-dropdown').val();
        if (saleType == 0) {
            $('#percent').show();
            $('#itemQuantity').hide();
            $('#quantityPrice').hide();
            $('#quantityPercent').hide();
            $('#quantityByPrice').hide();
            $('#qualifyingQty').hide();
        }
        else if (saleType == 1) {
            $('#percent').hide();
            $('#itemQuantity').show();
            $('#quantityPrice').hide();
            $('#quantityPercent').hide();
            $('#quantityByPrice').hide();
            $('#qualifyingQty').hide();
        }
        else if (saleType == 2 || saleType == 5) {
            $('#percent').hide();
            $('#itemQuantity').hide();
            $('#quantityPrice').show();
            $('#quantityPercent').hide();
            $('#quantityByPrice').hide();
            $('#qualifyingQty').hide();
        }
        else if (saleType == 3) {
            $('#percent').hide();
            $('#itemQuantity').hide();
            $('#quantityPrice').hide();
            $('#quantityPercent').show();
            $('#quantityByPrice').hide();
            $('#qualifyingQty').hide();
        }
        else if (saleType == 4) {
            $('#percent').hide();
            $('#itemQuantity').hide();
            $('#quantityPrice').hide();
            $('#quantityPercent').hide();
            $('#quantityByPrice').show();
            $('#qualifyingQty').hide();
        }
        else if (saleType == 6) {
            $('#percent').hide();
            $('#itemQuantity').hide();
            $('#quantityPrice').hide();
            $('#quantityPercent').hide();
            $('#quantityByPrice').hide();
            $('#qualifyingQty').show();
        }


        var setType = document.getElementById('type');
        var setItem = document.getElementById('items');

        var byGroup = document.getElementById('byType');
        var byItem = document.getElementById('byItem');

        if (that.model.attributes['item'] != null || that.model.attributes['item'] != undefined) {
            if (that.model.attributes['item'].length > 0) {   
                byGroup.value = false;
                byItem.value = true;
            }
        }
        
        if (that.model.attributes['group'] != null || that.model.attributes['group'] != undefined) {
            if (that.model.attributes['group'].length > 0) {   
                byGroup.value = true;
                byItem.value = false;
            }
        }

        $('.qualifyingQtyTypeBlock').hide();


        if( this.dataType == undefined || this.dataType == '' || this.dataType == 'salePrice' ) {
            $('.salePrice').show();

            if(that.model.attributes['groupIsCategory'] == true) {
                this.byCategory();
                document.getElementById('byCategory').checked = true;
            }
            else if (byGroup.value == 'true') {
                this.byType();
                document.getElementById('byType').checked = true;
            }
            else {
                this.getItemById();
                document.getElementById('byItem').checked = true;
                this.byItem();
            }

            if (that.model.attributes['sunday'] == true && that.model.attributes['monday'] == true && that.model.attributes['tuesday'] == true
                && that.model.attributes['wednesday'] == true && that.model.attributes['thursday'] == true && that.model.attributes['friday'] == true
                && that.model.attributes['saturday'] == true) {

                    $('.dayCheckboxes').hide();
                    this.$el.find('#everyDay').not(this).prop('checked', true)
                    this.$el.find('#everyDay').attr("disabled", true);
            }
            else {
                $('.dayCheckboxes').show();
                this.$el.find('#certainDays').not(this).prop('checked', true)
                this.$el.find('#certainDays').attr("disabled", true);
            }

            var startTime = new Date(that.model.attributes['start']);
            var determineStart = startTime.toLocaleTimeString();
            var endTime = new Date(that.model.attributes['end']);
            var determineEnd = endTime.toLocaleTimeString();

            if (determineStart == '12:00:00 AM' && determineEnd == '11:59:00 PM') {
                $('.timePickers').hide();
                this.$el.find('#allDay').not(this).prop('checked', true)
                this.$el.find('#allDay').attr("disabled", true);
            }
            else {
                $('.timePickers').show();
                this.$el.find('#certainTimes').not(this).prop('checked', true);
                this.$el.find('#certainTimes').attr("disabled", true);
            }
        }
        else if(this.dataType == 'qualifyingQtyType') {
            $('.qualifyingQtyTypeBlock').show();
            $('.salePrice').hide();
            
            if(this.qualifyingQtyType.typeIsCategory) {
                this.byCategory();
                document.getElementById('byCategory').checked = true;
            }
            else {
                this.byType();
                document.getElementById('byType').checked = true;

            }
        }

        this.selectSaleType();
    },
    
    getItemById: async function() {
        var that = this;
        var sessionToken = this.getCookie();
        var itemId = this.model.attributes.item;
        try {
            await $.ajax({
                url: '/data/get-item-by-id',
                data: {
                    token: sessionToken,
                    itemId: itemId,
                },
                dataType: 'json',
                type: 'POST',
                success: function (data) {
                    returnItems = data.results;
                    that.model.attributes.itemDescription = data.results[0].description;
                    var itemDescription = document.getElementById('itemDescription');
                    itemDescription.value = that.model.attributes.itemDescription;
                },
                error: function (e) {
                    if (e.status == 523) {
                        window.location.href = "#/log-in";
                        location.reload();
                    }
                    else {
                        M.toast({ html: '{Literal}There was a problem fetching item types from the server{/Literal}' });
                    }
                }
            });
        }
        catch (exception)  {

        }

    },


    byItem: function (){
            $('.byItemText').show();
            $('.byItemDescription').show();
            $('.byItemButton').show();              
            $('.byItemTypeText').hide();
            $('.byItemTypeButton').hide();
            $('.byItemCategoryText').hide();
            $('.byItemCategoryButton').hide();
            $('.compItemByQuantityCategory').hide();
            $('.compItemByQuantityType').hide();
    },

    byType: function () {
            $('.byItemText').hide();
            $('.byItemDescription').hide();
            $('.byItemButton').hide();              
            $('.byItemTypeText').show();
            $('.byItemTypeButton').show();
            $('.byItemCategoryText').hide();
            $('.byItemCategoryButton').hide();

            if(this.dataType == 'qualifyingQtyType' || document.getElementById('sale-type-dropdown').value == 6){
                $('.compItemByQuantityCategory').hide();
                $('.compItemByQuantityType').show();
            }
            else {
                $('.compItemByQuantityCategory').hide();
                $('.compItemByQuantityType').hide();
            }
    },
    byCategory: function () {
            $('.byItemCategoryText').show();
            $('.byItemCategoryButton').show();
            $('.byItemText').hide();
            $('.byItemDescription').hide();
            $('.byItemButton').hide();              
            $('.byItemTypeText').hide();
            $('.byItemTypeButton').hide();

            if(this.dataType == 'qualifyingQtyType' || document.getElementById('sale-type-dropdown').value == 6){
                $('.compItemByQuantityCategory').show();
                $('.compItemByQuantityType').hide();
            }
            else {
                $('.compItemByQuantityCategory').hide();
                $('.compItemByQuantityType').hide();
            }
    },

    certainDays: function () {
        var everyDay = document.getElementById('everyDay').checked;
        if (everyDay){
            this.$el.find('#everyDay').not(this).prop('checked', false); 
            this.$el.find('#certainDays').prop("disabled", true); 
            this.$el.find('#everyDay').removeAttr('disabled');
            $('.dayCheckboxes').show();
        }
    },

    everyDay: function () {
        var certainDays = document.getElementById('certainDays').checked;
        if (certainDays){
            this.$el.find('#certainDays').not(this).prop('checked', false); 
            this.$el.find('#everyDay').prop("disabled", true); 
            this.$el.find('#certainDays').removeAttr('disabled');
            $('.dayCheckboxes').hide();
        }
    },

    allDay: function () {
        var certainTimes = document.getElementById('certainTimes').checked;
        if (certainTimes){
            this.$el.find('#certainTimes').not(this).prop('checked', false); 
            this.$el.find('#allDay').prop("disabled", true); 
            this.$el.find('#certainTimes').removeAttr('disabled');
            $('.timePickers').hide();
        }
    },

    certainTimes: function () {
        var allDay = document.getElementById('allDay').checked;
        if (allDay){
            this.$el.find('#allDay').not(this).prop('checked', false); 
            this.$el.find('#certainTimes').prop("disabled", true); 
            this.$el.find('#allDay').removeAttr('disabled');
            $('.timePickers').show();
        }
    },

    selectItemType: function (e) {
        var that = this;
        var element = $(e.currentTarget);
        var salesId = $(element).attr('data-id');
        var inputId =  $(element).attr('data-input');
        $('#select-type-modal').attr('data-input', inputId);
        $("#item-type-id").val(salesId);
        $('#select-type-modal').modal().modal('open');
    },

    selectItemCategory: function (e) {
        var that = this;
        var element = $(e.currentTarget);
        var salesId = $(element).attr('data-id');
        var inputId =  $(element).attr('data-input');
        $('#select-type-modal').attr('data-input', inputId);
        $("#item-category-id").val(salesId);
        $('#select-category-modal').modal().modal('open');
    },

    chooseItemType: function (e) {
        var element = $(e.currentTarget);
        var inputId = document.getElementById('select-type-modal').dataset.input
        var input = document.getElementById(inputId);
        var itemTypeId = $(element).attr('data-id');
        $('#select-type-modal').modal().modal('close');
        input.value = itemTypeId;
    },

    chooseItemCategory: function (e) {
        var element = $(e.currentTarget);
        var inputId = document.getElementById('select-type-modal').dataset.input
        var input = document.getElementById(inputId);
        var itemCategoryId = $(element).attr('data-id');
        $('#select-category-modal').modal().modal('close');
        input.value = itemCategoryId;
    },

    removeQuantityPriceRow: function (e) {
        const row = e.currentTarget.parentElement.parentElement;
        row.classList.add('hide');
    },

    addQuantityPriceRow: function (e) {
        const table = document.querySelector('#quantityPrice table');
        const row = /*html*/ `
            <td class="input-field">
                <input type="number">
            </td>
            <td class="input-field">
                <input type="number">
            </td>
            <td>
            <a class="btn-floating waves-effect waves-light red remove-quantity-price"><i class="material-icons">remove</i></a>
            </td>`
        const tr = document.createElement('tr');
        // const a = document.createElement('a');
        tr.innerHTML = row;
        tr.querySelector('.remove-quantity-price').addEventListener('click', that.removeQuantityPriceRow);
        table.appendChild(tr);
    },

    selectSaleType: function() {
        if(this.dataType == 'salePrice') {
            var sales = this.model.attributes;

            if (sales.discount != 0)
                document.getElementById('sale-type-dropdown').value = 0;
            if (sales.quantity != 0 && sales.forPrice != 0)
                document.getElementById('sale-type-dropdown').value = 1;
            if (sales.quantityLevel != 0 && sales.quantityPrice != 0 && !sales.quantityPriceIsPct)
                document.getElementById('sale-type-dropdown').value = 2;
            if (sales.quantityLevel != 0 && sales.quantityPrice != 0 && sales.quantityPriceIsPct)
                document.getElementById('sale-type-dropdown').value = 5;
            if (sales.quantity != 0 && sales.nextDiscountPct != 0)
                document.getElementById('sale-type-dropdown').value = 3;
            if (sales.initialQuantity != 0 && sales.nextDiscountPrice != 0)
                document.getElementById('sale-type-dropdown').value = 4;
            if (sales.quantity == 0 && sales.nextDiscountPrice == 0 && sales.discount == 0 && sales.quantityLevel == 0)
                document.getElementById('sale-type-dropdown').value = -1;
        }
        else if(this.dataType == 'qualifyingQtyType')
            document.getElementById('sale-type-dropdown').value = 6;
        else
            document.getElementById('sale-type-dropdown').value = -1;

        $('select').formSelect();

    },

    onSaleTypeChange: function() {
        var selectedSaleType = document.getElementById('sale-type-dropdown').value;
        var labelEl = document.getElementById('price-percent-label');
        if(selectedSaleType == 5)
            labelEl.innerHTML = "{Literal}Percent Discount{/Literal}";
        else
            labelEl.innerHTML = "{Literal}Price Each{/Literal} {Literal}($){/Literal}";

        var percent = document.getElementById("percent");
        var itemQuantity = document.getElementById("itemQuantity");
        var quantityPrice = document.getElementById("quantityPrice");
        var quantityPercent = document.getElementById("quantityPercent");
        var quantityByPrice = document.getElementById("quantityByPrice");
        var qualifyingQty = document.getElementById("qualifyingQty");
        var qualifyingQtyTypeBlock = document.getElementById("qualifyingQtyTypeBlock");
        var selectedBy = this.getSelectRadioButton();

        if( selectedBy == '' || selectedBy == 'byItem')
            this.byItem();
        else if(selectedBy == 'byType')
            this.byType();
        else if(selectedBy == 'byCategory')
            this.byCategory();

        if (selectedSaleType == 0) {
            percent.style.display = "block";
            itemQuantity.style.display = "none";
            quantityPrice.style.display = "none";
            quantityPercent.style.display = "none";
            quantityByPrice.style.display = "none";
            qualifyingQty.style.display = "none";
            qualifyingQtyTypeBlock.style.display = "none";
            $('.salePrice').show();
        }
        else if (selectedSaleType == 1) {
            percent.style.display = "none";
            itemQuantity.style.display = "block";
            quantityPrice.style.display = "none";
            quantityPercent.style.display = "none";
            quantityByPrice.style.display = "none";
            qualifyingQty.style.display = "none";
            qualifyingQtyTypeBlock.style.display = "none";
            $('.salePrice').show();
        }
        else if (selectedSaleType == 2 || selectedSaleType == 5) {
            percent.style.display = "none";
            itemQuantity.style.display = "none";
            quantityPrice.style.display = "block";
            quantityPercent.style.display = "none";
            quantityByPrice.style.display = "none";
            qualifyingQty.style.display = "none";
            qualifyingQtyTypeBlock.style.display = "none";
            $('.salePrice').show();
        }
        else if (selectedSaleType == 3) {
            percent.style.display = "none";
            itemQuantity.style.display = "none";
            quantityPrice.style.display = "none";
            quantityPercent.style.display = "block";
            quantityByPrice.style.display = "none";
            qualifyingQty.style.display = "none";
            qualifyingQtyTypeBlock.style.display = "none";
            $('.salePrice').show();
        }
        else if (selectedSaleType == 4) {
            percent.style.display = "none";
            itemQuantity.style.display = "none";
            quantityPrice.style.display = "none";
            quantityPercent.style.display = "none";
            quantityByPrice.style.display = "block";
            qualifyingQty.style.display = "none";
            qualifyingQtyTypeBlock.style.display = "none";
            $('.salePrice').show();

        }
        else if (selectedSaleType == 6) {
            percent.style.display = "none";
            itemQuantity.style.display = "none";
            quantityPrice.style.display = "none";
            quantityPercent.style.display = "none";
            quantityByPrice.style.display = "none";
            qualifyingQty.style.display = "block";
            qualifyingQtyTypeBlock.style.display = "block";
            $('.salePrice').hide();

            if(selectedBy == 'byItem') {
                this.byType();
                document.getElementById('byType').checked = true;
            }
        }

    },

    getSelectRadioButton: function() {
        var radioButtons = document.querySelectorAll('.by-item-group');
        var checkedId = '';
        for (const el of radioButtons) {
                if(el.checked)
                    checkedId = el.id;
        }

        return checkedId;
    }
});