// Reference array sent to dynamic staticRenderFns
var staticRenderFns = [];
$(window).on('load', function () {

    Vue.component('product-unit-price', {
        mixins: [mixinUnit, mixinPrice, mixinTemplate],
        props: ['template', 'key'],
        data() {
            return Object.assign({
                behaviorPrice: 'by-piece',
                activeProducts: false,
            }, window.productUnitPriceValues);

        },
        computed: {
            buyingPriceValue: function () {
                return this.buyingPrice;
            },
            buyingPriceWithTaxValue: function () {
                return this.buyingPriceWithTax;
            },
            buyingPriceByRefUnitValue: function () {
                return this.buyingPriceByRefUnit;
            },
            buyingPriceByRefUnitWithTaxValue: function () {
                return this.buyingPriceByRefUnitWithTax;
            },
            multiplyingFactorValue: function () {
                return this.multiplyingFactor;
            },
            priceWithTaxValue: function () {
                return this.priceWithTax;
            },
            priceValue: function () {
                return this.price;
            },
            priceByRefUnitValue: function () {
                return this.priceByRefUnit;
            },
            priceByRefUnitWithTaxValue: function () {
                return this.priceByRefUnitWithTax;
            },
            quantityValue: function () {
                return this.quantity;
            },
            unitValue: function () {
                return this.unit;
            },
            behaviorPriceValue: function () {
                return this.behaviorPrice;
            },
            taxRateValue: function () {
                if (this.taxRate) {
                    return this.taxRatesList[this.taxRate]['value'];
                } else if (this.taxRate == null || this.taxRate == "undefined") {
                    return this.taxRatesList['default']['value'];
                } else {
                    log('ERREUR : pas de taxRate')
                }
            },
            supplierTaxRateValue: function () {
                if (this.supplierTaxRate) {
                    return this.taxRatesList[this.supplierTaxRate]['value'];
                } else if (this.supplierTaxRate == null || this.supplierTaxRate == "undefined") {
                    return this.taxRateValue;
                } else {
                    log('ERREUR : pas de supplier taxRate')
                }
            },

        },
        mounted: function () {
            this.init();
        },
        watch: {
            taxRate: function () {
                this.setBuyingPriceWithTax();
                this.setBuyingPriceByRefUnitWithTax();
                this.setPriceWithTax();
                this.setPriceByRefUnitWithTax();
                this.setMultiplyingFactor();
                this.$parent.updateChild();
            },
            supplierTaxRate: function () {
                this.setBuyingPriceWithTax();
                this.setBuyingPriceByRefUnitWithTax();
            },
            differentSupplierTaxRate: function () {
                this.supplierTaxRate = null;
            },
            activeProducts: function () {
                this.$parent.updateActiveProducts();
            },
            behaviorPrice: function () {
                if (this.behaviorPrice == 'by-reference-unit') {
                    this.quantity = 1;
                }
            }
        }
    });

    Vue.component('product-form', {
        mixins: [mixinUnit, mixinPrice, mixinTemplate],
        props: ['template', 'keyForm', 'productFamily'],
        computed: {
            taxRateValue: function () {
                return this.productFamily.taxRateValue;
            },
            supplierTaxRateValue: function () {
                return this.productFamily.supplierTaxRateValue;
            },
            buyingPriceValue: function () {
                if (this.buyingPrice) return this.buyingPrice;
                else return this.productFamily.buyingPrice;
            },
            buyingPriceWithTaxValue: function () {
                if (this.buyingPriceWithTax) return this.buyingPriceWithTax;
                else return this.productFamily.buyingPriceWithTax;
            },
            buyingPriceByRefUnitValue: function () {
                if (this.buyingPriceByRefUnit) return this.buyingPriceByRefUnit;
                else return this.productFamily.buyingPriceByRefUnit;
            },
            buyingPriceByRefUnitWithTaxValue: function () {
                if (this.buyingPriceByRefUnitWithTax) return this.buyingPriceByRefUnitWithTax;
                else return this.productFamily.buyingPriceByRefUnitWithTax;
            },
            multiplyingFactorValue: function () {
                if (this.multiplyingFactor) return this.multiplyingFactor;
                else return this.productFamily.multiplyingFactor;
            },
            priceWithTaxValue: function () {
                if (this.priceWithTax) return this.priceWithTax;
                else return this.productFamily.priceWithTax;
            },
            priceValue: function () {
                if (this.price) return this.price;
                else return this.productFamily.price;
            },
            priceByRefUnitValue: function () {
                if (this.priceByRefUnit) return this.priceByRefUnit;
                else return this.productFamily.priceByRefUnit;
            },
            priceByRefUnitWithTaxValue: function () {
                if (this.priceByRefUnitWithTax) return this.priceByRefUnitWithTax;
                else return this.productFamily.priceByRefUnitWithTax;
            },
            quantityValue: function () {
                if (this.quantity) return this.quantity;
                else return this.productFamily.quantity;
            },
            unitValue: function () {
                if (this.unit) return this.unit;
                else return this.productFamily.unit;
            },
            propertyExpirationDateValue: function () {
                if (this.propertyExpirationDate) return this.propertyExpirationDate;
                else return this.productFamily.propertyExpirationDate;
            },
            behaviorPriceValue: function () {
                return this.productFamily.behaviorPrice;
            }
        },
        data() {
            return Object.assign(
                {
                    title: null,
                    position: 0,
                    status:1,
                    fieldToUpdate: ['title', 'unit', 'quantity', 'price'],
                    price: null,
                    priceWithTax: null,
                    buyingPrice: null,
                    multiplyingFactor: null,
                    availableQuantityDefault: null,
                    availableQuantity: null,
                    propertyExpirationDate: null,
                    titleInherited: false,
                    priceInherited: false,
                    priceWithTaxInherited: false,
                    unitInherited: false,
                    quantityInherited: false,
                    multiplyingFactorInherited: false,
                    buyingPriceInherited: false,
                    buyingPriceWithTaxInherited: false,
                    buyingPriceByRefUnitInherited: false,
                    buyingPriceByRefUnitWithTaxInherited: false,
                    priceByRefUnitInherited: false,
                    priceByRefUnitWithTaxInherited: false,
                    expirationDateInherited: false,
                    availableQuantityInherited: false,
                    availableQuantityDefaultInherited: false,
                    propertyExpirationDateInherited: false

                }, window.productForm[this.keyForm])
        },
        mounted: function () {
            //INIT VAR
            this.init();
            this.initKeyboardNav();
            this.title = toPlainText(this.title)
            this.title = toPlainText(this.title)
            this.title = toPlainText(this.title)
            this.title = toPlainText(this.title)
            this.title = toPlainText(this.title)
            this.title = toPlainText(this.title);
            this.propertyExpirationDate = toPlainText(this.propertyExpirationDate);

            this.$nextTick(function () {

                log(this.status);
                if (this.status == 0) {
                    $(this.$el).addClass('disabled');
                }
            });
            //METHOD

            //this.updateProductForm();
            //this.updateProductView();
        },
        methods: {
            changeStatus:function(){
                if(this.status ==1) {
                    this.status = 0;
                    $(this.$el).addClass('disabled');
                }else{
                    this.status = 1;
                    $(this.$el).removeClass('disabled');
                }
            },
            decode(str){
                var textArea = document.createElement('textarea');
                textArea.innerText = str;
                return textArea.textContent;
            },
            titleUpdated: function () {
            },
            availableQuantityUpdated: function () {
            },
            availableQuantityDefaultUpdated: function () {
            },
            propertyExpirationDateUpdated: function () {
            },
            setFocusOnField: function (field, y) {
                this[field] = true;
                this.$nextTick(function () {
                    if (field == 'unitInherited') {
                        $('select[data-ref="' + field + '"]').eq(y).focus();
                    } else {
                        $('input[data-ref="' + field + '"]').eq(y).focus();

                    }
                });

            },
            setUnitSelect2: function () {
                $(this.$el).find('select').each(function (i, select) {
                    setSelect2($(select));
                });
            },
            updateProductForm: function () {
                this.init();

            },
            saveProductForm: function () {
                $('#form-product-modal-' + this.key).modal('hide');
            },
            deleteProductForm: function () {
                if (confirm('Êtes-vous sur de cette action ?')) {
                    Vue.delete(this.$parent.formProducts, this.keyForm);
                    this.$nextTick(function () {
                        this.$parent.updateSortableProducts(true);
                    });
                }

            },
            modalProductForm: function () {
                $('#modal-extends-product-' + this.keyForm).modal('show')
            },
            initKeyboardNav: function () {
                var app = this;
                $(this.$el).find('input, select').off('keydown');
                $(this.$el).find('input, select').on('keydown', function (e) {
                    if (e.keyCode == 13 || e.keyCode == 9) e.preventDefault();

                    //ENTRER
                    if (e.keyCode == 13) {
                        $(this).blur();
                        ;
                    }
                    // shift + [+]
                    if (e.shiftKey && e.keyCode == 107) {
                        e.preventDefault()
                        app.$parent.addProductForm();
                    }
                    //GAUCHE (tab + shift)
                    if (e.shiftKey && e.keyCode == 9) {
                        e.preventDefault();
                        $prevField = $(this).parents('td').prevAll('td:visible').first().find('input, select');
                        log($prevField);
                        if($prevField.length == 0){
                            $prevField = $(this).parents('td').prevAll('td:visible').first().prevAll('td:visible').first().find('input, select');

                        }
                        app.setFocusOnField($prevField.data('ref'), $prevField.data('y'));

                        //DROITE (tab)
                    } else if (e.keyCode == '9') {
                        e.preventDefault();
                        $nextField = $(this).parents('td').nextAll('td:visible').first().find('input, select');
                        if($nextField.length == 0){
                            $nextField = $(this).parents('td').nextAll('td:visible').first().nextAll('td:visible').first().find('input, select');
                        }
                        app.setFocusOnField($nextField.data('ref'), $nextField.data('y'));
                    }

                    //BAS (flèche bas)
                    if (e.keyCode == '40') {
                        y = parseInt($(this).data('y')) + 1;
                        if (y >= app.$parent.$refs['productForm'].length) y = 0;
                        app.$parent.$refs['productForm'][y].setFocusOnField($(this).data('ref'), y);
                    }
                    //HAUT (flèche haut
                    if (e.keyCode == '38') {
                        y = parseInt($(this).data('y')) - 1;
                        if (y == -1) y = app.$parent.$refs['productForm'].length - 1;
                        app.$parent.$refs['productForm'][y].setFocusOnField($(this).data('ref'), y);
                    }

                });
            }
        },
        watch: {}
    });


    appProductFamily = new Vue({
        el: '#lc-product-family-edit',
        mixins: [mixinReduction],
        delimiters: ['${', '}'],
        computed: {
            productFamily: function () {
                if (this.isMounted) {
                    return {
                        'title': this.title,
                        'behaviorCountStock': this.behaviorCountStock,
                        'behaviorStockWeek': this.behaviorStockWeek,
                        'behaviorPrice': this.$refs.productUnitPrice.behaviorPrice,
                        'unit': this.$refs.productUnitPrice.unit, //this.getProductUnitPrice('unit'),
                        'unitWording': this.$refs.productUnitPrice.unitWording,
                        'quantity': this.$refs.productUnitPrice.quantity,
                        'price': this.$refs.productUnitPrice.price,
                        'priceWithTax': this.$refs.productUnitPrice.priceWithTax,
                        'buyingPrice': this.$refs.productUnitPrice.buyingPrice,
                        'buyingPriceWithTax': this.$refs.productUnitPrice.buyingPriceWithTax,
                        'buyingPriceByRefUnit': this.$refs.productUnitPrice.buyingPriceByRefUnit,
                        'buyingPriceByRefUnitWithTax': this.$refs.productUnitPrice.buyingPriceByRefUnitWithTax,
                        'priceByRefUnit': this.$refs.productUnitPrice.priceByRefUnit,
                        'priceByRefUnitWithTax': this.$refs.productUnitPrice.priceByRefUnitWithTax,
                        'taxRateValue': this.$refs.productUnitPrice.taxRateValue,
                        'supplierTaxRateValue': this.$refs.productUnitPrice.supplierTaxRateValue,
                        'marginProfit': this.$refs.productUnitPrice.marginProfit,
                        'marginProfitPercent': this.$refs.productUnitPrice.marginProfitPercent,

                        /*'taxRate': this.$refs.productUnitPrice.taxRate,
                        'supplierTaxRate': this.$refs.productUnitPrice.supplierTaxRate,
                        */
                        'multiplyingFactor': this.$refs.productUnitPrice.multiplyingFactor,
                        'propertyExpirationDate': this.propertyExpirationDate,
                        'behaviorExpirationDate': this.behaviorExpirationDate,
                        'reductionActive': this.reductionActive,
                        'reductionUnit': this.reductionUnit,
                        'reductionValue': this.reductionValue,
                        'reductionBehaviorTaxRate': this.reductionBehaviorTaxRate
                    };
                } else {
                    return {
                        'title': null,
                        'behaviorCountStock': null,
                        'behaviorStockWeek': null,
                        'behaviorPrice': null,
                        'unit': null,
                        'unitWording': null,
                        'quantity': null,
                        'price': null,
                        'priceWithTax': null,
                        'buyingPrice': null,
                        'buyingPriceWithTax': null,
                        'buyingPriceByRefUnit': null,
                        'buyingPriceByRefUnitWithTax': null,
                        'priceByRefUnit': null,
                        'priceByRefUnitWithTax': null,
                        'taxRate': null,
                        'supplierTaxRate': null,
                        'multiplyingFactor': null,
                        'taxRateValue': null,
                        'propertyExpirationDate': this.propertyExpirationDate,
                        'behaviorExpirationDate': this.behaviorExpirationDate
                    };
                }
            },
            unitReference: function () {
                this.getUnitReference();
            }
        },
        data() {

            return Object.assign(
                {
                    isMounted: false,
                    stayOnPage: false,
                    title: null,
                    isNovelty: null,
                    isOrganic: null,
                    propertyExpirationDate: null,
                    behaviorCountStock: null,
                    behaviorStockWeek: null,
                    typeExpirationDate: null,
                    behaviorExpirationDate: null,
                    propertyAllergens: null,
                    propertyOrganicLabelActive: false,
                    propertyNoveltyExpirationDateActive: false,
                    activeProducts: false,

                    formProducts: {},
                    currentSection: 'general',
                    sectionsArray: [
                        {
                            name: 'general',
                            nameDisplay: 'Général'
                        },
                        {
                            name: 'price',
                            nameDisplay: 'Prix '
                        },
                        {
                            name: 'products',
                            nameDisplay: 'Déclinaisons'
                        },
                        {
                            name: 'stock',
                            nameDisplay: 'Stock'
                        },
                        {
                            name: 'property',
                            nameDisplay: 'Caractéristiques'
                        },
                        {
                            name: 'reduction',
                            nameDisplay: 'Réduction'
                        },
                        {
                            name: 'seo',
                            nameDisplay: 'SEO'
                        },
                        {
                            name: 'note',
                            nameDisplay: 'Note interne'
                        }
                    ]
                }, window.appProductFamilyValues);
        },
        mounted: function () {
            this.$nextTick(function () {
                this.title = toPlainText(this.title)
                this.title = toPlainText(this.title)
                this.title = toPlainText(this.title)
                this.title = toPlainText(this.title)
                this.title = toPlainText(this.title)
                this.title = toPlainText(this.title)
                this.propertyExpirationDate = toPlainText(this.propertyExpirationDate);


                this.isMounted = true;
                $(".vuejs-checkbox-switch input").each(function () {
                    setBootstrapSwitch($(this));
                });
                if (location.hash) {
                    try {
                        this.changeSection(location.hash.substr(1));
                    } catch (e) {
                        this.currentSection = 'general';
                    }

                }
                this.initLcSortableProductsList();
            });

        },
        methods: {
            changeSection: function (section) {
                if (typeof section === "object") {
                    this.currentSection = section.name;
                } else {
                    this.currentSection = section;
                }
                this.updateChild();
            },
            addProductForm: function () {
                var $collectionHolder = $('table.products-collection-table');
                var prototype = $collectionHolder.data('prototype');
                var newForm = prototype;
                newForm = newForm.replace(/__name__/g, Object.keys(this.formProducts).length);
                Vue.set(this.formProducts, Object.keys(this.formProducts).length, newForm);

                log(Object.keys(this.formProducts).length);
                this.$nextTick(function () {
                    this.updateSortableProducts(true);

                });
            },
            updateKeyboardNav: function () {
                this.$nextTick(function () {
                    if (typeof this.$refs.productForm !== 'undefined') {
                        for (i = 0; i < this.$refs.productForm.length; i++) {
                            this.$refs.productForm[i].initKeyboardNav();
                        }
                    }
                });
            },
            postForm:function(){
                this.stayOnPage = 1;
                this.$nextTick(function () {
                    $("#edit-productfamily-form").submit();
                });
            },

            initLcSortableProductsList: function () {
                if ($('.lc-sortable-products').length > 0) {
                    $('.lc-sortable-products tbody').sortable({
                        placeholder: "ui-state-highlight"
                    });
                    var app=this;
                    $('.lc-sortable-products tbody').on("sortupdate", function (event, ui) {
                        app.updateSortableProducts(true);
                    });
                }
            },
            updateSortableProducts: function (post) {
                if ($('.lc-sortable-products').length > 0) {
                    var app=this;
                    var newArray = {};

                    $('.lc-sortable-products tr.lc-draggable').each(function (index, li) {
                        oldKey = $(li).find('.field-position').val();
                        $(li).find('.field-position').val(index);
                        //log($(li).find('.field-position').val());
                    });
                    if(post)this.postForm();
                }
            },

            updateChild: function () {
                if (typeof this.$refs.productUnitPrice !== 'undefined') {
                    this.$refs.productUnitPrice.init();
                }
                if (typeof this.$refs.productForm !== 'undefined') {
                    for (i = 0; i < this.$refs.productForm.length; i++) {
                        this.$refs.productForm[i].updateProductForm();
                    }
                }
            },
            getUnitReference: function () {
                if (typeof this.$refs.productUnitPrice !== 'undefined') {
                    return this.$refs.productUnitPrice.unitReference;
                }
            },
            updateActiveProducts: function () {
                this.activeProducts = this.$refs.productUnitPrice.activeProducts;
            },
            getBehaviorPrice: function () {
                if (typeof this.$refs.productUnitPrice !== 'undefined') {
                    return this.$refs.productUnitPrice.behaviorPrice;
                }
            }
        },
        watch: {
            title: function () {
                this.updateChild()
            },
        }
    });

    var allowLeave = false;
    $('#edit-productfamily-form, #new-productfamily-form').on('submit', function () {
        allowLeave = true;
    })
    $(window).bind('beforeunload', function (e) {
        if (!allowLeave) {
            return 'Êtes vous sur de vouloir quitter ?';
        }
    });

    for (var key in formProductTemplate) {
        appProductFamily.formProducts[key] = formProductTemplate[key];
    }

});
