odoo.define('lefilament_tdb.dashboard_year', 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 YearDashboardView = Widget.extend({
	    template: 'YearDashboard',

	    events: {
	        // 'click .card': function() { 
	        // 	this.mychart.reflow();
	        //  },
	        'click #facture_non_encaisse': function() {
	        	this.facture();
	        },
	        'click #commandes': function() {
	        	this.commandes();
	        },
	    },

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

	    willStart: function() {
	        var deferred = new jQuery.Deferred();
	        var self = this;
	        this.values = {};
	        this.progess = 0;
	        
	        var dash_model = new Model('lefilament.dashboard');
	        dash_model.call('retrieve_datas_dashboard')
                .then(function(results) {
                    self.values = results;
                    self.progress = results.facture / results.target;

                    self.pfact = (self.values.facture / self.values.target * 100).toFixed(0);
					self.pcomm = (self.values.commandes / self.values.target * 100).toFixed(0);
					self.ppipe_win = (self.values.pipe_win / self.values.target * 100).toFixed(0);
					self.ppipe_to_win = (self.values.pipe_to_win / self.values.target * 100).toFixed(0);
					self.ptarg = 100-self.pfact-self.pcomm-self.ppipe_win-self.ppipe_to_win;
					self.pfact2 = (self.values.facture);
					self.pcomm2 = (self.values.commandes);
					self.ppipe2_win = (self.values.pipe_win);
					self.ppipe2_to_win = (self.values.pipe_to_win);
					self.ptarg2 = self.values.target -self.pfact2-self.pcomm2-self.ppipe2_to_win-self.ppipe2_win;
					self.total2 = ((self.values.facture + self.values.commandes + self.values.pipe_win) / self.values.target * 100).toFixed(0);
					self.total = self.pfact + self.pcomm + self.ppipe_win
                    deferred.resolve();
                });
	          return jQuery.when(this._super.apply(this, arguments),deferred);
	    },

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

	    render_chart: function(chart) {
	    	self = this;

	    	/////////////////////////////////////////
            //    Etat d'avancement -> HighChart   //
            /////////////////////////////////////////

			// var hchart = this.$el.find('#hchart')[0];

	    	// Highcharts.setOptions({ colors: ['#8ED8A2', '#F6DCA2', '#F6CCA2', '#F6ACA2', '#eee'], });

			// this.mychart = new Highcharts.chart({
			// 	chart: {
			//         renderTo: hchart,
			//         type: 'pie',
			//         margin: 0
			//     },
			//     title: {
			//         text: '<span class="ca_target">'+
			// 	    	self.values.target.toLocaleString('fr', { maximumFractionDigits: 0 }) + ' € </span>',
			//         align: 'center',
			//         verticalAlign: 'middle',
			//         style: { 'color': '#73879C', 'font-size': '11px'  },
			//         y: -20,
			//     },
			//     plotOptions: {
			//         pie: {
			//         	slicedOffset: 0,
			//             size: '100%',
			//             dataLabels: {
			//                 enabled: false
			//             }
			//         },
			//         series: {
			//             states: {
			//                 hover: {
			//                     enabled: false
			//                 }
			//             }
			//         }
			//     },
			//     tooltip: { 
			//     	pointFormat: '<p class="point"><span class="point_percent">{point.percentage:.0f}% </span><br/> {point.y} €</p>',
			//     	backgroundColor: "rgba(255,255,255,0.85)",
			// 		borderColor: null,
			// 		borderRadius: 0,
			// 		borderWidth: 0,
			// 		useHTML: true,
			// 		shadow: false,
			// 	},
			//     series: [{
			//         type: 'pie',
			//         innerSize: '85%',
			//         data: [  ['Facturé', this.pfact2], ['Commandes', this.pcomm2], ['Gagné', this.ppipe2_win], ['Pipe', this.ppipe2_to_win], ['To Do', this.ptarg2], ],
			//         slicedOffset: 0,

			//     }],
			// });

			// this.mychart.reflow();

			/////////////////////////////////////////
            //    Etat d'avancement -> Bar Chart   //
            /////////////////////////////////////////
            
            this.ctx = this.$el.find('#target')[0].getContext('2d');
	    		
   			var dataset_stacked = [
		        { label: 'Facturé', data: [this.pfact2], backgroundColor: '#8ED8A2', },
		        { label: 'Commandes', data: [this.pcomm2], backgroundColor: '#F6DCA2', },
		        { label: 'Gagné', data: [this.ppipe2_win], backgroundColor: '#F6CCA2', },
		        { label: 'Pipe', data: [this.ppipe2_to_win], backgroundColor: '#F6ACA2', },
		        { label: 'To Do', data: [this.ptarg2], backgroundColor: '#eee', }];

		    var label = 'Année ' + moment(Date.now()).format('YYYY');

		    this.targetData = {
	            labels : [label],
	            datasets : dataset_stacked
	        };

            var options = { 
            	legend: {
            		display: false,
            		position: 'bottom',
            		fullWidth: false,
            	},
            	layout: { 
            		padding: { left:0, right: 0, bottom: 20, top: 20, },
            	},
            	scales: {
		            xAxes: [{
		                stacked: true,
		                scaleShowLabels: false,
                        display : false ,
		            }],
                    yAxes: [{
                            stacked: true,
                            scaleShowLabels: false,
                            display : false ,
                        }]
		        },
		        tooltips: {
		        	backgroundColor: 'rgba(255,255,255,0.8)',
		        	titleFontStyle: 'normal',
		        	titleFontColor: '#999',
		        	bodyFontColor: '#777',
		        	callbacks: {
	                    label: function(tooltipItems, data) { 
	                        return (tooltipItems.xLabel / 1000).toLocaleString('fr', { maximumFractionDigits: 2 }) + ' K€';
	                    }
	                }
		        },
		        responsive: true,
            }

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

	    },

	    render_monetary: function(value) {
	        value = value.toLocaleString('fr', { maximumFractionDigits: 0 }) + ' €';
	        return value;
	    },
	    render_keur: function(value) {
	        value = (value / 1000).toLocaleString('fr', { maximumFractionDigits: 0 }) + ' K€';
	        return value;
	    },
	    render_percent: function(value) {
	        value = value.toLocaleString('fr', { maximumFractionDigits: 1 }) + ' %';
	        return value;
	    },
	    render_date: function(value) {
	    	var dateFormat = new Date(value);
            var new_value = moment(dateFormat).format('Do MMM YYYY');
            return new_value;
	    },
	    render_monetary_color: function(value) {
	        if (value >= 0)
	          value = '<span class="positive">'+value.toLocaleString('fr', { maximumFractionDigits: 0 }) + ' €</span>';
	        else
	          value = '<span class="negative">'+value.toLocaleString('fr', { maximumFractionDigits: 0 }) + ' €</span>';
	        
	        return value;
	    },

	    facture: function() {
	    	var self = this;
	    	var context = { 'user_id': this.session.uid, }

        	var action = ({
            	type: 'ir.actions.act_window',
             	res_model: 'account.invoice',
            	view_type: 'form',
            	view_mode: 'tree,form',
            	views: [[false, 'list'], [false, 'form']],
            	domain: [['state','=','open'],['type','=','out_invoice']],
            	target:'current',
            	name: 'Factures en cours',
            	context: context
        	})

        	this.do_action(action);
	    },
	    commandes: function() {
	    	var self = this;
	    	var context = { 'user_id': this.session.uid, }

        	var action = ({
            	type: 'ir.actions.act_window',
             	res_model: 'sale.order',
            	view_type: 'form',
            	view_mode: 'tree,form',
            	views: [[false, 'list'], [false, 'form']],
            	domain: [['invoice_status','=','to invoice']],
            	target:'current',
            	name: 'Commandes en cours',
            	context: context
        	})

        	this.do_action(action);
	    },
	});

	core.action_registry.add('lefilament_tdb.dashboard_year', YearDashboardView);


});