

var app = new Vue({
    el: '#app-order-order',
    data() {
        return Object.assign({
            loading: false,
            loadingInit: true,
            step: null,
            producer: null,
            user: null,
            date: null,
            dateFormat: null,
            distributions: [],
            distribution: null,
            pointsSale: [],
            pointSaleActive: null,
            pointsSaleCodes: [],
            products: [],
            categories: [],
            categoryCurrent: null,
            comment: '',
            creditCheckbox: false,
            useCredit: false,
            errors: [],
            disableConfirmButton: false,
            delivery: false,
            deliveryAddress: null,
            calendar: {
                mode: 'single',
                attrs: [],
                availableDates: [],
                themeStyles: {
                    wrapper: {
                        background: '#F7F7F7',
                        color: '#333',
                        border: 'solid 1px #e0e0e0'
                    },
                    header: {
                        padding: '10px 10px',
                    },
                    headerHorizontalDivider: {
                        borderTop: 'solid rgba(255, 255, 255, 0.2) 1px',
                        width: '80%',
                    },
                    weekdays: {
                        color: 'gray',
                        fontWeight: '600',
                        padding: '10px 10px',
                        fontSize: '2rem'
                    },
                    weeks: {
                        padding: '0 15px 15px 15px',
                    },
                    dayContent: function (object) {
                        var style = {
                            fontSize: '1.5rem',
                            padding: '20px',
                        };
                        return style;
                    },
                },
                formats: {
                    dayPopover: 'DD/MM/YYYY'
                }
            }
        }, window.appInitValues);
    },
    mounted: function() {
        var dateDefined = $('#order-distribution-date').size() || $('#distribution-date').size() ;

        if(dateDefined) {
            if($('#order-distribution-date').size()) {
                this.date = new Date($('#order-distribution-date').html()) ;
            }
            else {
                this.date = new Date($('#distribution-date').html()) ;
            }
            
            this.dateFormat = ('0' + this.date.getDate()).slice(-2)+ '/'
            + ('0' + (this.date.getMonth() +1)).slice(-2) + '/'
            + this.date.getFullYear() ;
        }
        
        this.init('first') ;

        this.loadingInit = false ;
    },
    methods: {
        getDate: function() {
            return this.formatDate(this.date) ;
        },
        formatDate: function(date) {
            if(date) {
                return date.getFullYear() + '-'
                    + ('0' + (date.getMonth() +1)).slice(-2) + '-'
                    + ('0' + date.getDate()).slice(-2) ;
            }
            return false ;
        },
        formatPrice: formatPrice,
        getPointSale: function(idPointSale) {
            for(var key in this.pointsSale) {
                if(this.pointsSale[key].id == idPointSale) {
                    return this.pointsSale[key] ;
                }
            }
        },
        getPointSaleKey: function(idPointSale) {
            for(var key in this.pointsSale) {
                if(this.pointsSale[key].id == idPointSale) {
                    return key ;
                }
            }
        },
        init: function(type, oldStep, step) {

            var app = this ;
            this.loading = true ;

            if(app.isChangeState('date', 'date', 'point-sale')) {
                app.pointSaleActive = null ;
                app.products = [] ;
            }

            axios.get("ajax-infos",{params: {
                date : this.getDate(),
                pointSaleId: this.pointSaleActive ? this.pointSaleActive.id : 0
            }})
                .then(function(response) {

                    // distributions
                    var distributions = response.data.distributions;

                    app.calendar.attrs = [];
                    app.calendar.availableDates = [];

                    if (distributions.length) {
                        app.distributions = distributions;
                        var arrayDate;
                        for (var i = 0; i < distributions.length; i++) {
                            app.calendar.attrs.push({
                                highlight: {
                                    backgroundColor: '#5cb85c',
                                },
                                contentStyle: {
                                    color: 'white',
                                },
                                dates: distributions[i].date,
                            });

                            arrayDate = distributions[i].date.split('-');
                            app.calendar.availableDates.push({
                                start: new Date(arrayDate[0], arrayDate[1] - 1, arrayDate[2]),
                                end: new Date(arrayDate[0], arrayDate[1] - 1, arrayDate[2])
                            });
                        }
                    }

                    // distribution
                    if (response.data.distribution) {
                        app.distribution = response.data.distribution;
                    }

                    // liste commandes
                    var orders = [];
                    if (response.data.orders) {
                        orders = response.data.orders;
                    }

                    if (orders.length) {
                        for (var i = 0; i < orders.length; i++) {
                            arrayDate = orders[i].date_distribution.split('-');
                            var dateOrder = new Date(arrayDate[0], arrayDate[1] - 1, arrayDate[2]);
                            if (app.isAvailableDate(dateOrder)) {

                                app.calendar.attrs.push({
                                    highlight: {
                                        backgroundColor: '#FF7F00'
                                    },
                                    contentStyle: {
                                        color: 'white'
                                    },
                                    popover: {
                                        label: orders[i].pointSale.name + ' / ' + app.formatPrice(orders[i].amount_total),
                                        hideIndicator: true
                                    },
                                    dates: orders[i].date_distribution,
                                });
                            }
                        }
                    }

                    // catégories
                    if(response.data.categories) {
                        app.categories = response.data.categories ;
                        app.setCategoryCurrent(response.data.categories[0]) ;
                    }

                    // producer
                    app.producer = response.data.producer;

                    // user
                    app.user = response.data.user;

                    // use credit
                    app.useCredit = response.data.producer.use_credit_checked_default;

                    // points de vente
                    if (response.data.points_sale) {
                        app.pointsSale = [];
                        var orderPointSale = 0;
                        for (var key in response.data.points_sale) {
                            response.data.points_sale[key].order = orderPointSale++;
                            app.pointsSale[response.data.points_sale[key].id] = response.data.points_sale[key];

                            if(!app.pointsSaleCodes[response.data.points_sale[key].id]) {
                                app.pointsSaleCodes[response.data.points_sale[key].id] = '';
                                Vue.set(app.pointsSaleCodes, response.data.points_sale[key].id, '');
                            }
                        }
                    }

                    if(app.isChangeState('point-sale', 'point-sale', 'date')) {
                        app.date = null ;
                        app.dateFormat = null ;
                    }

                    // update order
                    var updateOrder = false ;
                    if(app.isChangeState('date', 'point-sale', 'products')
                        || app.isChangeState('date', 'date', 'point-sale')
                        || app.isChangeState('point-sale', 'date', 'products')
                        || app.isChangeState('point-sale', 'point-sale', 'date')) {

                        updateOrder = true ;
                    }

                    if(updateOrder) {
                        // products
                        if(response.data.products) {
                            app.products = response.data.products ;
                        }

                        // order
                        app.order = null ;
                        if(response.data.order) {
                            app.order = response.data.order ;
                            app.comment = app.order.comment ;
                            app.delivery = app.order.delivery_home ;
                            if(app.order.delivery_address && app.order.delivery_address.length > 0) {
                                app.deliveryAddress = app.order.delivery_address ;
                            }
                            app.pointSaleActive = app.getPointSale(response.data.order.id_point_sale) ;
                        }
                        else {
                            app.comment = null ;
                            app.delivery = false ;
                            app.deliveryAddress = null ;
                            if(app.user.address && app.user.address.length > 0) {
                                app.deliveryAddress = app.user.address ;
                            }
                        }
                    }

                    if(type == 'first') {
                        if(app.producer.option_order_entry_point == 'point-sale') {
                            app.step = 'point-sale' ;
                        }
                        else if(app.getDate() && app.producer && app.producer.option_order_entry_point == 'date') {
                            app.step = 'point-sale' ;
                        }
                        else {
                            app.step = 'date' ;
                        }
                    }

                    app.loading = false ;
                });  
        },

        isChangeState: function(entryPoint, oldStep, newStep) {

            return this.producer
                &&  entryPoint == this.producer.option_order_entry_point
                && oldStep == this.oldStep
                && newStep == this.step ;

        },

        nextStep: function() {
            this.errors = [] ;
            var oldStep = this.step ;
            var nextStep = null ;

            // par point de vente
            if(this.producer && this.producer.option_order_entry_point == 'point-sale') {
                if(oldStep == 'point-sale') {
                    nextStep = 'date' ;
                }
                else if(oldStep == 'date') {
                    nextStep = 'products' ;
                }
            }
            // par date
            else {
                if(oldStep == 'date') {
                    nextStep = 'point-sale' ;
                }
                else if(oldStep == 'point-sale') {
                    nextStep = 'products' ;
                }
            }

            if(nextStep) {
                this.changeStep(nextStep) ;
            }

        },

        changeStep: function(step) {
            this.errors = [] ;
            var oldStep = this.step ;
            this.oldStep = oldStep ;
            
            if(oldStep == 'products' && step == 'payment') {
                this.checkProducts() ;
            }
            if(!this.errors.length) {
                this.step = step ;
                window.scroll(0, $('#page-title').position().top - 25) ;
                this.init('basic', oldStep, step) ;
            }
        },
        dayClickList: function(event) {
            var dateStr = event.currentTarget.getAttribute('data-distribution-date') ;
            var dateObject = new Date(dateStr.replace(/-/g, "/")) ;
            if(this.isAvailableDate(dateObject)) {
                this.dayClickEvent(dateObject) ;
            }
        },
        dayClick: function(day) {
            if(this.isAvailableDate(day.date)) {
                this.dayClickEvent(day.date) ;
            }
        },
        dayClickEvent: function(date) {
            this.date = date ;
            this.dateFormat = ('0' + this.date.getDate()).slice(-2)+ '/'
                + ('0' + (this.date.getMonth() +1)).slice(-2) + '/'
                + this.date.getFullYear() ;

            this.nextStep() ;
        },
        isAvailableDate: function(date) {
            for(var key in this.calendar.availableDates) {
                if(date.getTime() == this.calendar.availableDates[key].start.getTime()) {
                    return true ;
                }
            }

            return false ;
        },
        pointSaleClick: function(event) {
            var app = this ;
            var idPointSale = event.currentTarget.getAttribute('data-id-point-sale') ;
            var hasCode = event.currentTarget.getAttribute('data-code') ;
        
            if(hasCode) {
                axios.get('ajax-validate-code-point-sale',{params: {
                    idPointSale: idPointSale,    
                    code: this.pointsSaleCodes[idPointSale]
                }}).then(function(response) {
                    if(response.data) {
                        app.pointsSale[app.getPointSaleKey(idPointSale)].invalid_code = false ;
                        app.validatePointSale(idPointSale) ;
                    }
                    else {
                        app.pointsSale[app.getPointSaleKey(idPointSale)].invalid_code = true ;
                        Vue.set(app.pointsSaleCodes, idPointSale, '');
                    }
                }) ;
            }
            else {
                this.validatePointSale(idPointSale) ;
            }
        },

        validatePointSale: function(idPointSale) {
            this.pointSaleActive = this.getPointSale(idPointSale) ;
            if(this.pointSaleActive.credit_functioning == 'mandatory' || (this.pointSaleActive.credit_functioning == 'user' && this.user.credit_active)) {
                this.useCredit = true ;
            }

            this.nextStep() ;
        },
        productQuantityClick: function(product, quantity) {
            if( this.products[product.index].quantity_form + quantity >= 0 && 
                (this.products[product.index].quantity_form + quantity <=  (this.products[product.index].quantity_remaining * this.products[product.index].coefficient_unit) ||
                 !this.products[product.index].quantity_max)
               ) {
                this.products[product.index].quantity_form += quantity ;
            }
        },
        oneProductOrdered: function() {
            for(var key in this.products) {
                if(this.products[key].quantity_form > 0) {
                    return true ;
                }
            } 
            return false ;
        },
        countProductOrdered: function() {
            var count = 0 ;
            for(var key in this.products) {
                if(this.products[key].quantity_form > 0) {
                    if(this.products[key].unit != 'piece') {
                        count ++ ;
                    }
                    else {
                        count += this.products[key].quantity_form ;
                    }
                }
            }
            return count ;
        },
        priceTotal: function(format) {
            var price = 0 ;
            for(var key in this.products) {
                if(this.products[key].quantity_form > 0) {
                    price += (this.products[key].quantity_form / this.products[key].coefficient_unit) * this.products[key].price_with_tax ;
                }
            }
            if(format) {
                return this.formatPrice(price) ;
            }
            else {
                return price ;
            }
        },
        confirmClick: function() {

            var app = this ;

            // delivery
            if(app.delivery && !app.deliveryAddress) {
                this.errors = [] ;
                this.errors.push('Veuillez saisir une adresse de livraison') ;
                return false ;
            }

            // guest form
            var $signupGuestForm = $('#signup-guest form') ;
            if($signupGuestForm.length > 0 && !$signupGuestForm.valid()) {
                $signupGuestForm.submit() ;
                return false ;
            }

            var user = false ;
            if(this.producer.option_allow_order_guest && !this.user) {
                user = {
                    email: $('#signupguest-email').val(),
                    password: $('#signupguest-password').val(),
                    firstname: $('#signupguest-firstname').val(),
                    lastname: $('#signupguest-lastname').val(),
                    phone: $('#signupguest-phone').val(),
                } ;
            }

            // products
            var productsArray = {} ;
            for(var key in this.products) {
                if( this.products[key].quantity_form != null && 
                    this.products[key].quantity_form > 0) {
                    productsArray[this.products[key].id] = this.products[key].quantity_form ;
                }
            }

            app.disableConfirmButton = true ;
            
            axios.post('ajax-process', {
                Order: {
                    id_distribution : this.distribution.id,
                    id_point_sale: this.pointSaleActive.id,
                    comment: this.comment,
                    delivery_home: this.delivery,
                    delivery_address: this.deliveryAddress
                },
                code_point_sale: this.pointsSaleCodes[this.pointSaleActive.id],
                products: productsArray,
                use_credit: Number(this.useCredit),
                user: user
            }).then(function(response) {
                if(response.data.status == 'success') {
                    app.errors = [] ;
                    window.location.href = opendistrib_base_url(true)+'order/confirm?idOrder='+response.data.idOrder ;
                }
                else {
                    app.errors = response.data.errors ;
                    app.disableConfirmButton = false ;
                }
            });
        },
        checkProducts: function() {
            if(!this.oneProductOrdered()) {
                this.errors.push('Veuillez sélectionner au moins un produit.') ;
            }
        },
        checkCreditLimit: function(order) {
            var total = this.priceTotal() ;
            if(order != null) {
                total = this.priceTotal() - order.amount_paid ;
            }
            return this.producer.credit_limit == null || (this.producer.credit_limit != null && (this.user.credit - total >= this.producer.credit_limit)) ;
        },
        countProductsByCategory: function(category) {
            var count = 0 ;
            for(var i = 0 ; i < this.products.length ; i++) {
                if(this.products[i].id_product_category == category.id) {
                    count ++ ;
                }
            }
            return count ;
        },
        countSelectedProductsByCategory: function(category) {
            var count = 0 ;
            for(var key in this.products) {
                if(this.products[key].quantity_form > 0 && this.products[key].id_product_category == category.id) {
                    count ++ ;
                }
            }

            return count ;
        },
        setCategoryCurrent: function(category) {
            if(this.categoryCurrent && this.categoryCurrent.id == category.id) {
                this.categoryCurrent = null ;
            }
            else {
                this.categoryCurrent = category ;
            }
        }
    },
    computed : {
        orderedPointsSale: function() {
            var orderedPointsSaleArray = this.pointsSale.sort(function(a, b) {
                if(a.order > b.order) {
                    return 1 ;
                }
                else {
                    return -1 ;
                }
            }) ;
            
            return orderedPointsSaleArray ;
        }
    },
    updated: function () {
        var app = this;
        this.$nextTick(function () {
            if(app.step == 'payment' && !app.user && app.producer.option_allow_order_guest) {
                $("#signup-guest form").validate({
                    rules: {
                        'SignupForm[email]': {
                            'email': true,
                            'required': true,
                            'minlength': 8,
                            'maxlength': 255
                        },
                        'SignupForm[password]': {
                            'required': true,
                            'minlength': 8,
                            "maxlength": 255
                        },
                        'SignupForm[firstname]': {
                            'required': true,
                            'minlength': 2,
                            "maxlength": 255
                        },
                        'SignupForm[lastname]': {
                            'required': true,
                            'minlength': 2,
                            "maxlength": 255
                        },
                        'SignupForm[phone]': {
                            'required': true,
                            'minlength': 2,
                            "maxlength": 255
                        },
                    },
                    messages: {
                        'SignupForm[email]' : {
                            'required': 'Ce champs est requis.',
                            'email' : 'Email invalide.'
                        },
                        'SignupForm[password]' : {
                            'required': 'Ce champs est requis.',
                        },
                        'SignupForm[firstname]' : {
                            'required': 'Ce champs est requis.',
                        },
                        'SignupForm[lastname]' : {
                            'required': 'Ce champs est requis.',
                        },
                        'SignupForm[phone]' : {
                            'required': 'Ce champs est requis.',
                        },
                    }
                }) ;
            }
        });
    }
});

Vue.component('step-date',{
    props: [
        'step',
        'pointSaleActive',
        'dateFormat',
        'changeStep',
        'producer',
        'first',
    ],
    data: function() {
        return {
        } ;
    },
    template: '#template-step-date',
    methods: {
    }
}) ;

Vue.component('step-point-sale',{
    props: [
        'step',
        'pointSaleActive',
        'changeStep',
        'producer',
        'first',
    ],
    data: function() {
        return {
        } ;
    },
    template: '#template-step-point-sale',
    methods: {
    }
}) ;