import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { HyperService } from '../../core/services/http.service';
import { Router,NavigationEnd, RoutesRecognized } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { LocalStorage } from '../../core/services/local_storage.service';
import * as moment from 'moment';
import { DatepickerOptions } from 'ng2-datepicker';
import { AmazingTimePickerService } from 'amazing-time-picker';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import {  View, EventSettingsModel, DayService, WeekService, WorkWeekService, MonthService, ResizeService, DragAndDropService, PopupOpenEventArgs, DragEventArgs, ResizeEventArgs, ActionEventArgs, EventRenderedArgs, ScheduleComponent} from '@syncfusion/ej2-angular-schedule';
import { ChangeArgs } from '@syncfusion/ej2-buttons';
import { ToasterService } from '@service/toaster.service';
import { enableRipple } from '@syncfusion/ej2-base';
import { TaskstatusDealerComponent } from "../taskstatus-dealer/taskstatus-dealer.component";
import { ConfirmPopupComponent } from '../../sales_executive/confirm-popup/confirm-popup.component';
import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';
import { send } from 'q';
import { CONFIG } from '../../config';
import { filter, pairwise } from 'rxjs/operators';



enableRipple(true);
declare var $: any;

@Component({
  selector: 'app-activity-planner-dealer',
  templateUrl: './activity-planner-dealer.component.html',
  styleUrls: ['./activity-planner-dealer.component.scss']
})
export class ActivityPlannerDealerComponent implements OnInit {
  // @ViewChild(TaskstatusDealerComponent) taskmodal: TaskstatusDealerComponent;
  @ViewChild(ConfirmPopupComponent) confirm_modal: ConfirmPopupComponent;
  sales_date: any;
  date_now: any;
  yearpresent:any;
  monthpresent:any;
  idvalue:any='';
  setsmpin: any='';
  loader: boolean;
  trainer_welcomenote = '';
  trainer_error: string = '';
  itemdetail = [];
  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
  }
  sub: any;
  type: any;
  user_id: any;
  userData: any = {};
  setMenuId:string;
  videoitemdetail: any;
  batchitemdetail: any;
  registerForm: FormGroup;
  // calendarOptions: CalendarOptions = {
  //   initialView: 'dayGridMonth'
  // };
  options: DatepickerOptions = {
    minDate: new Date(Date.now()), 
    maxDate: new Date(Date.now()), 
  };
  rm_list: any = [];
  showdse: boolean;
  typermdata: any=[];
  typeamdata: any=[];
  typedealerdata: any=[];
  typedsedata: any=[];
  typezmuserdata: any=[];
  typermuserdata: any=[];
  typeamuserdata: any=[];
  totalparticipant_list: any[];
  showdealer: boolean;
  showam: boolean;
  am_list: any=[];
  dealer_list: any=[];
  dse_list: any[];
  @ViewChild('scheduleObj')
  public scheduleObj: ScheduleComponent;
  public readonly: boolean = true;
  today = new Date();
  eventData: EventSettingsModel={};
  currentmonth;
  dataSource = [];
  calender_list: any;
  totalcalenderlist: any = [];
  schdule_id: any;
  rolename: any;
  showmodify: boolean;
  feedback_list: any=[];
  dsescorelist: any = [];
  todaylist: any = [];
  monthlist: any = [];
  monthlistvalue:any=[];
  templateobj:any='';
  smpinselected:any=[];
  selecteddse:any='';
  smpinselectedname:any='';
  
  constructor(private route: ActivatedRoute,public toaster : ToasterService,private formBuilder : FormBuilder ,private server: HyperService, private router: Router,private atp: AmazingTimePickerService,public elm : ElementRef) { 
  }


  ngOnInit() {

    let smpinvalue=LocalStorage.getValue('setdseselected')
    this.smpinselectedname=LocalStorage.getValue('setdseselectedname');
    this.smpinselected = smpinvalue
  //  alert("this.smpinselected---->"+this.smpinselected)

  LocalStorage.setValue("activity_check",'activity_check');
    let spin='';
    this.server.get("dealer/userlist")
    .then((data) => {
      if (data.status == 200 && data.result.response != 'failed') {
        this.setsmpin = data.result.data;
        spin = data.result.data[0].smpin;
        // spin.push({smpin:'select',fname:'Select',lname:''})
        this.setsmpin.unshift({smpin:'',fname:'Select',lname:''})
        this.loader = false;
      } else if (data.result.status == 406) {
        //alert(data.result.message)
      }
      else if (data.result.status == 401 && data.result.response == 'failed') {

      }
    });

    if((this.smpinselected =='')||(this.smpinselected ==undefined)){
      this.selecteddse ='';
    }else{
      this.selecteddse =this.smpinselected;
    }
  //  alert("this.selecteddse---->"+this.selecteddse)
    
    this.idvalue='';
    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.yearpresent=y;
    this.monthpresent=m;

    var urlvalue='nonmyenquiries';
    // this.taskmodal.getmonthbaseddetails(this.yearpresent,this.monthpresent,urlvalue);
   // this.addplan();
    this.getmonthlist();

    this.setMenuId = '1';
    // this.initFilter();
    LocalStorage.setValue('is_firsttime', false);
    let month = this.today.getMonth()+Number(1);
    this.currentmonth = this.today.getFullYear()+'-'+month;
   // this.gettraininglist(this.currentmonth);
    this.rolename = LocalStorage.getValue('user_data').role;    
    //this.getdsefeedback();
    //this.getdsescore();
  }

  public onPopupOpen(args: PopupOpenEventArgs): void {
    if(args.type == "QuickInfo"){
      // args.cancel = true;
      args.cancel = this.onEventCheck(args);
    }
  }
  public onEventRendered(args: EventRenderedArgs): void {
    var back_color:any = args.data.color;
    args.element.style.backgroundColor = back_color;
  }

  onActionComplete(args): void {
    if ( args.requestType === "dateNavigate") {
      let currentViewDates: Date[] = this.scheduleObj.getCurrentViewDates() as Date[];
      for (let i = 0; i < currentViewDates.length; i++) {
          var d1 = currentViewDates[i];
        if (d1.getDate() == 1){
          let month = d1.getMonth() + 1;
          let year = d1.getFullYear();
        //  let dateval=d1.getDate();
         // console.log("dateval--->",dateval)
          this.yearpresent=year;
         /// alert("month-->"+month);
          this.monthpresent=month;
          this.getmonthlist();
         // this.gettraininglist(year+'-'+month);
            break;
        }
      }
    }
  }

  public onActionBegin(args){
    
  }
  
  public onEventCheck(args: any) {
    LocalStorage.setValue("activity_day_list",'');
      let eventObj: any = args.data instanceof Array ? args.data[0] : args.data;
      console.log("this.rolename-->",eventObj)
      this.schdule_id = eventObj.Id;
      LocalStorage.setValue("activity_day_list",eventObj);
      LocalStorage.setValue("activity_check",'activity_check');
      

      // let given_date = new Date(new Date(eventObj.StartTime).getTime() - 3 * 24 * 60 * 60 * 1000);
      // let today = new Date();
      // let given_date = new Date(eventObj.StartTime);
      // this.showmodify = given_date >= today ?true : false;
      this.showmodify = eventObj.trainingupdate_status;


      this.router.navigateByUrl('dealer-activityday-link/'+this.schdule_id);
      
      
      return true;
  }

  // getdsefeedback(){
  //   if(this.rolename == 10){
  //     this.server.get("crtraining/dsefeedbacklist").then((data) => {
  //       if (data.status == 200 && data.result.response == "success") {
  //         this.feedback_list= data.result.data;
  //         LocalStorage.setValue('DSEFeedbackdata',JSON.stringify(this.feedback_list))
  //       }else if (data.result.response == "failed" && data.status == 401) {
  //         this.router.navigateByUrl('');
  //       }
  //     })
  //   }else{
  //     this.server.get("crtraining/trainingsfeedbacklist").then((data) => {
  //       if (data.status == 200 && data.result.response == "success") {
  //         this.feedback_list= data.result.data;
  //         LocalStorage.setValue('training_Feedbackdata',JSON.stringify(this.feedback_list))
  //       }else if (data.result.response == "failed" && data.status == 401) {
  //         this.router.navigateByUrl('');
  //       }
  //     })
  //   }
  // }

  // getdsescore(){
  //   if(this.rolename == 10){
  //     this.server.get("crtraining/dsescoreresultlist").then((data) => {
  //       if (data.status == 200 && data.result.response == "success") {
  //         this.dsescorelist= data.result.data;
  //       }else if (data.result.response == "failed" && data.status == 401) {
  //         this.router.navigateByUrl('');
  //       }
  //     })
  //   }
  // }

  // viewfeedback(data){
  //   this.router.navigateByUrl('allfeedback/'+data.assessmentid)
  // }

  setTab(id){
    this.setMenuId = id;
    if(id=='1'){
      // this.getvideotraininglist();
    }else if (id =='2'){
      this.getbatchlist();
    }
  }

  // addtraining(){
  //   this.router.navigateByUrl('newcreationtraining');
  // }

  // addbatch(){
  //  this.router.navigateByUrl('addbatch');
  // }

  // gettraininglist(current_month){
  //   this.totalcalenderlist = [];
  //   this.dataSource = [];
  //   this.loader = true;
  //   this.server.post("crtraining/trainingcalenderlist",{ month: current_month }).then((data) => {
  //     this.loader = false;
  //     if (data.status == 200 && data.result.response == "success") {
  //       this.calender_list = data.result.data;
  //       if(this.calender_list !=null && this.calender_list!= undefined){
  //         for (let key in this.calender_list) {
  //           for(let j in this.calender_list[key])
  //             this.totalcalenderlist.push(this.calender_list[key][j]);
  //         }
  //         this.setvaluecal(this.totalcalenderlist)
  //       }
  //     } else if (data.result.response == "failed" && data.status == 401) {
  //       this.router.navigateByUrl('');
  //     }
  //   })
  // }

  setvaluecal(value){
    // let template: string = '<div class="tooltip-wrap">' +
    // '<div class="image ${EventType}"></div>' +
    // '<div class="content-area"><div class="name">${Subject}</></div>' +
    // '${if(City !== null && City !== undefined)}<div class="city">${City}</div>${/if}' +
    // '<div class="time">Start&nbsp;:&nbsp;${localstartdate} , ${localstarttime} </div>' +
    // '<div class="time">End&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;${localenddate}, ${localendtime} </div></div></div>';

    let template: string = '<div class="tooltip-wrap">' +
    '${if(color !== null && color !== undefined)}<div class="city">${Subject}</div>${/if}'
    '${if(color === null && color === undefined)}<div class="city">No schedules are present</div>${/if}'
    '</div>';
    // '<div class="image ${EventType}"></div>' +
    // '<div class="content-area"><div class="name">${Subject}</></div>' +
    // '${if(City !== null && City !== undefined)}<div class="city">${City}</div>${/if}' +
    // '<div class="time">Start&nbsp;:&nbsp;${localstartdate} , ${localstarttime} </div>' +
    // '<div class="time">End&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:&nbsp;${localenddate}, ${localendtime} </div></div></div>';







    function removeDuplicates(originalArray, prop) {
      var newArray = [];
      var lookupObject  = {};

      for(var i in originalArray) {
        lookupObject[originalArray[i][prop]] = originalArray[i];
      }

      for(i in lookupObject) {
          newArray.push(lookupObject[i]);
      }
      return newArray;
    }
    var uniqueArray = [];
    uniqueArray = removeDuplicates(value, "schedule_id");
    for(let i=0;i<uniqueArray.length;i++){
      let time1 = uniqueArray[i].starttime;
      let time2 = uniqueArray[i].endtime;
      let start = JSON.parse(time1);
      let end = JSON.parse(time2);

      this.dataSource.push({
        Id: uniqueArray[i].schedule_id,
        Subject: uniqueArray[i].title,
        StartTime: new Date(uniqueArray[i].startdate),
        EndTime: new Date(uniqueArray[i].enddate),
        color : uniqueArray[i].training_status,
        is_deleted : uniqueArray[i].is_deleted,
        localstartdate : moment(uniqueArray[i].startdate).format('DD/MM/YYYY'),
        localenddate : moment(uniqueArray[i].enddate).format('DD/MM/YYYY'),
        trainingupdate_status : uniqueArray[i].training_update_status,
        localstarttime : start[start.length - 1],
        localendtime : end[end.length - 1]
    });
    }
    this.eventData={
      dataSource :this.monthlist,
      enableTooltip: true,
      tooltipTemplate: ''
    }
  //  console.log(this.dataSource)
  }
  

  getbatchlist(){
 
  }

  getmonthlist(){
    let smpinvalue=LocalStorage.getValue('setdseselected')
    this.smpinselected = smpinvalue;
    var urlvalue='nonmyenquiries';
    // this.taskmodal.getmonthbaseddetails(this.yearpresent,this.monthpresent,urlvalue);
    //alert("333--->"+this.smpinselected);
    let monthstr=this.monthpresent.length;
    if(monthstr =='2'){
      //this.monthpresent=monthstr;
    }else{
      this.monthpresent='0'+this.monthpresent;
    }
    this.monthlist=[];
    let req={
      type:'month',
      month:this.monthpresent,
      year:this.yearpresent
    }
    this.server.post("dealerenquiry/plannerlist/"+this.smpinselected,req).then((data) => {
      if (data.status == 200 && data.result.response == "success") {
        let datavalue=data.result.data.month;
     //   console.log("datavalue->",datavalue);
       
        let datevalue1= Object.entries(datavalue);
     //   console.log("this.monthlist->",datevalue1);
        let new_array=[];

        datevalue1.forEach((element,index) => {
          this.templateobj='';
      //    console.log("element[1]--->",element[1]['date']);
            
          let tempvar1=element[1]['data'];
          let colorval='';
          let dat_val='';
          if(tempvar1.length==0){
            colorval=''
            dat_val='0';

          }else{
            colorval='#003d58';
            let a=tempvar1.length;
            dat_val=a;
          }
          new_array.push(element[1]['date'])
          new_array.push({date:element[1]['date']},{data:'0'})

        //  console.log("datevalue1-->",new_array);
         // return false;
          this.templateobj = '<div class="tooltip-wrap">' +
         '<div class="city">${Subject}</div>'
        //  '${if(color === null && color === undefined && color === "")}<div class="city">No schedules are present</div>${/if}'
         '</div>';



           this.monthlist.push({
              Subject: dat_val,
              StartTime: new Date(element[1]['date']),
              EndTime: new Date(element[1]['date']),
              color : colorval
           });
        });

        // this.monthlist=data.result.data.month;

        this.eventData={
          dataSource :this.monthlist,
          enableTooltip: true,
          tooltipTemplate: this.templateobj
        }


      //   console.log("data-getmonthlist->",this.monthlist);
      }else if (data.result.response == "failed" && data.status == 401) {
        
      }
    })
  }

  todayclick(){


    var date12 = new Date()
    // Add  day
    var date29 =  date12.setDate(date12.getDate())
    var date30 =  new Date(date29);
    let dateinsertion = moment(date30).format("YYYY-MM-DD");


    this.todaylist='';
    let req={
      //month,today
      type:'date',
      month:'',
      year:'',
      date:dateinsertion
    }
    this.server.post("enquiry/plannerlist",req).then((data) => {
      if (data.status == 200 && data.result.response == "success") {
      //  console.log("data-getmonthlist->",data.result.data.date);
        this.todaylist=data.result.data.date;
        
        // this.setvaluecal(this.totalcalenderlist)
      }else if (data.result.response == "failed" && data.status == 401) {
        
      }
    })
  }
  edittoday(item){

  }
  deletetoday(tempval){
  //  console.log("tempval-->",tempval.id);
    this.confirm_modal.deleterowmodal(tempval.id);
  }
  sendtolist(tempvar){
  //  console.log("tempvar----->",tempvar); 
     if(tempvar == 'list'){
       this.router.navigateByUrl('activityplanner');
     }else{
       //this.router.navigateByUrl('');
     }
   }


   selectdse(){
    LocalStorage.setValue("setdseselected",this.selecteddse);
    this.smpinselected = this.selecteddse;
    this.getmonthlist();
  }


  // addplan(){
  //   let req={
  //     title:'call client',
  //     plandate:'27-09-2020',
  //     fromtime:'11:00',
  //     totime:'11:30'
  //   }
  //   this.server.post("enquiry/plannersave",req).then((data) => {
  //     if (data.status == 200 && data.result.response == "success") {
  //       console.log("data-addplan->",data);
        
  //     }else if (data.result.response == "failed" && data.status == 401) {
        
  //     }
  //   })
  // }


  // setTab(id){
  //   this.setMenuId = id;
  //   if(id=='2'){
  //     // this.getvideotraininglist();
  //   }else if (id =='3'){
  //     this.getbatchlist();
  //   }else{
  //     let y = moment(this.filter_date, "MMM YYYY").format("YYYY");
  //     let m = moment(this.filter_date, "MMM YYYY").format("MM");
  //     this.getTrainingSchedule(y,m)
  //   }
  // }

  // getvideotraininglist(){
  //   this.server.get("videotraining?page=0&limit=10").then((data) => {
  //     this.loader = false;
  //     if (data.status == 200 && data.result.response == "success") {
  //       this.trainer_welcomenote = '';
  //       if (data.result.data.length > 0) {
  //         this.videoitemdetail = data.result.data;
  //       } else {
  //         this.trainer_welcomenote = 'Video Training is not available';
  //       }
  //     } else if (data.result.response == "failed") {
  //       this.trainer_error = data.result.message;
  //     }
  //   })
  // }
  
  // getbatchlist(){
  //   this.server.get("trainer/batch?page=0&limit=10").then((data) => {
  //     this.loader = false;
  //     if (data.status == 200 && data.result.response == "success") {
  //       this.trainer_welcomenote = '';
  //       if (data.result.data.length > 0) {
  //         this.batchitemdetail = data.result.data;
  //       } else {
  //         this.trainer_welcomenote = 'Batch is not available';
  //       }
  //     } else if (data.result.response == "failed") {
  //       this.trainer_error = data.result.message;
  //     }
  //   })
  // }

  // deleteRow(id){
  //   this.loader = true;
  //   this.server.delete("videotraining/" + id).then((data) => {
  //     this.loader = false;
  //     if (data.status == 200 && data.result.response == "success") {
  //       this.getvideotraininglist();
  //     } else if (data.result.response == "failed") {
       
  //     }
  //   })
  // }

  //   initFilter() {
//     this.sub = this.route.params.subscribe(params => {
//       this.type = params['type'];
//       this.user_id = params['id'];
//       this.userData.emailid = params['email'];
//     });
//     this.date_now = moment().format("MMM YYYY");
//     if (this.type == 'mobile') {
//       LocalStorage.setValue('token', this.user_id)
//       this.getuserdetails() //Get Authentication token 

//     } else {
//       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");
//       this.getTrainingSchedule(yy, mm); // Get the Training Details
//     }

//   }

//   getuserdetails() {
//     this.loader = true;
//     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");
//     this.getTrainingSchedule(yy, mm); // Get the Training Details
// }

//   decreasFilter() {
//     this.loader = true;
//     this.filter_date = moment(this.filter_date, "MMM YYYY").add(-1, 'months').format("MMM YYYY"); //- one month
//     setTimeout(() => {
//       let y = moment(this.filter_date, "MMM YYYY").format("YYYY");
//       let m = moment(this.filter_date, "MMM YYYY").format("MM");
//       this.getTrainingSchedule(y, m); // Get the Training Details
//     }, 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.loader = true;
//       this.filter_date = moment(this.filter_date, "MMM YYYY").add(1, 'months').format("MMM YYYY"); //+ one month
//       let y = moment(this.filter_date, "MMM YYYY").format("YYYY");
//       let m = moment(this.filter_date, "MMM YYYY").format("MM");
//       this.getTrainingSchedule(y, m); // Get the Training Details
//     }
//   }
//   getTrainingSchedule(year, month) {
//     this.server.post("trainer/monthdata/" + year + "/" + month + "?page=0&limit=10", {}).then((data) => {
//       this.loader = false;
//       if (data.status == 200 && data.result.response == "success") {
//         this.trainer_welcomenote = '';
//         if (data.result.data.length > 0) {
//           this.itemdetail = data.result.data;
//         } else {
//           this.trainer_welcomenote = 'Classroom Training is not available';
//         }
//       } else if (data.result.response == "failed") {
//         this.trainer_error = data.result.message;
//       }
//     })
//   }
//   takeTraining(sid) {
//     if(this.type=="mobile"){
//       this.router.navigateByUrl('trainingcourse/' + sid+'/'+this.type+'/'+this.userData.emailid+'/'+this.user_id);
//     }else{
//       this.router.navigateByUrl('trainingcourse/' + sid);
//     }   
//   }
 
//   deletetraining(id){
//   }

}

