import { Component, Injector, OnInit, ViewChild, ViewEncapsulation, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AppConsts } from '@shared/AppConsts';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { RouteListDto, RouteServiceProxy, ControllerKpiCountServiceProxy } from '@shared/service-proxies/service-proxies';

import * as moment from 'moment';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { HttpClient } from '@angular/common/http';
import { finalize } from 'rxjs/operators';
import { Subscription }  from 'rxjs';
import { ControllerRoutesService } from '@app/sprintship/controller/routes/croutes.service';


@Component({
	selector: 'kpi-box',
    templateUrl: './kpi-box.component.html',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./kpi-box.component.less'],
    animations: [appModuleAnimation()]
})

export class KPIBoxComponent extends AppComponentBase implements OnInit {
    hide : boolean;
    isLoading : boolean;
    @Input('statistics') statistics: {
        total_vehicles: number,
        total_packages: number
    };
    @Input ('total_packages') total_packages: number;
    @Input ('total_vehicles') total_vehicles: number;
    @Input() filters: {
        locationFilter: number;
        statusFilter: number;
        typeFilter: number;
        startDate: Date;
        endDate: Date
    } = < any > {};
    subscription: Subscription;
	constructor(
        injector: Injector,
        private _routeService: RouteServiceProxy,
        private _cRoutesService: ControllerRoutesService,
        private _cKpiCountService: ControllerKpiCountServiceProxy
    ) {
        super(injector);
        var that = this;
        this.subscription = _cRoutesService.setStatisticsObj.subscribe(details=> {
            // console.log('RECEIVED');
            // console.log(details);
            that.total_packages = details.total_packages;
            that.total_vehicles = details.total_vehicles;
        });
    }

    ngOnInit(): void {
        // this.total_packages = this.statistics.total_packages;
   
    }
    getKpiCount(): void {
        this.isLoading = true;
        this.filters.startDate = new Date(this.filters.startDate.toString());
        this.filters.endDate = new Date(this.filters.endDate.toString());
        let startDate = moment(moment(this.filters.startDate).format('YYYY-MM-DD HH:mm:ss'));
        let endDate = moment(moment(this.filters.endDate).format('YYYY-MM-DD HH:mm:ss'));

        let startDateA = startDate['_i'].split(' ');
        startDateA = startDateA[0] + ' ' + '00:00:00';

        let endDateA = endDate['_i'].split(' ');
        endDateA = endDateA[0] + ' ' + '23:59:59';
      

        this._cKpiCountService.getControllerKpiCount(
            undefined,
            this.filters.locationFilter,
            moment.utc(moment(startDateA).toISOString()),
            moment.utc(moment(endDateA).toISOString())
        ).subscribe(
            result => {
            var key;
            let unassigned = 0;
            let remaining_pickup = 0;
            let remaining_deliveries = 0;   
            let with_issues = 0;
            let picked_up = 0;
            let delivered = 0;
            let completion_rate = 0;
            this.isLoading = false;

            for (key in result) 
            {   
                switch(result[key].code)
                {
                    case "ARRIVED" :
                        picked_up = picked_up + result[key].orderId
                        break;
                    case "WAITING_PICKUP" :
                        remaining_pickup = remaining_pickup + result[key].orderId
                        break;
                    case "PICKED_UP" :
                        picked_up = picked_up + result[key].orderId
                        break;
                    case "IN_TRANSIT" :
                        picked_up = picked_up + result[key].orderId
                        break;
                    case "DELIVERED" :
                        delivered = delivered + result[key].orderId
                        break;
                    case "PICKUP_IN_TRANSIT" :
                        remaining_pickup = remaining_pickup + result[key].orderId
                        break;
                    case "ARRIVED_PICKUP" :
                        remaining_pickup = remaining_pickup + result[key].orderId
                        break;
                    case "DELIVERY_IN_TRANSIT" :
                        picked_up = picked_up + result[key].orderId
                        break;
                    case "ARRIVED_DELIVERY" :
                        picked_up = picked_up + result[key].orderId
                        break;
                    case "DELIVERY_ISSUE" :
                        with_issues = with_issues + result[key].orderId
                        break;
                    case "WAREHOUSE_IN_TRANSIT" :
                        picked_up = picked_up + result[key].orderId
                        break;
                    case "WAREHOUSE" :
                        remaining_pickup = remaining_pickup + result[key].orderId
                        break;
                }
                
            }

            this._cKpiCountService.getUnassignedPackagesCount(
                undefined,
                this.filters.locationFilter,
                moment.utc(moment(startDateA).toISOString()),
                undefined
            ).subscribe(result => {
                if (result > 0)
                {
                    unassigned = unassigned + result;
                    
                    $('#box-unassigned').css('cursor', 'pointer');
                    $('#box-unassigned').click(function(){
                        window.open('app/sprintship/unassigned-packages', '_blank');
                    });
                } 
                else 
                {
                    $('#box-unassigned').css('cursor', 'auto');
                }

                $('#unassigned').html(unassigned.toString());
                $('#remaining_pickup').html(remaining_pickup.toString());
                $('#remaining_deliveries').html((picked_up + remaining_pickup).toString());
                $('#with_issues').html(with_issues.toString());
                $('#picked_up').html(picked_up.toString());
                $('#delivered').html(delivered.toString());
                $('#completion_rate').html(((delivered/(picked_up + remaining_pickup) * 100 || 0 ).toFixed(2) + '%'));
                $('#total_packages').html((picked_up + remaining_pickup + with_issues + delivered + unassigned).toString());
            });
        });
        
        this._cKpiCountService.getControllerVehicleCount(
            undefined,
            this.filters.locationFilter,
            moment.utc(moment(startDateA).toISOString()),
            moment.utc(moment(endDateA).toISOString()),
            undefined,
            undefined,
            undefined
        ).subscribe(result => {
            $('#total_vehicles').html('0');
            if (result.length > 0 )
            {
                $('#total_vehicles').html(result[0].vehicleId.toString());
            }
        });
    }
}