import { Component, OnInit, Input, OnChanges, ViewChild } from '@angular/core';
import { DashboardService } from '../dashboard.service';
import { ToastrService } from 'ngx-toastr';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { environment } from '../../../environments/environment';
import { AuthService } from 'src/app/auth.service';
import { ActivatedRoute, Router , NavigationExtras} from '@angular/router';
import { CompletionPopupComponent } from '../completionPopup/completionPopup.component';
import {MatDialog, MatDialogConfig} from "@angular/material";
import { DialogService } from 'ng2-bootstrap-modal';
import { NgxSpinnerService } from 'ngx-spinner';									
import { Console } from 'console';
@Component({
  selector: 'app-myjobs',
  templateUrl: './myjobs.component.html',
  styleUrls: ['./myjobs.component.css']
})
export class MyjobsComponent implements OnInit, OnChanges, ViewChild {
  @Input() projectid: number;
  @Input() jobid: number;
  @Input() projectname: string;
  @Input() jobtitle: string;
  @Input() search: string;
  @Input() supplementlotids: any = [];
  tranid: number;
  projectjoblist: any;
  selectedproject = '';
  AssignedLotLoading_2 = false;
  prdef: number;
  isPushstage = false;
  userid: string = localStorage.getItem('userid');
  isViewQuery: boolean;
  selector: any;
  static: boolean;
  showpopup = false;
  descendants: boolean;
  first: boolean;
  read: any;
  url = environment.commontoolappUrl;
  urlSafe: SafeResourceUrl;
  show = false;
  spinner:boolean=true;
  lotstatus:string='';
  p = 1;
  itemsPerPage = 10;
  constructor(
    private dashboardservice: DashboardService,
    private toastr: ToastrService,
    public sanitizer: DomSanitizer,
    public auth: AuthService,
    private router: Router,
    private dialog: MatDialog,
    private SpinnerService: NgxSpinnerService
  ) { }

  ngOnChanges(changes: import('@angular/core').SimpleChanges): void {
  }

  ngOnInit(): void {
    this.spinner = true; 
    //console.log(this.search);
    this.search= localStorage.getItem("search");  
    this.fn_LoadProjectJobDetails(this.projectid, this.projectname,this.jobtitle,this.search);
  }

  fn_LoadProjectJobDetails(projectid,projectname,jobtitle,search) {
    debugger;
	  this.SpinnerService.show();						   
    this.prdef = projectid;
    const input = []; this.projectjoblist = [];
    input.push({ p_userid: +this.userid, p_projectdefinitionid: this.prdef});
    this.dashboardservice.getProjectJobDetails(input[0]).subscribe(res => {
      debugger;
      this.AssignedLotLoading_2 = true;
      if (res.body !== undefined && res.body !== null) {
       /*  if (res.body[0] !== undefined && res.body[0] !== null && JSON.parse(res.body[0][0]) !== null) {
          this.isPushstage = true;
        } else {
          this.isPushstage = false;
        } */
        if (res.body[1] !== undefined && res.body[1] !== null && JSON.parse(res.body[1][0]) !== null) {
		  this.SpinnerService.hide();
          this.projectjoblist = JSON.parse(res.body[1][0]);
         // console.log('myjobdata',JSON.stringify(this.projectjoblist))
        } else {
		    this.SpinnerService.hide();
          this.projectjoblist = [];
        }
      }
    }, err => {  this.SpinnerService.hide();
      });
  }
  WorkArea(userid, jtid, spath, projectid) {
    this.show = true;
    this.router.navigate(['/dashboard/workarea'], {
      queryParams:
        { jtid: jtid, projectid: projectid, spath: spath }
    });
  }
  openDialog(job) {
    console.log(job)
    this.spinner = false;
    if(job.lotstatus == 'R' ||  job.lotstatus =='YTS'){
      this.getcheckin(job);       
    }else{
     this.call_workarea(job);
    } 					  		 
}
call_workarea(job){

  if(job.stagename_alias=="Allocation"){
    this.call_vedor_Allocation_wa(job);
  }else{
  /*   if(job.stageorder == 1){
      this.call_first_wa(job);
      }else{
      this.call_popup_wa(job);
      } */
      this.WorkArea(this.userid,job.transactionid,job.weburl,job.projectdefinitionid);
  }
}
getcheckin(job){
  let fileData = new FormData();
  fileData.append('tranid',job.transactionid.toString());
  fileData.append('userid',this.userid.toString());
  fileData.append('lotstatus', 'P');
  fileData.append('p_option', 'checkin');
  fileData.append('jobworkflowid', job.jobworkflowid.toString());
  this.dashboardservice.getCheckincur(fileData).subscribe(res => {
    debugger;
    this.lotstatus=res.body[0].json_build_object.lotstatus;
    console.log(this.lotstatus);
  this.call_workarea(job);
  }, error => { this.toastr.error('Error in updating lot transaction'); });
}
call_first_wa(job){
  const queryParams = {tranid : job.transactionid, lotid :job.lotid, pdid:job.projectdefinitionid,userid:this.userid,jobid:job.jobid,jwfid:job.jobworkflowid,m:1};
  const navigationExtras: NavigationExtras = {
    queryParams,
    state: {
      id:job.uniquemailid,
      parentid:job.parentmailid,
      subject:job.subject,
      from:job.from_user,
      body:job.body,
      recdate:job.mailrecievedtime,
    },
  };
  this.router.navigate(
    ["/ccstageprocess/collectionprocess"],
    navigationExtras
  );
}
call_vedor_Allocation_wa(job){
  const queryParams = {tranid : job.transactionid, lotid :job.lotid, pdid:job.projectdefinitionid,userid:this.userid,jobid:job.jobid,jwfid:job.jobworkflowid,m:1,wfid:job.wfid};
  const navigationExtras: NavigationExtras = {
    queryParams,  state: {
      transactionkey:job.transactionkey,
      stagename_alias:job.stagename_alias,
      
    },

  };
  this.router.navigate(
    ["/ccstageprocess/vendorallocation"],
    navigationExtras
  );
}
call_popup_wa(job){
  debugger;
  const dialogConfig = new MatDialogConfig();
  dialogConfig.disableClose = true;
  dialogConfig.autoFocus = true;
  dialogConfig.data = {
    tranid: job.transactionid,
    title: 'Stage Completion',
    jobworkflowid:job.jobworkflowid,
    lotid:job.lotid,
    status:this.lotstatus==''?'P':this.lotstatus,
    projectcode:job.projectcode,
    projectname:job.projectname,	
    biddate:job.biddate,
    url:job.joburl,
    moveback:job.moveback,
    jobid:job.jobid,
    projetdefid:job.projectdefinitionid,       
    stageorder:job.stageorder,
    stagename:job.stagename_alias,
    id:job.uniquemailid,
    parentid:job.parentmailid,
    lotmaster_status:job.lotmaster_status,
    subject:job.subject,
    from:job.from_user,
    body:job.body,
    recdate:job.mailrecievedtime,
    wfid:job.wfid,
    
};
  const dialogRef = this.dialog.open(CompletionPopupComponent, dialogConfig);
  dialogRef.afterClosed().subscribe(
    data => this.fn_LoadProjectJobDetails(this.projectid, this.projectname,this.jobtitle,this.search)); 
}
}
