var app = new Vue({
    el: '#app-subscription-form',
    data: {
        loading: true,
        idSubscription: 0,
        pointsSale: [],
        idPointSaleActive: 0,
        pointSaleActive: null,
        pointsSaleCodes: [],
        dateBegin: null,
        dateEnd: null,
        weekFrequency: 1,
        autoPayment: true,
        monday: false,
        tuesday: false,
        wednesday: false,
        thursday: false,
        friday: false,
        saturday: false,
        sunday: false,
        products: [],
        errors: [],
        disableSubmitButton: false,
        lastCountDays: 0,
    },
    mounted: function() {
        this.init();
    },
    methods: {
        init: function() {
            var app = this ;
            if($('#subscription-id').val() != 0) {
                this.idSubscription = $('#subscription-id').val() ;
            }
            
            this.dateBegin = new Date() ;

            axios.get("ajax-infos",{params: {idSubscription : this.idSubscription}})
                .then(function(response) {
                    
                    app.products = response.data.products ;
                    app.pointsSale = response.data.points_sale ;
                    
                    if(app.idSubscription > 0) {
                        app.validatePointSale(response.data.id_point_sale) ;
                        app.weekFrequency = response.data.week_frequency ;
                        app.autoPayment = response.data.auto_payment ;
                        var arrayDateBegin = response.data.date_begin.split('-') ;
                        app.dateBegin = new Date(arrayDateBegin[0], arrayDateBegin[1] - 1, arrayDateBegin[2]) ;
                        if(response.data.date_end && response.data.date_end.length > 0) {
                            var arrayDateEnd = response.data.date_begin.split('-') ;
                            app.dateEnd = new Date(arrayDateEnd[0], arrayDateEnd[1] - 1, arrayDateEnd[2]) ;
                        }
                        app.monday = response.data.monday ;
                        app.tuesday = response.data.tuesday ;
                        app.wednesday = response.data.wednesday ;
                        app.thursday = response.data.thursday ;
                        app.friday = response.data.friday ;
                        app.saturday = response.data.saturday ;
                        app.sunday = response.data.sunday ;
                    }
                    
                    app.loading = false ;
            });
            
        },
        formatDate: function(date) {
            if(date) {
                return ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear()  ;
            }
            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.getPointSale(idPointSale).invalid_code = false ;
                        app.validatePointSale(idPointSale) ;
                    }
                    else {
                        app.getPointSale(idPointSale).invalid_code = true ;
                        Vue.set(app.pointsSaleCodes, idPointSale, '');
                    }
                }) ;
            }
            else {
                this.validatePointSale(idPointSale) ;
            }
        },
        validatePointSale: function(idPointSale) {
            if(this.idPointSaleActive != idPointSale) {
                this.monday = false ;
                this.tuesday = false ;
                this.wednesday = false ;
                this.thursday = false ;
                this.friday = false ;
                this.saturday = false ;
                this.sunday = false ;
            }
            
            this.pointSaleActive = this.getPointSale(idPointSale) ;
            this.idPointSaleActive = idPointSale ;
            boulange_scroll('step-date') ;
        },
        getPointSale: function(idPointSale) {
            for(var key in this.pointsSale) {
                if(this.pointsSale[key].id == idPointSale) {
                    return this.pointsSale[key] ;
                }
            }
        },
        dayChange: function() {
            console.log(this.monday+' '+this.tuesday+' '+this.wednesday+' '+
                    this.thursday+' '+this.friday+' '+this.saturday+' '+this.sunday) ;
            
            var count = Number(this.monday) + Number(this.tuesday) + Number(this.wednesday)
                + Number(this.thursday) + Number(this.friday) + Number(this.saturday) 
                + Number(this.sunday) ;
            
            if(count == 1 && this.lastCountDays == 0) {
                this.lastCountDays = count ;
                boulange_scroll('step-days') ;  
            }
        },
        checkProductAvailable: function(product) {
            var available = product.active &&
                    (!this.monday || (this.monday && product.monday)) && 
                    (!this.tuesday || (this.tuesday && product.tuesday)) && 
                    (!this.wednesday || (this.wednesday && product.wednesday)) && 
                    (!this.thursday || (this.thursday && product.thursday)) && 
                    (!this.friday || (this.friday && product.friday)) && 
                    (!this.saturday || (this.saturday && product.saturday)) && 
                    (!this.sunday || (this.sunday && product.sunday)) ;
            
            if(!available) {
                product.quantity_form = 0 ;
            }
            
            return available ;
        },
        checkOneProductAvailable: function() {
            var count = 0 ;
            for(key in this.products) {
                if(this.checkProductAvailable(this.products[key])) {
                    count ++ ;
                }
            }
            return count ;
        },
        productQuantityClick: function(product, quantity) {
            if( this.products[product.index].quantity_form + quantity >= 0) {
                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 ;
        },
        formatPrice: function(price) {
            var isNumberRegExp = new RegExp(/^[-+]?[0-9]+(\.[0-9]+)*$/);
            if(isNumberRegExp.test(price) && price > 0) {
                return Number(price).toFixed(2).replace('.',',')+' €' ;
            }
            return '--' ;
        },
        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].price ;
                }
            }
            if(format) {
                return this.formatPrice(price) ;
            }
            else {
                return price ;
            }
        },
        formSubmit: function() {
            this.checkForm() ;
            if(!this.errors.length && !this.disableSubmitButton) {

                this.disableSubmitButton = true ;

                var productsArray = {} ;
                for(var key in this.products) {
                    if( this.products[key].quantity_form != null && 
                        this.products[key].quantity_form > 0) {
                        productsArray['product_'+this.products[key].id] = this.products[key].quantity_form ;
                    }
                }
                
                axios.post('ajax-process', {
                    idSubscription: this.idSubscription,
                    SubscriptionForm: {
                        id_point_sale: this.idPointSaleActive,
                        date_begin: this.dateBegin ? this.formatDate(this.dateBegin) : '',
                        date_end: this.dateEnd ? this.formatDate(this.dateEnd) : '',
                        week_frequency: this.weekFrequency,
                        auto_payment: this.autoPayment,
                        monday: this.monday == true ? 1 : 0,
                        tuesday: this.tuesday == true ? 1 : 0,
                        wednesday: this.wednesday == true ? 1 : 0,
                        thursday: this.thursday == true ? 1 : 0,
                        friday: this.friday == true ? 1 : 0,
                        saturday: this.saturday == true ? 1 : 0,
                        sunday: this.sunday == true ? 1 : 0,
                        products: productsArray
                    }
                }).then(function(response) {
                    window.location.href = chat_base_url(true)+'subscription/index' ;
                });
            }
        },
        checkForm: function() {
            var app = this ;
            this.errors = [] ;
            
            if(!this.idPointSaleActive) {
                this.errors.push('Veuillez sélectionner un point de vente') ;
            }
            else {
                if(this.pointSaleActive.code && this.pointSaleActive.code.length > 0) {
                    axios.get('ajax-validate-code-point-sale',{params: {
                        idPointSale: this.idPointSaleActive,    
                        code: this.pointSaleActive.code
                    }}).then(function(response) {
                        if(response.data) {
                            app.pointsSale[idPointSale].invalid_code = false ;
                        }
                        else {
                            app.pointsSale[idPointSale].invalid_code = true ;
                            Vue.set(app.pointsSaleCodes, idPointSale, '');
                        }
                    }) ;
                }
            }
            
            var regexDate = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;
   
            if(!this.dateBegin) {
                this.errors.push('Veuillez sélectionner une date de début') ;
            }
            else {
                if(!regexDate.test(this.formatDate(this.dateBegin))) {
                    this.errors.push('Mauvais format de date de début') ;
                }
            }
            
            if(this.dateEnd && this.dateEnd.length > 0 && !regexDate.test(this.formatDate(this.dateEnd))) {
                this.errors.push('Mauvais format de date de fin') ;
            }
            
            if(this.weekFrequency != 1 && this.weekFrequency != 2 && 
                this.weekFrequency != 3 && this.weekFrequency != 4) {
            
                this.errors.push('Veuillez sélectionner une périodicité') ;
            }
            
            if(!this.monday && !this.tuesday && !this.wednesday && !this.thursday && 
                !this.friday && !this.saturday) {
                this.errors.push('Veuillez sélectionner un jour de distribution') ;
            }
            
            if(!this.oneProductOrdered()) {
                this.errors.push('Veuillez choisir au moins un produit') ;
            }
            
            
            if(this.errors.length) {
                window.scroll(0, $('#page-title').position().top - 25) ;
            }
        }
    }
});