odoo.define('lefilament_tdb.previ_tresorerie', function (require) {
	"use strict";

	var core = require('web.core');
	var formats = require('web.formats');
	var Model = require('web.Model');
	var session = require('web.session');
	var Widget = require('web.Widget');

	var QWeb = core.qweb;

	var _t = core._t;
	var _lt = core._lt;

	var TresorerieView = Widget.extend({
	    template: 'Tresorerie',

	    init: function() {
	      var result = this._super.apply(this, arguments);
	      return result;
	    },

	    willStart: function() {
	        var deferred = new jQuery.Deferred();
	        var self = this;
	        this.values = {};
	        
	        var dash_model = new Model('lefilament.dashboard');
	        dash_model.call('previ_tresorerie')
                .then(function(results) {
                    self.values = results;
                    deferred.resolve();
                });
	          return jQuery.when(this._super.apply(this, arguments),deferred);
	    },

	    start: function() {
	    	console.log(this.values);
	    	return this.render_chart();
	    },

	    render_chart: function(chart) {
	    	self = this;

			/////////////////////////////////////////
            //      Trésorerie  -> Bar Chart       //
            /////////////////////////////////////////
            this.ctx = this.$el.find('#tresorerie')[0].getContext('2d');

            var labels = [];
            var data_months = [];
            var data_year = [];
            var month = moment().month();
            for (var i = -5; i < 7; i++) {
            	labels.push(moment().month(month + i).format("MMM YYYY"));
            	data_months.push(moment().month(month + i).format("MM"));
            	data_year.push(moment().month(month + i).format("YYYY-MM"));
            }
            var treso_r = this.reverse_array(this.values.tresorerie);

            var treso = [];
            var cca = [];
            var fonds_propres = [];
            
            var charges_an = 0;
            var charges_fixes_an = [];
            var charges_fixes = [];
            
            var client = 0;
            var f_client = [];
            var fournisseur = 0;
            var f_fournisseur = [];

            var previsionnel = [];
            

            for (var i = 0; i < 12 ; i++) {
            	// CCA + Fonds Propres
            	cca.push(this.values.fonds_propres.cca);
            	fonds_propres.push(this.values.fonds_propres.cca+this.values.fonds_propres.capital);
            	
            	// Trésorerie
            	if (treso_r[i]) { treso.push(treso_r[i].treso); }

            	// Calcul des factures
            	_.each( this.values.factures, function(value, key) {
	            	if (value.mois == data_year[i] ) {
	           			client = value.f_client; 
	           			fournisseur = value.f_fournisseur;         		
	            	}
	            });
            	if ( client > 0 ) { f_client.push(client); client = 0; } else { f_client.push(0); }
            	if ( fournisseur > 0 ) { f_fournisseur.push(fournisseur); fournisseur = 0; } else { f_fournisseur.push(0); }
            	
            	// Calcul des fixes annuelles
            	_.each( this.values.charges_fixes, function(value, key) {
	            	if (value.mois == data_year[i] ) {
	           			charges_an = value.sum;         		
	            	}
	            });
            	if ( charges_an > 0 ) { charges_fixes_an.push(charges_an); charges_an = 0; } else { charges_fixes_an.push(0); }

            	// Calcul charges fixes
            	if ( i < 5 ) { charges_fixes.push(null); }
            	else if ( i == 5 ) { charges_fixes.push(treso_r[5].treso); }
            	else {
            		// Trimestres
            		if (['01', '04', '07', '10'].indexOf(data_months[i]) >= 0) {
            			charges_fixes.push( this.values.charges_periode[0].sum + this.values.charges_periode[1].sum );
            		} else {
            			charges_fixes.push( this.values.charges_periode[1].sum );
            		}
            	}
            	
            }

            for (var i = 0; i < 12 ; i++) {
            	if (i > 4 ) {
            		previsionnel.push( previsionnel[i-1] + charges_fixes[i]+f_client[i]-f_fournisseur[i]-charges_fixes_an[i]);
            	} else { 
            		previsionnel.push(null); 
            	}
            }
            
   			var datasets = [
   				{ label: 'Trésorerie', data: treso, backgroundColor: 'transparent',borderColor: '#5E8ED5', },
   				{ label: 'Prévisionnel', data: previsionnel, backgroundColor: 'transparent',borderColor: 'rgba(94,142,213,0.5)', borderDash: [5,5] },
   				{ label: 'Client', data: f_client, backgroundColor: 'transparent',borderColor: '#51d2b7', borderWidth: 1.5, radius: 1, },
   				{ label: 'Fournisseur', data: f_fournisseur, backgroundColor: 'transparent',borderColor: '#FCA7B3', borderWidth: 1.5, radius: 1, },
   				{ label: 'CCA', data: cca, backgroundColor: 'transparent',borderColor: '#FFDFA9', borderWidth: 1.5, radius: 0, },
   				{ label: 'Fonds Propres', data: fonds_propres, backgroundColor: 'transparent',borderColor: '#A2BFEA', borderWidth: 1.5, radius: 0, },
		        ];

		    var options = {
			        scales: {
			            yAxes: [{
			                ticks: {
			                    beginAtZero:true,
			                }
			            }]
			        },
			        tooltips: {
		        	backgroundColor: 'rgba(255,255,255,0.8)',
		        	titleFontStyle: 'normal',
		        	titleFontColor: '#999',
		        	bodyFontColor: '#777',
		        	callbacks: {
	                    label: function(tooltipItems, data) { 
	                        return ' ' + (tooltipItems.yLabel / 1000).toLocaleString('fr', { maximumFractionDigits: 1 }) + ' k€';
	                    }
	                }
		        },
		        responsive: true,
			    }

		    this.targetData = {
	            labels : labels,
	            datasets : datasets
	        };

            var myChart = new Chart(this.ctx, { type: 'line', data: this.targetData, options: options } );

	    },
	    reverse_array: function(array) {
	    	var tabLength = array.length - 1;
	    	var new_array = [];
	    	for (var i = tabLength; i > -1; i--) {
	    		new_array.push(array[i]);
	    	}
	    	return new_array;
	    },

	});

	core.action_registry.add('lefilament_tdb.previ_tresorerie', TresorerieView);


});