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';
import { CONFIG } from '../../config';
import { filter, pairwise } from 'rxjs/operators';

@Component({
  selector: 'app-analitical-report',
  templateUrl: './analitical-report.component.html',
  styleUrls: ['./analitical-report.component.scss']
})
export class AnaliticalReportComponent implements OnInit {

  sub: any;
  type: any;
  user_id: any;
  userData: any = {};
  user_info: any;
  loader: boolean;
  report_data: any;
  sales_date: 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 },
  ]
  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;
  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 = '';
  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) { }

  ngOnInit() {

    this.sub = this.route.params.subscribe(params => {
      this.type = params['type'];
      this.user_id = params['id'];
      this.userData.emailid = params['email'];
      this.rmmail = params['rmmail'];
      this.ammail = params['ammail'];
      this.zmmail = params['zmmail'];
    });
    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.zmmail)
      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.rm_email = "all";
          this.am_email = "all";
          this.cont = (CONFIG.page_change) ? false : true;
          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 {
          // this.getDseReport(this.activePage)
          if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
            // this.zmReport(this.activePage)
            this.getDseReport(this.activePage,"zm")
          } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            // this.rmReport(this.activePage)
            this.getDseReport(this.activePage,"rm")
          } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            // this.amReport(this.activePage)
            this.getDseReport(this.activePage,"am")
          }
        }
      }

    }
    console.log(this.userData)
    this.location_selected = this.leader_type.filter(question => question.is_selected == 1);
  }
  //pagination
  public getServerData(event) {
    console.log(event)
    this.page_count = (event - 1);
    console.log('page', this.page_count)
    console.log(this.sales_date)
    if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
      // this.zmReport(this.activePage)
      this.getDseReport(this.page_count,"zm")
    } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
      // this.rmReport(this.activePage)
      this.getDseReport(this.page_count,"rm")
    } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
      // this.amReport(this.activePage)
      this.getDseReport(this.page_count,"am")
    }
    this.onPageChange(event);
  }
  public onPageChange(event) {
    this.activeItem = -1;
    this.activePage = event;
    console.log('pagech', this.activePage)
  }
  //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) {
          console.log(this.zmmail, CONFIG.page_change)
          this.zmuser_list = data.result.data;
          this.zmChange("all")
          // this.zmChange(this.zmuser_list[0])
        } 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 {
      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;
    // this.zmReport(this.activePage);
    this.getDseReport(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.rmChange("all")
          }
        } else if (data.result.status == 401 && data.result.response == 'failed') {
          this.router.navigateByUrl('');
        }
      });
  }
  rmChange(event) {
    console.log('2')
    console.log(event)
    this.am_email = "all"
    if (event == "all") {
      this.amInactive = true;
    } else {
      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;
    // this.rmReport(this.activePage);
    this.getDseReport(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.amChange("all")
          }
          
        } else if (data.result.status == 401 && data.result.response == 'failed') {
          this.router.navigateByUrl('');
        }
      });
  }
  amChange(event) {
    console.log('3')
    console.log(event)
    this.am_email = event;
    // LocalStorage.setValue("ammail", this.am_email)
    this.current_page = 0;
    this.activePage = 0;
    if (this.am_email != 'all') {
      this.getDseReport(this.activePage,"am");
    } else {
      this.getDseReport(this.activePage,"rm");
    }

    // this.getDseReport(this.activePage)
  }
 
  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;
        if (this.user_role != undefined && this.user_role < 4) {
          // LocalStorage.setValue('zmmail', this.zmmail)
          this.getZm();
        } else if (this.user_role != undefined && this.user_role < 6) {
          // this.cont = (CONFIG.page_change) ? false : true;
          // LocalStorage.setValue('rmmail', this.rmmail)
          this.getRm();
        } else if (this.user_role != undefined && this.user_role < 7) {
          // this.am_cont = (CONFIG.am_page_change) ? false : true;
          // LocalStorage.setValue('ammail', this.ammail)
          this.getAm();
        } else {
          this.current_page = 0;
          this.activePage = 0;
          // this.getDseReport(this.activePage)
          if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
            // this.zmReport(this.activePage)
            this.getDseReport(this.activePage,"zm")
          } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
            // this.rmReport(this.activePage)
            this.getDseReport(this.activePage,"rm")
          } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
            // this.amReport(this.activePage)
            this.getDseReport(this.activePage,"am")
          }
        }
      }
      else if (data.result.status == 401 && data.result.response == 'failed') {
        this.router.navigateByUrl('');
      }
      else {
        alert("Oops something happened!");
      }
    })
  }
  getDseReport(page: number = 0,role): any {
    this.loader = true
    if (this.selected_title == '') {
      this.sort_by = 0
    }
    if (this.mymodel == "") {
      this.mymodel = '';
    }
    this._url = "manager/newregistrationreport/"+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.am_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') {
          setTimeout(() => {
            this.loader = false;
            this.user_info = data.result.data;
            this.total_item = Number(data.result.total);
            console.log('UserData', this.user_info)
          }, 500);
        } else if (data.result.status == 401 && data.result.response == 'failed') {
          this.router.navigateByUrl('');
        }
      });
  }

  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()
  }

  isLocationSelected() {
    this.location_selected = this.leader_type.filter(question => question.is_selected == 1);
    this.current_page = 0;
    this.activePage = 0;
    // this.getDseReport(this.activePage)
    console.log(this.zm_email, this.rm_email, this.am_email)
    if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
      // this.zmReport(this.activePage)
      this.getDseReport(this.activePage,"zm")
    } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
      // this.rmReport(this.activePage)
      this.getDseReport(this.activePage,"rm")
    } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
      // this.amReport(this.activePage)
      this.getDseReport(this.activePage,"am")
    }
  }

  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;
    this._url = "managerexport/newregistrationreportexport/"+role+"?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() {
    return this.sanitizer.bypassSecurityTrustResourceUrl(this.export_url);
  }

  onSearchChange(searchValue: string) {
    this.mymodel = searchValue;
    console.log(this._url)
    this.current_page = 0;
    this.activePage = 0;
    // this.getDseReport(this.activePage)
    if (this.zm_email != undefined && this.zm_email != '' && this.rm_email == 'all' && this.am_email == 'all') {
      // this.zmReport(this.activePage)
      this.getDseReport(this.activePage,"zm")
    } else if (this.rm_email != undefined && this.rm_email != '' && this.am_email == 'all') {
      // this.rmReport(this.activePage)
      this.getDseReport(this.activePage,"rm")
    } else if (this.am_email != undefined && this.zm_email != 'all' && this.rm_email != 'all' && this.am_email != 'all') {
      // this.amReport(this.activePage)
      this.getDseReport(this.activePage,"am")
    }
  }

}
