import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HyperService } from '../../core/services/http.service';
import { Router, NavigationEnd, RoutesRecognized } from "@angular/router";
import { LocalStorage } from '../../core/services/local_storage.service';
import * as moment from 'moment';
import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';
declare var $: any;
import { CONFIG } from '../../config';
import { filter, pairwise } from 'rxjs/operators';
import { a } from '@angular/core/src/render3';
@Component({
    selector: 'app-sales-report',
    templateUrl: './sales-report.component.html',
    styleUrls: ['./sales-report.component.scss']
})
export class SalesReportComponent implements OnInit {

    sub: any;
    type: any;
    user_id: any;
    userData: any = {};
    user_info: any;
    loader: boolean;
    report_data: any;
    sales_date: any;
    date_now: any;
    page_load: boolean;
    excel_load: boolean;
    export_url: any;
    location_selected: any;
    selected_title: any = '';
    mymodel: string = "";
    _url: any;
    leader_type = [
        { title: "All", id: "0", is_selected: 0, sort_by: 0 },
        { title: "Dealer", id: "1", is_selected: 0, sort_by: 1 },
        { title: "Location", id: "2", is_selected: 0, sort_by: 2 },
        // { title: "AM", id: "3", is_selected: 0, sort_by: 3 },
        // { title: "RM", id: "4", is_selected: 0, sort_by: 4 },
        // { title: "ZM", id: "5", is_selected: 0, sort_by: 5 }
    ]
    sort_by: 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;
    selected_index: number;
    active_product: number;
    total_item: number;
    page_per_size: number = 10;
    current_page: number;
    total_page: number;
    activeItem: number = -1;
    activePage: number = 1;
    page_count: number;
    zmmail: string = '';
    rmmail: string = '';
    ammail: string = '';
    mob_tempmth: string = '';
    mob_tempyr: string = '';
    cont: boolean;
    am_cont: boolean;
    previousUrl: string;
    rmInactive: boolean;
    amInactive: boolean;
    zmEmail: any;
    zmData: any;
    rmData: any;
    amData: any;
    constructor(private route: ActivatedRoute, private server: HyperService, private router: Router, private sanitizer: DomSanitizer) {
        this.sub = this.route.params.subscribe(params => {
            console.log(params)
            this.type = params['type'];
            this.user_id = params['id'];
            this.userData.emailid = params['email'];
            this.rmmail = params['rmmail'];
            console.log( this.rmmail)
            this.ammail = params['ammail'];
            console.log( this.ammail)
            this.zmmail = params['zmmail'];
            console.log( this.zmmail)
            this.mob_tempmth = params['mob_tempmth'];
            this.mob_tempyr = params['mob_tempyr'];
        });
        this.router.events
            .pipe(filter((e: any) => e instanceof RoutesRecognized),
                pairwise()
            ).subscribe((e: any) => {
                console.log(e[0].urlAfterRedirects);
                this.previousUrl = e[0].urlAfterRedirects// previous url
                LocalStorage.setValue('previous_Url', this.previousUrl)
            });
        if (LocalStorage.getValue('previous_Url') != '/dashboard') {
            CONFIG.page_change = false;
            CONFIG.am_page_change = false;
        }
        this.current_page = 0;
        this.activePage = 0;
        if (this.type == 'mobile') {
            console.log(this.mob_tempmth,this.mob_tempyr)
            this.sales_date = moment(('0' +this.mob_tempmth).slice(-2) + this.mob_tempyr, "MM YYYY").format("MMM YYYY");
            console.log(this.sales_date)
        } else if (this.type != 'mobile' && LocalStorage.getValue("temp_yr") != undefined || LocalStorage.getValue("temp_yr") != null || LocalStorage.getValue("temp_yr") != '') {
            this.sales_date = moment(LocalStorage.getValue("temp_mth") + LocalStorage.getValue("temp_yr"), "MM YYYY").format("MMM YYYY")
        } else {
            this.sales_date = moment().format("MMM YYYY") //current month and year
        }
        this.date_now = moment().format("MMM YYYY");
        console.log(this.date_now)
        if (this.type == 'mobile') {
            LocalStorage.setValue('token', this.user_id)
            // LocalStorage.setValue('zmmail', this.zmmail)
            // LocalStorage.setValue('rmmail', this.rmmail)
            // LocalStorage.setValue('ammail', this.ammail)
            this.getuserdetails() //Get Authentication token 

        } else {
            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.cont = (CONFIG.page_change) ? false : true;
                    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.am_cont = (CONFIG.am_page_change) ? false : true;
                    this.getAm();
                } else {
                    console.log(this.userData)
                    let m = moment(this.sales_date, "MMM YYYY").format("MM");
                    let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
                    // this.getSalesReport(y, m, this.activePage)
                    if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
                        this.getSalesReport(y, m,this.activePage, "zm")
                    } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
                        this.getSalesReport(y, m,this.activePage, "rm")
                    } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
                        this.getSalesReport(y, m,this.activePage, "am")
                    }
                }
            }

        }

        this.location_selected = this.leader_type.filter(question => question.is_selected == 1);
    }

    ngOnInit() {
        // this.zm_email = LocalStorage.getValue('zmdata')!='' &&  LocalStorage.getValue('zmdata')!=null && LocalStorage.getValue('zmdata')!=undefined ? LocalStorage.getValue('zmdata') : 'all'
        // this.rm_email = LocalStorage.getValue('rmdata')!='' &&  LocalStorage.getValue('rmdata')!=null && LocalStorage.getValue('rmdata')!=undefined ? LocalStorage.getValue('rmdata') : 'all'
        // this.am_email = LocalStorage.getValue('amdata')!='' &&  LocalStorage.getValue('amdata')!=null && LocalStorage.getValue('amdata')!=undefined ? LocalStorage.getValue('amdata') : 'all'
        // alert('zm'+this.zm_email+'rm'+this.rm_email+'am'+this.am_email);
    }

    //pagination
    public getServerData(event) {
        this.active_product = null;
        console.log(event)
        this.page_count = (event - 1);
        console.log('page', this.page_count)
        console.log(this.sales_date)
        // this.sales_date = moment().format("MMM YYYY") //current month and year
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
            this.getSalesReport(y, m,this.page_count, "zm")
        } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            this.getSalesReport(y, m,this.page_count, "rm")
        } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            this.getSalesReport(y, m,this.page_count, "am")
        }
        this.onPageChange(event);
    }
    public onPageChange(event) {
        this.activeItem = -1;
        this.activePage = event;
        console.log('pagech', this.activePage)
    }
    //HO LOGGED
    compareFn(a, b) {
        // console.log(a);
        // console.log(b);
        return a && b && a.name == b.name;
      }
      
    getZm() {
        this.zm_email = LocalStorage.getValue('zmdata')!='' &&  LocalStorage.getValue('zmdata')!=null && LocalStorage.getValue('zmdata')!=undefined ? LocalStorage.getValue('zmdata') : 'all'
        console.log(this.zm_email)
        this.server.post("manager/zone", {})
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                    console.log(data.result.data)
                    this.zmuser_list = data.result.data;
                    this.zm_email !='all' ? this.zmChange(this.zm_email) :  this.zmChange("all")
                    // this.zmChange("all")
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    }
    zmChange(event) {
        console.log(event)
        if (event == "all") {
            this.rmInactive = true;
            this.amInactive = true;
            this.zm_email = "all";
            this.rm_email = "all";
            this.am_email = "all";
            // LocalStorage.setValue("zmmail", this.zm_email)
        } else {
            this.rm_email = LocalStorage.getValue('rmdata')!='' &&  LocalStorage.getValue('rmdata')!=null && LocalStorage.getValue('rmdata')!=undefined ? LocalStorage.getValue('rmdata') : 'all'
            this.am_email = LocalStorage.getValue('amdata')!='' &&  LocalStorage.getValue('amdata')!=null && LocalStorage.getValue('amdata')!=undefined ? LocalStorage.getValue('amdata') : 'all'
            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;
          }
        this.current_page = 0;
        this.activePage = 0;
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.getSalesReport(y, m,this.activePage, "zm")
    }
    // ZM LOGGED
    getRm() {
        this.amInactive = true;
        this.server.post("manager/region", {
            zone: (this.user_role > 3 && this.user_role != 5) ? this.userData.emailid : this.zm_zonename,
            zonename: (this.user_role > 3 && this.user_role == 5) ? this.userData.zone : this.zm_zone
        })
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                    CONFIG.page_change = true;
                    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.rm_email !='all' && this.rm_email!='' && this.rm_email!=undefined && this.rm_email!=null ? this.rmChange(this.rm_email) :  this.rmChange("all")
                        // this.rmChange("all")
                      }else{
                        this.rm_email !='all' && this.rm_email!='' && this.rm_email!=undefined && this.rm_email!=null ? this.rmChange(this.rm_email) :  this.rmChange("all")
                      }
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    }
    rmChange(event) {
        console.log(event)
        // this.am_email = "all"
        if (event == "all") {
            this.amInactive = true;
            this.rm_email = "all";
            this.am_email = "all"
        } else {
            this.am_email = LocalStorage.getValue('amdata')!='' &&  LocalStorage.getValue('amdata')!=null && LocalStorage.getValue('amdata')!=undefined ? LocalStorage.getValue('amdata') : 'all'
            this.amInactive = false;
            this.rm_email = event;
            // LocalStorage.setValue("rmmail", this.rm_email)
            // this.am_cont = (CONFIG.am_page_change) ? false : true;
            this.getAm();
        }
        this.current_page = 0;
        this.activePage = 0;
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.getSalesReport(y, m,this.activePage, "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 : this.userData.emailid
        })
            .then((data) => {
                if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                    console.log(data.result.data)
                    CONFIG.am_page_change = true;
                    this.amuser_list = data.result.data;
                    if (this.user_role != undefined && this.user_role==6) {
                        this.rm_email = this.userData.emailid;
                        this.am_email !='all' && this.am_email!='' && this.am_email!=undefined && this.am_email!=null ? this.amChange(this.am_email) :  this.amChange("all")
                        // this.amChange("all")
                      }else{
                        this.am_email !='all' && this.am_email!='' && this.am_email!=undefined && this.am_email!=null ? this.amChange(this.am_email) :  this.amChange("all")
                      }
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }
            });
    }
    amChange(event) {
        this.am_email = event;
        // LocalStorage.setValue("ammail", this.am_email)
        // 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");
        this.current_page = 0;
        this.activePage = 0;
        this.getSalesReport(y, m,this.activePage, "am")
    }
    isLocationSelected() {
        this.location_selected = this.leader_type.filter(question => question.is_selected == 1);
        // this.sales_date = moment().format("MMM YYYY") //current month and year
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.current_page = 0;
        this.activePage = 0;
        if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
            this.getSalesReport(y, m,this.activePage, "zm")
        } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            this.getSalesReport(y, m,this.activePage, "rm")
        } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            this.getSalesReport(y, m,this.activePage, "am")
        }
    }

    getuserdetails() {
        this.loader = true;
        this.updateMobileView();
    }
    updateMobileView() {
        this.server.get("user/profile").then((data) => {
            if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                this.userData = data.result.data;
                LocalStorage.setValue('user_data', this.userData)
                this.user_role = this.userData.role;
                console.log("here" + this.user_role)
                if (this.user_role != undefined && this.user_role < 4) {
                    this.getZm();
                } else if (this.user_role != undefined && this.user_role < 6) {
                    this.cont = (CONFIG.page_change) ? false : true; 
                    this.getRm();
                } else if (this.user_role != undefined && this.user_role < 7) { 
                    this.am_cont = (CONFIG.am_page_change) ? false : true;
                    this.getAm();
                } else {
                    console.log(this.userData)
                    //this.sales_date = moment().format("MMM YYYY") //current month and year
                    let m = moment(this.sales_date, "MMM YYYY").format("MM");
                    let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
                    this.current_page = 0;
                    this.activePage = 0;
                    if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
                        this.getSalesReport(y, m,this.activePage, "zm")
                    } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
                        this.getSalesReport(y, m,this.activePage, "rm")
                    } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
                        this.getSalesReport(y, m,this.activePage, "am")
                    }
                }
            }
            else if (data.result.status == 401 && data.result.response == 'failed') {
                this.router.navigateByUrl('');
            }
            else {
                alert("Oops something happened!");
            }
        })
    }
    getSalesReport(year, month, page, role) {
        console.log(year, month, page, role)
        this.loader = true
        // this.mymodel == "" 
        LocalStorage.setValue("temp_mth",month)
        LocalStorage.setValue("temp_yr",year)
        if (this.selected_title == '') {
            this.sort_by = 0
        }
        if (LocalStorage.getValue("temp_yr") == undefined || LocalStorage.getValue("temp_yr") == null || LocalStorage.getValue("temp_yr") == '' && this.type != 'mobile') {
            this._url = "manager/newsalesreport/" + year + "/" + month +  "/" + role +"?page=" + page + "&limit=10" + "&filter=sort:" + this.sort_by + "";
        } else if (this.type == 'mobile') {
            this._url = "manager/newsalesreport/" + this.mob_tempyr + "/" + this.mob_tempmth + "/" + role +"?page=" + page + "&limit=10" + "&filter=sort:" + this.sort_by + "";
        } else {
            this._url = "manager/newsalesreport/" + LocalStorage.getValue("temp_yr") + "/" + LocalStorage.getValue("temp_mth") +  "/" + role + "?page=" + page + "&limit=10" + "&filter=sort:" + this.sort_by + "";
        }

        this.server.post(this._url, {
            search: this.mymodel,
            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
            // area: (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') {
                    setTimeout(() => {
                        this.loader = false
                        this.user_info = data.result.data;
                        this.total_item = Number(data.result.total);
                        console.log('Length', this.user_info.length)
                    }, 500);
                } else if (data.result.status == 401 && data.result.response == 'failed') {
                    this.router.navigateByUrl('');
                }

            });

    }

    increasMonth() {
        let now = moment(this.sales_date, "MMM YYYY").format("YYYY-MM-DD");
        console.log(now)
        let tdyDate = moment(new Date()).format('YYYY-MM-DD');
        console.log(tdyDate)
        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");
            this.loader = true
            this.current_page = 0;
            this.activePage = 0;
            if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
                this.getSalesReport(y, m,this.activePage, "zm")
            } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
                this.getSalesReport(y, m,this.activePage, "rm")
            } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
                this.getSalesReport(y, m,this.activePage, "am")
            }
        }
    }

    decreasMonth() {
        this.loader = true
        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");
            this.current_page = 0;
            this.activePage = 0;
            if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
                this.getSalesReport(y, m,this.activePage, "zm")
            } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
                this.getSalesReport(y, m,this.activePage, "rm")
            } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
                this.getSalesReport(y, m,this.activePage, "am")
            }
        }, 1200);
    }
    showDetails(val, list) {
        console.log(val, list)
        console.log(this.active_product)
        this.selected_index = val;
        if (this.active_product == val) {
            this.active_product = null;
        } else {
            this.active_product = val;
        }
    }

    clickExcelDownload() {
        console.log(this.zm_email,this.zm_zonename)
        if (this.zm_email == 'all') {
          this.zmData = 'all';
          this.rmData = '';
          this.amData = '';
          this.roleBasedExcel("zm")
        } else if (this.zm_email != undefined && this.zm_email != '' && this.zm_email != 'all' && this.rm_email == 'all' ) {
          this.zmData = this.zm_zonename;
          this.rmData = '';
          this.amData = '';
          this.roleBasedExcel("zm")
        } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
          this.zmData = this.zm_zonename;
          this.rmData = this.rm_email;
          this.amData = '';
          this.roleBasedExcel("rm")
        } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
          this.zmData = '';
          this.rmData = this.rm_email;
          this.amData = (this.user_role < 7) ? this.am_email : (this.user_role == 14) ? this.userData.dealer.am_email : this.userData.emailid;
          this.roleBasedExcel("am")
        }
    
      }
    roleBasedExcel(role) {
        this.loader = true;
        this.excel_load = true;
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this._url = "managerexport/newsalesreportexport/" + y + "/" + m + "/" +role+"?page=0&limit=10&filter=sort:" + this.sort_by;
        this.server.post(this._url, {
          zmemail: this.zmData,
          rmemail: this.rmData,
          amemail: this.amData
        }).then((data) => {
          if (data.status == 200) {
            this.loader = false;
            this.export_url = (data.result.data);
            setTimeout(() => this.export_url = "", 1000);
            this.excelExport();
          } else {
            alert("error");
          }
        });
      }
    excelExport() {
        console.log("here" + this.export_url)
        return this.sanitizer.bypassSecurityTrustResourceUrl(this.export_url);

    }

    radioSelect(val) {
        for (let i = 0; i < this.leader_type.length; i++) {
            if (val == i) {
                this.leader_type[i].is_selected = 1;
                this.selected_title = this.leader_type[i].title
                this.sort_by = this.leader_type[i].sort_by
                console.log(this.selected_title)
            } else { this.leader_type[i].is_selected = 0; }
        }
        this.isLocationSelected()
    }

    onSearchChange(searchValue: string) {
        console.log(searchValue)
        this.mymodel = searchValue;
        this.sales_date = moment().format("MMM YYYY") //current month and year
        let m = moment(this.sales_date, "MMM YYYY").format("MM");
        let y = moment(this.sales_date, "MMM YYYY").format("YYYY");
        this.current_page = 0;
        this.activePage = 0;
        if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
            this.getSalesReport(y, m,this.activePage, "zm")
        } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            this.getSalesReport(y, m,this.activePage, "rm")
        } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            this.getSalesReport(y, m,this.activePage, "am")
        }
    }
}