import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { BaseComponent } from '../base/base.component';
import { StatsService } from '../_services/index';
import { AuthenticationService } from '../_services/authentication.service';
import * as _ from 'lodash';
import * as moment from 'moment';

@Component({
    moduleId: module.id.toString(),
    selector: 'app-negocio',
    templateUrl: 'negocio.component.html',
    styleUrls: ['negocio.component.scss']
})

export class NegocioComponent extends BaseComponent implements OnInit, OnDestroy {
    public stats: any;
    public data: any;
    public liveData: any;
    public userData: any;
    public drivers: any = [];
    public client;

    public dates = [];
    public total = [];
    public trucks = [];
    public tp = [];
    public options = {};

    // Filter
    public filter = {
        NroCliente: null,
        Desde: null,
        Hasta: null
    };
    public filterTopDrivers = {
        NroCliente: null,
        Desde: null,
        Hasta: null
    };
    public filterKPI = {
        NroCliente: null,
        Desde: null,
        Hasta: null
    };
    public currentDate;
    public yearRange;

    // Private
    private sub: any;

    constructor(
        private statsService: StatsService,
        private auth: AuthenticationService,
        private router: Router
    ) {
        super();

        this.userData = JSON.parse(localStorage.getItem('userData'));

        const from = moment().subtract(7, 'd').format(this.CONSTANTS.dateFormat.date);
        const to = moment().format(this.CONSTANTS.dateFormat.date);
        this.filter = { NroCliente: this.client, Desde: from, Hasta: to };
        this.filterTopDrivers = { NroCliente: this.client, Desde: from, Hasta: to };
        this.filterKPI = { NroCliente: this.client, Desde: from, Hasta: to };

        const today = new Date();
        this.currentDate = today;
        this.yearRange = '2010:' + today.getFullYear();

        this.sub = auth.currentClient$.subscribe(
            currentClient => {
                this.client = currentClient;
                localStorage.setItem('client', this.client);
                this.filter.NroCliente = currentClient;
                this.filterTopDrivers.NroCliente = currentClient;

                this.getStats();
                this.topDrivers();
                this.livePercentage();
            });
        this.getClient();
    }

    ngOnInit() { }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }

    getClient() {
        const client = localStorage.getItem('client');
        if (this.client !== client) {
            this.client = client;
            this.auth.setCurrentClient(this.client);
        }
    }

    getStats() {
        this.filter.Desde = moment(this.filter.Desde).format(this.CONSTANTS.dateFormat.date);
        this.filter.Hasta = moment(this.filter.Hasta).format(this.CONSTANTS.dateFormat.date);

        this.statsService.getStats(this.filter).subscribe((stats: any) => {
            if (stats.msg === 'OK') {
                this.stats = stats.datos;
                this.dates = _.map(this.stats, 'Fecha');
                this.tp = _.map(this.stats, 'TP');
                this.trucks = _.map(this.stats, 'Camiones');

                this.total = _.map(this.stats, function(elem) {
                    return elem.Pedidos.length;
                });

                // dividir entre 60 para obtener minutos
                this.tp = _.map(this.tp, function(elem) {
                    return (elem / 60);
                });

                this.data = {
                    labels: this.dates,
                    datasets: [
                        {
                            label: 'Promedio entrega (min) / día',
                            data: this.tp,
                            fill: false,
                            borderColor: '#4bc0c0'
                        }
                    ]
                };

                const that = this;

                this.options = {
                    responsive: false,
                    maintainAspectRatio: false,
                    tooltips: {
                        mode: 'label',
                        callbacks: {
                            label: function(tooltipItem, data) {
                                const indice = tooltipItem.index;
                                const first = 'Pedidos: ' + that.total[indice];
                                const second = 'Camiones: ' + that.trucks[indice];
                                const tool = [first, second];
                                return  tool;
                            }
                        }
                    }
                };
            }
        }, err => this.handleError(err));

    }

    /* Top drivers table */
    topDrivers() {
        this.filterTopDrivers.Desde = moment(this.filterTopDrivers.Desde).format(this.CONSTANTS.dateFormat.date);
        this.filterTopDrivers.Hasta = moment(this.filterTopDrivers.Hasta).format(this.CONSTANTS.dateFormat.date);

        this.statsService.topDrivers(this.filterTopDrivers).subscribe((drivers: any) => {
            this.drivers = drivers.datos;
        }, err => this.handleError(err));
    }

    livePercentage() {
        const data = {
            NroCliente: this.client
        };

        this.statsService.livePercentage(data).subscribe((result: any) => {
            let verde = result.PedidosTiempoOk.length;
            let amarillo = result.PedidosTiempoLimite.length;
            let rojo = result.PedidosTiempoCumplido.length;
            let suma = verde + amarillo + rojo;

            verde = (verde * 100) / suma;
            amarillo = (amarillo * 100) / suma;
            rojo = (rojo * 100) / suma;

            this.liveData = {
                labels: ['Cumplido', 'Por vencer', 'No cumplido'],
                datasets: [
                    {
                        data: [verde, amarillo, rojo],
                        backgroundColor: [
                            '#2ec144',
                            '#ffea30',
                            '#cc0e0e'
                        ],
                        hoverBackgroundColor: [
                            '#2ec144',
                            '#ffea30',
                            '#cc0e0e'
                        ]
                    }

                ]
            };

            this.options = {
                tooltips: {
                    mode: 'label',
                    enabled: true,
                    callbacks: {
                        label: function(tooltipItem, data) {
                            console.log(data);
                            const dataset = data.datasets[tooltipItem.datasetIndex];
                            const currentValue = dataset.data[tooltipItem.index];
                            const currentLabel = data.labels[tooltipItem.index];

                            return currentLabel + ': ' + currentValue + ' %';
                        }
                    }
                }
            };
        }, err => this.handleError(err));
    }

    getKPI() {
        console.log('getKPI');
    }

    private handleError(error: any): Promise<any> {
        console.error(this.constructor.name + ': An error occurred', error);
        if (error.error.msg === this.CONSTANTS.servicesMsg.NOT_AUTHORIZED) {
            this.auth.logout();
            this.router.navigate(['/login']);
        }
        return Promise.reject(error.message || error);
    }
}
