import { Component, OnInit } from '@angular/core';
import * as moment from 'moment';
import { HyperService } from '../../core/services/http.service';
import { Router } from "@angular/router";
import { LocalStorage } from '../../core/services/local_storage.service';
import { listenToElementOutputs } from '@angular/core/src/view/element';
@Component({
  selector: 'app-leaderboard-ranking',
  templateUrl: './leaderboard-ranking.component.html',
  styleUrls: ['./leaderboard-ranking.component.scss']
})
export class LeaderboardRankingComponent implements OnInit {

  is_selected: any = [];
  is_selected_loc: any;
  is_selected_role: any;
  year: any = [];
  month: any = [];
  sel_loc_val: any;
  sel_role_val: any;
  sales_date: any;
  user_dashboard: any;
  percentage: any;
  loader: boolean;
  leader_deatail: any = [];
  user_data: any=[];
  total_count: any;
  leader_type: any;
  is_filter: boolean = true;
  filter_year: any;
  filter_month: any;
  filter_date: any;
  selected_type: any = 1;
  times = {
    year: 31557600,
    month: 2629746,
    day: 86400,
    hr: 3600,
    min: 60,
    sec: 1
  }
  location_arr: any = [];
  role_arr: any = [];
  user_role: any;
  rolewise: string = '';
  date_now: any;
  is_team: boolean = false;
  selectTabId: string;
  zmmail: string = '';
  rmmail: string = '';
  ammail: string = '';
  rmInactive: boolean;
  amInactive: boolean;
  amuser_list: any = [];
  rmuser_list: any = [];
  zmuser_list: any = [];
  am_email: string = '';
  rm_email: string = '';
  zm_email: string = '';
  zmEmail: any;
  zm_zone: string;
  zm_zonename: string;
  userData:any;
  selectedRole:string;
  user_data_assessment:any=[];
  leader_assessment:any=[]
  constructor(private server: HyperService, private router: Router) {
    console.log(location, 'loc');
    if (this.router.url == '/leaderboard-ranking') {
      this.is_team = false;
    } else {
      this.is_team = true;
    }
    this.is_selected[0] = 'selected';
    
    
    if (LocalStorage.getValue('user_data') != undefined) {
      this.userData = LocalStorage.getValue('user_data');
      this.user_role = LocalStorage.getValue('user_data').role;
    }
    if (this.user_role != 15) {
      this.leader_type = [
        { title: "SALES", id: "0" },
        { title: "ASSESSMENT", id: "1" }
      ]
    } else {
      this.selected_type = 0;
      this.is_filter = false;
      this.leader_type = [
        { title: "ASSESSMENT", id: "1" }
      ]

    }

  }

  ngOnInit() {
    
    this.filter_date = moment().format("MMM YYYY")
    this.date_now = moment(this.filter_date, "MMM YYYY").format("MMM YYYY");
    this.month= moment(this.filter_date, "MMM YYYY").format("MM");
    this.year= moment(this.filter_date, "MMM YYYY").format("YYYY");
    this.setIndex(0);
    // this.initFilter();
    // this.getRoleLocation();
    // this.setIndexLocRank(0);
    // setTimeout(() => {
    //   this.getLeaderDetails()
    // }, 500);
    // if(this.is_team){
    //   if (this.user_role == 3) {
    //     this.setTab('1')
    //   } else if (this.user_role < 6) {
    //     this.setTab('2')
    //   } else if (this.user_role < 7) {
    //     this.setTab('3')
    //   } else {
        
    //     this.setTab('4')
    //   }
    // }
    

  }
  setIndex(i) {
    this.loader = true;
    // debugger;
    if (i == 0) {
      // this.getLeaderDetails(1, yy, mm, "");
      this.is_filter = true;
      this.rolewise = "area";
    }
    else if (i == 1) {
      this.rolewise = "area";
      // this.getLeaderDetails(2, yy, mm, "");
      this.is_filter = false;

    }
    for (let i = 0; i <= 1; i++) {
      this.is_selected[i] = ""
    }
    this.is_selected[i] = "selected";
    this.selected_type = i + 1;
    
    if(this.is_team){
      
      if (this.user_role == 3) {
        // this.setTab('1')
        this.setTab('5')
      } else if (this.user_role < 6) {
        this.setTab('2')
      } else if (this.user_role < 7) {
        this.setTab('3')
      } else {
        this.am_email = this.userData.emailid;
        
        this.setTab('4')
        
      }
    }else{
      
      this.getLeaderDetails(this.year,this.month)
    }
    // setTimeout(() => {
    //   this.getLeaderDetails()
    // }, 500);
  }
  setTab(id) {
    
    
    this.selectTabId = id;
    if(this.selectTabId=='1'){
      if(this.user_role<6){
        this.rmmail = "";
        this.ammail = "";
        this.zm_email = "";
        this.zmmail = "";
       
      }
      this.selectedRole = 'ZM'
    }else if(this.selectTabId=='2'){
      if(this.user_role<6){
        this.rmmail = "";
        this.ammail = "";
      }
      this.selectedRole = 'RM'
    }else if(this.selectTabId=='3'){
      this.selectedRole = 'AM'
    }else if(this.selectTabId=='4'){
      this.selectedRole = 'DSE'
        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 {
          this.am_email = this.userData.emailid;
        }
    }
    else if(this.selectTabId=='5'){
      if(this.user_role<6){
        this.rmmail = "";
        this.ammail = "";
      }
      this.selectedRole = 'TR'
    }
    
    setTimeout(() => {
      this.getLeaderDetails(this.year,this.month)
    }, 500);
  }
  setIndexLocRank(j) {
    //   for (let j = 0; j <=this.location_arr.length; j++) {
    //     this.is_selected_loc[j] = ""
    //   }
    //  this.is_selected_loc[j] = "selected";
    this.sel_loc_val = j;
    console.log(j, this.sel_loc_val, this.location_arr, j)
  }
  setIndexRole(j) {
    // for (let j = 0; j <=this.role_arr.length; j++) {
    //   this.is_selected_role[j] = "";
    // }
    // this.is_selected_role[j] = "selected";
    // this.location_arr=this.role_arr[index].location;
    this.role_arr.forEach(element => {
      if (element.id == j) {
        this.location_arr = element.location;
        this.sel_loc_val = this.location_arr[0].id;
      }
    });
    // console.log(this.location_arr,index,this.role_arr)
    this.sel_role_val = j;
  }
  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")
          // 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;
      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.filter_date = moment().format("MMM YYYY")
    
    this.getLeaderDetails(this.year,this.month)
  }
  // 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) {
          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;
      this.getAm();
    }
    
    this.getLeaderDetails(this.year,this.month)
  }
  // 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)
          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;
    
    this.getLeaderDetails(this.year,this.month)
  }
  getRoleLocation() {
    console.log("innn")
    this.server.get("leaderboard/location").then((data) => {
      if (data.status == 200) {
        this.loader = false;
        if (this.is_team) {
          this.role_arr = data.result.data.teamrank;
          this.location_arr = data.result.data.teamrank[0].location;
          this.sel_role_val = this.role_arr[0].id;
          this.sel_loc_val = this.location_arr[0].id;
          this.is_selected_role = this.location_arr[0].title;
        } else {
          this.location_arr = data.result.data.myrank;
          this.is_selected_loc = this.location_arr[0].title;
          this.sel_loc_val = this.location_arr[0].id;
        }


        console.log(this.location_arr, this.location_arr[0], "heyyyyyyyyyy")
      } else {
        alert("error");
      }
    });
  }

  initFilter() {
    this.filter_date = moment().format("MMM YYYY")//current month and year
    this.month = moment(this.filter_date, "MMM YYYY").format("MM");
    this.year = moment(this.filter_date, "MMM YYYY").format("YYYY");
    this.date_now = moment(this.filter_date, "MMM YYYY").format("MMM YYYY");
    this.rolewise = "area";
    this.changeRole("area");
    this.changeRoleSales("area");
    if (this.user_role != 15) {
      this.leader_type = [
        { title: "SALES", id: "0" },
        { title: "ASSESSMENT", id: "1" }
      ]
    } else {
      this.selected_type = 0;
      this.is_filter = false;
      this.leader_type = [
        { title: "ASSESSMENT", id: "1" }
      ]

    }
    // this.getLeaderDetails(this.selected_type, yy, mm, "");
    // console.log(mm, yy)
  }



  getLeaderDetails(year, month) {
    console.log(this.zmEmail,this.rm_email,this.am_email)
    this.loader = true;
    // this.user_data=[];
    // this.leader_deatail=[];
    // this.user_data_assessment=[];
    // this.leader_assessment=[];
    let t = '';
    if (this.is_team) {
      // t = (this.selected_type == 1) ? 'myteamsales' : 'myteamassessment';
      if(this.selected_type == 1){
        this.salesTeamRanking(year, month)
      }else{
        this.assessmentTeamRanking(year, month)
      }
    } else {
      // t = (this.selected_type == 1) ? 'mysales' : 'myassessment';
      if(this.selected_type == 1){
        this.salesRanking(year, month)
      }else{
        this.assessmentRanking(year, month)
      }
    }

    let _url;
    if (this.selected_type == 1) {
      // if(rolewise!='' && rolewise!='area'){
      _url = "leaderboard/" + t;
      // }else{
      // _url = "leaderboard/" + t ;
      // }
      // _url = "leaderboard/" + t + "/" + year + "/" + month;
    }
    else {
      // if(rolewise!=''){
      // _url = "leaderboard/" + t + "/"  + rolewise ;
      // }else{
      _url = "leaderboard/" + t;
      // }

    }
    console.log(this.loader)
    
  }
  salesTeamRanking(year, month){
    this.loader = true;
    this.server.post('leaderboard/myteamsales', { 
      month: month, 
      year: year, 
      location: 'P', 
      role: this.selectedRole ,
      zmemail: (this.zmEmail!=undefined || this.zmEmail!='')?this.zmEmail:'',
      rmemail: (this.rm_email!=undefined || this.rm_email!='')?this.rm_email:'',
      amemail: (this.am_email!=undefined || this.am_email!='')?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' && data.result.data != null) {
          this.user_data = data.result.user_data;
          this.leader_deatail = data.result.data;
          
          this.total_count = data.result.total_count;
          this.loader = false
          console.log(this.loader)
        }
        else if (data.result.status == 406) {
          this.loader = false
        }
        else if (data.result.status == 401 && data.result.response == 'failed') {
          this.router.navigateByUrl('');
        }
      });
  }
  assessmentTeamRanking(year, month){
    this.loader = true;
    this.server.post('leaderboard/myteamassessment', { 
      month: month, 
      year: year, 
      location: 'P', 
      role: this.selectedRole ,
      zmemail: (this.zmEmail!=undefined || this.zmEmail!='')?this.zmEmail:'',
      rmemail: (this.rm_email!=undefined || this.rm_email!='')?this.rm_email:'',
      amemail: (this.am_email!=undefined || this.am_email!='')?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' && data.result.data != null) {
          
          this.user_data_assessment = data.result.user_data;
          this.leader_assessment = data.result.data;

          this.total_count = data.result.total_count;
          this.loader = false
          console.log(this.loader)
        }
        else if (data.result.status == 406) {
          this.loader = false
        }
        else if (data.result.status == 401 && data.result.response == 'failed') {
          this.router.navigateByUrl('');
        }
      });
  }
  salesRanking(year, month){
    this.loader = true;
    this.server.post('leaderboard/mysales', { 
      month: month, 
      year: year, 
      location: 'P', 
      role: this.selectedRole ,
      zmemail: (this.zmEmail!=undefined || this.zmEmail!='')?this.zmEmail:'',
      rmemail: (this.rm_email!=undefined || this.rm_email!='')?this.rm_email:'',
      amemail: (this.am_email!=undefined || this.am_email!='')?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' && data.result.data != null) {
            this.user_data = data.result.user_data;
            this.leader_deatail = data.result.data;
          
          
          this.total_count = data.result.total_count;
          this.loader = false
          console.log(this.loader)
        }
        else if (data.result.status == 406) {
          this.loader = false
        }
        else if (data.result.status == 401 && data.result.response == 'failed') {
          this.router.navigateByUrl('');
        }
      });
  }
  assessmentRanking(year, month){
    this.server.post('leaderboard/myassessment', { 
      month: month, 
      year: year, 
      location: 'P', 
      role: this.selectedRole ,
      zmemail: (this.zmEmail!=undefined || this.zmEmail!='')?this.zmEmail:'',
      rmemail: (this.rm_email!=undefined || this.rm_email!='')?this.rm_email:'',
      amemail: (this.am_email!=undefined || this.am_email!='')?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' && data.result.data != null) {

          this.user_data_assessment = data.result.user_data;
          this.leader_assessment = data.result.data;
          
          this.total_count = data.result.total_count;
          this.loader = false
          console.log(this.loader)
        }
        else if (data.result.status == 406) {
          this.loader = false
        }
        else if (data.result.status == 401 && data.result.response == 'failed') {
          this.router.navigateByUrl('');
        }
      });
  }
  decreasFilter() {
    this.filter_date = moment(this.filter_date, "MMM YYYY").add(-1, 'months').format("MMM YYYY"); //- one month
    setTimeout(() => {
      this.year = moment(this.filter_date, "MMM YYYY").format("YYYY");
      this.month = moment(this.filter_date, "MMM YYYY").format("MM");
      this.getLeaderDetails(this.year, this.month)
    }, 1200);
  }

  increasFilter() {
    let now = moment(this.filter_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.filter_date = moment(this.filter_date, "MMM YYYY").add(1, 'months').format("MMM YYYY"); //+ one month
      this.year = moment(this.filter_date, "MMM YYYY").format("YYYY");
      this.month = moment(this.filter_date, "MMM YYYY").format("MM");
      this.getLeaderDetails(this.year, this.month)
    }
  }

  selectTopic(type) {
    this.filter_date = moment().format("MMM YYYY")//current month and year
    let mm = moment(this.filter_date, "MMM YYYY").format("MM");
    let yy = moment(this.filter_date, "MMM YYYY").format("YYYY");
    if (type == 0) {
      // this.getLeaderDetails(1, yy, mm, "");
      this.is_filter = true;
      this.rolewise = "area";
    }
    else if (type == 1) {
      this.rolewise = "area";
      // this.getLeaderDetails(2, yy, mm, "");
      this.is_filter = false;

    }

  }

  formatMin(seconds) {
    if (seconds == 0) {
      return 0;
    }
    else {
      let time_string: string = '';
      let plural: string = '';
      for (var key in this.times) {
        if (Math.floor(seconds / this.times[key]) > 0) {
          if (Math.floor(seconds / this.times[key]) > 1) {
            plural = 's';
          }
          else {
            plural = '';
          }

          time_string += Math.floor(seconds / this.times[key]).toString() + ' ' + key.toString() + plural + ' ';
          seconds = seconds - this.times[key] * Math.floor(seconds / this.times[key]);

        }
      }
      return time_string;
    }


  }
  changeRole(event) {
    console.log(this.selected_type, event)
    let role: string = '';
    this.selected_type = '2';
    role = (event == "area") ? "" : event;
    console.log(role, "role")
    this.filter_date = moment().format("MMM YYYY")//current month and year
    this.date_now = moment(this.filter_date, "MMM YYYY").format("MMM YYYY");
    let mm = moment(this.filter_date, "MMM YYYY").format("MM");
    let yy = moment(this.filter_date, "MMM YYYY").format("YYYY");
    // this.getLeaderDetails(this.selected_type, yy, mm, role);
  }
  changeRoleSales(event) {
    console.log(this.selected_type, event)
    let role: string = '';
    this.selected_type = '1';
    role = (event == "area") ? "" : event;
    console.log(role, "role")
    this.filter_date = moment().format("MMM YYYY")//current month and year
    this.date_now = moment(this.filter_date, "MMM YYYY").format("MMM YYYY");
    let mm = moment(this.filter_date, "MMM YYYY").format("MM");
    let yy = moment(this.filter_date, "MMM YYYY").format("YYYY");
    // this.getLeaderDetails(this.selected_type, yy, mm, role);
  }
}
