
var app = new Vue({
    el: '#app-order-order',
    data: {
        loading: false,
        loadingInit: true,
        step: 'date',
        producer: null,
        user: null,
        date: null,
        dateFormat: null,
        distributions: [],
        distribution: null,
        pointsSale: [],
        pointSaleActive: null,
        pointsSaleCodes: [],
        products: [],
        comment: '',
        creditCheckbox: false,
        useCredit: false,
        errors: [],
        disableConfirmButton: false,
        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'
            }
        },
    },
    mounted: function() {        
        if($('#order-distribution-date').size() || $('#distribution-date').size()) {
            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.changeStep('point-sale') ;
        }
        
        this.init() ;
        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() {
            var app = this ;
            this.loading = true ;
            axios.get("ajax-infos",{params: {date : this.getDate()}})
                .then(function(response) {
                    app.producer = response.data.producer ;
                    app.user = response.data.user ;
                    app.useCredit = response.data.producer.use_credit_checked_default ;
                    app.calendar.attrs = [] ;
                    app.calendar.availableDates = [] ;
                    var distributions = response.data.distributions ;
                    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])
                            }) ;

                        }
                    }  
                    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,
                                }) ;
                            }
                        }
                    }
                    
                    if(response.data.distribution) {
                        app.distribution = response.data.distribution ;
                    }

                    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] ;
                            app.pointsSaleCodes[response.data.points_sale[key].id] = '' ;
                            Vue.set(app.pointsSaleCodes, response.data.points_sale[key].id, '');
                        }
                    }
                    
                    if(response.data.products) {
                        app.products = response.data.products ;
                    }
                    
                    app.order = null ;
                    if(response.data.order) {
                        app.order = response.data.order ;
                        app.pointSaleActive = app.getPointSale(response.data.order.id_point_sale) ;
                    }
                    else {
                        app.pointSaleActive = null ;
                    }
                    
                    app.loading = false ;
                });  
        },
        changeStep: function(step) {
            this.errors = [] ;
            var oldStep = this.step ;
            
            if(oldStep == 'products' && step == 'payment') {
                this.checkProducts() ;
            }
            if(!this.errors.length) {
                this.step = step ;
                window.scroll(0, $('#page-title').position().top - 25) ;
                if(oldStep == 'date' && step == 'point-sale') {
                    this.init() ;
                }
            }
            
        },
        dayClick: function(day) {
            if(this.isAvailableDate(day.date)) {
                this.date = day.date ;
                this.dateFormat = ('0' + this.date.getDate()).slice(-2)+ '/'
                        + ('0' + (this.date.getMonth() +1)).slice(-2) + '/'
                        + this.date.getFullYear() ;
                this.changeStep('point-sale') ;
            }
        },
        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.changeStep('products') ;
        },
        productQuantityClick: function(product, quantity) {
            console.log(this.products[product.index].quantity_remaining) ;
            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() {
            this.disableConfirmButton = true ;
            
            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 ;
                }
            }
            
            axios.post('ajax-process', {
                Order: {
                    id_distribution : this.distribution.id,
                    id_point_sale: this.pointSaleActive.id,
                    comment: this.comment
                },
                code_point_sale: this.pointsSaleCodes[this.pointSaleActive.id],
                products: productsArray,
                use_credit: Number(this.useCredit)
            }).then(function(response) {
                if(response.data.status == 'success') {
                    window.location.href = opendistrib_base_url(true)+'order/confirm?idOrder='+response.data.idOrder ;
                }
            });
        },
        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)) ;
        }
    },
    computed : {
        orderedPointsSale: function() {
            var orderedPointsSaleArray = this.pointsSale.sort(function(a, b) {
                if(a.order > b.order) {
                    return 1 ;
                }
                else {
                    return -1 ;
                }
            }) ;
            
            return orderedPointsSaleArray ;
        }
    }
});