import { Component, OnInit } from '@angular/core';
import * as moment from 'moment';
import { HyperService } from '../../core/services/http.service';
import { Router ,ActivatedRoute} from "@angular/router";
import { BarChart } from '../../core/services/bar_chart';
import { LocalStorage } from '../../core/services/local_storage.service';
import { CONFIG } from '../../config';

@Component({
    selector: 'app-dashboard-am-details',
    templateUrl: './dashboard-am-details.component.html',
    styleUrls: ['./dashboard-am-details.component.scss']
})
export class DashboardAmDetailsComponent implements OnInit {

    sales_date: any;
    userData: any = {};
    user_dashboard: any;
    percentage: any;
    user_type: any;
    certified_dse: any;
    assessment_data: any;
    barChartDataa: any = [];
    leader_board: any;
    access_token: any
    barchart_data: any = [];
    total_dse:any;
    total_user:any;
    user_role:number;
    amuser_list: any = [];
    rmuser_list: any = [];
    zmuser_list: any = [];
    am_email: string='';
    rm_email: string='';
    zm_email: string='';
    zm_zone:string;
    zm_zonename:string;
    sub: any;
    type: any;
    zmmail: string = '';
    rmmail: string = '';
    ammail: string = '';
    cont: boolean;
    am_cont: boolean;
    previousUrl: string;
    rmInactive: boolean;
    amInactive: boolean;
    zmEmail: any;
    zmData:any;
    rmData:any;
    amData:any;
    date_now: any;
    constructor(private route: ActivatedRoute,private server: HyperService, private router: Router) {
        // console.log(this.barChartData)
        this.sub = this.route.params.subscribe(params => {
            this.type = params['type'];
            this.rmmail = params['rmmail'];
            this.ammail = params['ammail'];
        });
        CONFIG.page_change = false;
        CONFIG.am_page_change = false;
        console.log(this.user_role,LocalStorage.getValue('signup_user').emailid,this.type,this.ammail,"hello")
    }
    ngOnInit() {
        LocalStorage.setValue('zmmail',{})
        LocalStorage.setValue('zmdata','')
        LocalStorage.setValue('rmdata','')
        LocalStorage.setValue('amdata','')
        this.access_token = LocalStorage.getValue('token')
        this.sales_date = moment().format("MMM YYYY") //current month and year
        this.date_now = moment(this.sales_date, "MMM YYYY").format("MMM YYYY");
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");

        let val = {
            "data": [],
            "label": ''
        }
        this.barChartDataa.push(val)
        console.log(this.barChartDataa[0])
        if(LocalStorage.getValue('user_data')!=undefined){
            this.userData = LocalStorage.getValue('user_data');
            this.user_role = LocalStorage.getValue('user_data').role;
            if(this.user_role!=undefined && this.user_role<4){
                this.zm_email = "all";
                this.rmmail = "all";
                this.ammail = "all";
                this.zmmail = "all";
                this.getZm();
            }else if(this.user_role!=undefined && this.user_role<6){
                this.rm_email = "all";
                this.am_email = "all";
                this.getRm();
            }else if(this.user_role!=undefined && this.user_role<7  ){
                this.am_email = "all";
                this.getAm();

            }else{
                if(this.user_role==14){
                    this.getLeaderBoard(LocalStorage.getValue('user_data').dealer.am_email);
                    this.am_email = LocalStorage.getValue('user_data').dealer.am_email;
                }else{
                    this.getLeaderBoard(LocalStorage.getValue('user_data').emailid);
                    this.am_email = LocalStorage.getValue('user_data').emailid;
                }

                if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
                    this.dashboarAm(y, m,"zm"); //Manager Dashboard details
                } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
                    this.dashboarAm(y, m,"rm");
                } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
                    this.dashboarAm(y, m,"am");
                }
            }
        }

    }
    //HO LOGGED
    getZm(){
        this.rmInactive = true;
        this.amInactive = true;
        this.server.post("manager/zone", {})
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                    this.zmuser_list = data.result.data;
                    this.zmChange("all")
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    }
    zmChange(event){
        console.log(event)
        this.rm_email = "all";
        this.am_email = "all";
        if (event == "all") {
            this.rmInactive = true;
            this.amInactive = true;
            this.zm_email = "all";
            // LocalStorage.setValue("zmmail", this.zm_email)
        } else {
            console.log('else')
            LocalStorage.setValue('zmdata',event);
            this.rmInactive = false;
            this.amInactive = true;
            this.zm_email = event;
            // LocalStorage.setValue("zmmail", this.zm_email)
            // this.cont = (CONFIG.page_change) ? false : true;
            this.zm_zone = event.zone;
            this.zm_zonename = event.email;
            this.getRm();

        }
        if (this.zm_email == 'all') {
            this.zmEmail = 'all';
          } else {
            this.zmEmail = this.zm_zonename;
          }


        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.dashboarAm(y, m, "zm");
    }
    // ZM LOGGED
    getRm(){
        console.log(this.user_role>3 && this.user_role!=5)
        this.server.post("manager/region", {
            zone : (this.user_role>3 && this.user_role!=5) ? LocalStorage.getValue('signup_user').emailid : this.zm_zonename,
            zonename : (this.user_role>3 && this.user_role==5) ? LocalStorage.getValue('signup_user').zone : this.zm_zone
        })
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                   console.log(data.result.data)
                   this.rmuser_list = data.result.data;
                   if (this.user_role != undefined && this.user_role==4 || this.user_role==5) {
                    this.zmEmail = this.userData.emailid;
                    this.rmChange("all")
                  }
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    }
    rmChange(event){
        this.am_email = "all"
        if (event == "all") {
            this.amInactive = true;

        } else {
            LocalStorage.setValue('rmdata',event);
            this.amInactive = false;
            this.rm_email = event;
            // LocalStorage.setValue("rmmail", this.rm_email)
            // this.am_cont = (CONFIG.am_page_change) ? false : true;
            this.getAm();
        }
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.dashboarAm(y, m, "rm");
    }

    // RM LOGGED
    getAm(){

        this.server.post("manager/area", {
            region : ((this.user_role<7 || this.user_role==14) && this.user_role!=6) ? this.rm_email : LocalStorage.getValue('signup_user').emailid
        })
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                   console.log(data.result.data)
                   this.amuser_list = data.result.data;
                   if (this.user_role != undefined && this.user_role==6) {
                    this.rm_email = this.userData.emailid;
                    this.amChange("all")
                  }

                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    }
    amChange(event){
        LocalStorage.setValue('amdata',event);
        this.am_email = event;
        // LocalStorage.setValue("ammail",this.am_email)
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.dashboarAm(y, m,"am");
        // this.getLeaderBoard(this.am_email);
    }
    dashboarAm(year, month, role){
        LocalStorage.setValue("temp_mth",month)
        LocalStorage.setValue("temp_yr",year)
        this.server.post("dashboard/newareamanagerdashboard/" + year + "/" + month +  "/" + role +"", {
            zmemail: this.zmEmail,
            rmemail: this.rm_email,
            amemail: (this.user_role < 7) ? this.am_email : (this.user_role == 14) ? this.userData.dealer.am_email : this.userData.emailid
        })
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                    this.user_dashboard = data.result.data;
                    this.getPercentage();
                    this.getDonutValues();
                    this.getbarValues();
                    this.total_dse = this.user_dashboard['learning'].total
                    this.total_user = this.user_dashboard['learning'].user_total
                    console.log(this.total_dse,this.total_user)
                    console.log(this.user_dashboard['learning'].total)
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });

    }
    //AM LOGGED
    dashboardDetails(year, month) {
        LocalStorage.setValue("temp_mth",month)
        LocalStorage.setValue("temp_yr",year)
        this.server.get("dashboard/managerdashboard/" + year + "/" + month + "")
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                    this.user_dashboard = data.result.data;
                    this.getPercentage();
                    this.getDonutValues();
                    this.getbarValues();
                    this.total_dse = this.user_dashboard['learning'].total
                    this.total_user = this.user_dashboard['learning'].user_total
                    // console.log(this.user_dashboard['learning'].total)
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    }

    getLeaderBoard(username) {
        this.server.post("dashboard/dashboardleaderboard", {
            area: username
        })
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                    this.leader_board = data.result.data;

                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    }

    public barChartOptions: any ;

    ////BAR CHART PROPERTIES???//////

    public barChartLabels: string[] = ['BASE', 'BRONZE', 'SILVER', 'GOLD']; //X Asix Label
    public barChartType: string = 'bar'; //Chart Type
    public barChartLegend: boolean = false; //Show Legend
    public barChartData: any = []

    getbarValues(){

        setTimeout(() => {
            this.barChartOptions =  {
                scaleShowVerticalLines: false,
                responsive: true,
                scaleShowValues: true,
                tooltips: false,
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero:true,
                            // max: Number(this.user_dashboard['learning'].total),
                        }
                    }]
                },
                animation: {
                    onComplete: function () {
                        var chartInstance = this.chart,
                            ctx = chartInstance.ctx;
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'bottom';
                        this.data.datasets.forEach(function (dataset, i) {
                            var meta = chartInstance.controller.getDatasetMeta(i);
                            meta.data.forEach(function (bar, index) {
                                var data = dataset.data[index];
                                ctx.fillText(data, bar._model.x, bar._model.y - 5);
                            });
                        });
                    }
                }
            };
            this.barChartData=[{
            data: [this.user_dashboard['learning'].basic, this.user_dashboard['learning'].bronze, this.user_dashboard['learning'].silver, this.user_dashboard['learning'].gold],
            label: ''
            }];
        }, 100);
    }

    public doughnutChartLabels: string[] = ['PUBLISHED', 'ACTIVE', 'EXPIRED'];
    // public doughnutChartData: number[] = [50, 22, 28];
    public doughnutChartData: any=[];
    public doughnutChartType: string = 'doughnut';
    getDonutValues(){

        this.doughnutChartData =   [this.user_dashboard['assessment'].published, this.user_dashboard['assessment'].active, this.user_dashboard['assessment'].expired]
    }

    public colors = [{
        backgroundColor: [
            '#ffc266',
            '#a6ff4d',
            '#e6e600'

        ]
    }];

    public barcolors = [{
        backgroundColor: [
            '#475729',
            '#C46C53',
            '#AAAAAA',
            '#E2BB4D'
        ]
    }];
    public chartClicked(e: any): void {
        console.log("here")
        console.log(e);
    }

    public chartHovered(e: any): void {
        console.log(e);
    }

    decreasMonth() {
        console.log('Decreasse')
        this.sales_date = moment(this.sales_date, "MMM YYYY").add(-1, 'months').format("MMM YYYY"); //- one month
        setTimeout(() => {
            let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
            let m = moment(this.sales_date, "MMM YYYY").format("MM");
            if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
                this.dashboarAm(y, m, "zm")
            } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
                this.dashboarAm(y, m, "rm")
            } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
                this.dashboarAm(y, m, "am")
            }
        }, 1200);
    }

    increasMonth() {
        let now = moment(this.sales_date, "MMM YYYY").format("YYYY-MM-DD");
        let tdyDate = moment(new Date()).format('YYYY-MM-DD');
        if (moment(now).isSame(tdyDate, 'month') == false && moment(now).isSameOrBefore(tdyDate, 'year') == true) {
            this.sales_date = moment(this.sales_date, "MMM YYYY").add(1, 'months').format("MMM YYYY"); //+ one month
            let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
            let m = moment(this.sales_date, "MMM YYYY").format("MM");
            if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
                this.dashboarAm(y, m, "zm")
            } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
                this.dashboarAm(y, m, "rm")
            } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
                this.dashboarAm(y, m, "am")
            }
        }
    }

    getPercentage() {
        this.percentage = Math.floor(this.user_dashboard.sales.achieved / this.user_dashboard.sales.target * 100);
        console.log(this.percentage)
    }

    viewSalesReport() {
        console.log('sales')
        this.router.navigateByUrl('salesreport');
        // this.router.navigateByUrl('salesreport/mobile/'+this.access_token);
    }

    viewDseReport() {
        console.log('dse')
        this.router.navigateByUrl('dsereport');
        // this.router.navigateByUrl('dsereport/mobile/'+this.access_token);

    }

    viewAssessmentReport() {
        console.log('assessment')
        this.router.navigateByUrl('assessmentreport');
        // this.router.navigateByUrl('assessmentreport/mobile/'+this.access_token);
    }

    viewSalesleaderBoard() {
      this.router.navigateByUrl('leaderboard-ranking');
    }

    viewAssessmentleaderBoard() {
      this.router.navigateByUrl('leaderboard-teamranking');
    }


}
