import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { ActivatedRoute ,Router} from '@angular/router';
import { CollectionprocessService } from '../collectionprocess/collectionprocess.service';
import { DxDataGridComponent } from 'devextreme-angular';
import { NgxSpinnerService } from 'ngx-spinner';	
@Component({
  selector: 'app-vendorallocation',
  templateUrl: './vendorallocation.component.html',
  styleUrls: ['./vendorallocation.component.css']
})
export class VendorAllocationComponent implements OnInit {
  frommyjob = false;
  completevalidate = false;
  stagename_alias: string;
  transactionid_pass: any;
  lotid_pass: any;
  projectdefinitionid_pass: any;
  userid_pass: any;
  jobid_pass: any;
  jobworkflowid_pass: any;
  wfid_pass: any;
  jobtitle: string;
  command = false;
  fromorder: number;
  toorder: number;
  stageorder_pass: any;
  userid: any;
  mode: number = 0; //1=FROM MY JOB //2 NEWLY CREATED LOT LOAD
  jobid: number;
  transactionid: number;
  jobworkflowid: string;
  lotid = 0;
  projectdefinitionid: any;
  _joblist: any = [];
 availablelotlist: any = [];
 assignedlotlist: any = [];
 userlist: any[];
 wfid:number=0;
 empmodel: number=0;
   // pagination variables
 p = 1;
   itemsPerPage = 10;
   _ddluserSettings: any;
   selectedusername:string='';
   selected_assginlot: any=[];
   transactionkey:string='';
  constructor( private toastr: ToastrService,
    private route: ActivatedRoute, 
    private collectionprocessservice: CollectionprocessService,
    private router: Router,  private SpinnerService: NgxSpinnerService,) {
       const navigation = this.router.getCurrentNavigation();
      const state = navigation.extras.state as {
        transactionkey: any;
        stagename_alias:any
      };
      if (state !== null && state !== undefined) {
        debugger;
        this.transactionkey = state.transactionkey;
        this.stagename_alias=state.stagename_alias;
      } }

  ngOnInit(): void {
    debugger;
    this.frommyjob = false;
    this._ddluserSettings = {
      singleSelection: true,
      idField: 'userid',
      textField: 'username',
      allowSearchFilter: true
    };
    this.userid = +localStorage.getItem("userid");
    this.transactionid_pass = +this.route.snapshot.queryParamMap.get("tranid");
    this.lotid_pass = +this.route.snapshot.queryParamMap.get("lotid");
    this.projectdefinitionid_pass =
      +this.route.snapshot.queryParamMap.get("pdid");
    this.userid_pass = +this.route.snapshot.queryParamMap.get("userid");
    this.jobid_pass = +this.route.snapshot.queryParamMap.get("jobid");
    this.jobworkflowid_pass = +this.route.snapshot.queryParamMap.get("jwfid");
    this.wfid_pass = +this.route.snapshot.queryParamMap.get("wfid");
    this.stageorder_pass = +this.route.snapshot.queryParamMap.get("stageorder");
    this.mode = +this.route.snapshot.queryParamMap.get("m");
    if (this.jobid_pass != 0 && this.jobid_pass != undefined) {
      this.frommyjob = true;
      this.jobid = this.jobid_pass;
      this.transactionid = this.transactionid_pass;
      this.jobworkflowid = this.jobworkflowid_pass;
      this.projectdefinitionid = this.projectdefinitionid_pass;
      this.lotid = this.lotid_pass;
      this.wfid=this.wfid_pass;
      this.fn_LoadJoblistDetails(this.projectdefinitionid_pass); //job title
      this.getlot();//lot data
      this.validatecomplete();
    }
  }
  fn_LoadJoblistDetails(projectdefinitionid) {
    this._joblist = [];
    const inputvalue = [];
    inputvalue.push({ projectdefinitionid: +projectdefinitionid });
    this.collectionprocessservice.getJobNo(inputvalue[0]).subscribe(
      (res) => {
        if (
          res !== undefined &&
          res !== null &&
          res.body[0] !== undefined &&
          res.body[0] !== null
        ) {
          if (JSON.parse(res.body[0]).length > 0) {
            this._joblist = JSON.parse(res.body[0]);
            if (this.jobid != 0 && this.jobid != undefined) {
              this.jobtitle = this._joblist.filter(
                (u) => u.jobid === this.jobid
              )[0].title;
            }
          }
        }
      },
      (error) => {
        this.toastr.error("Error while getting data");
      }
    );
  }
  exit() {
    this.router.navigate(["/dashboard"]);
  }
  getlot(){
    this.SpinnerService.show();
    this.collectionprocessservice.GetLotDeatils(this.projectdefinitionid_pass, this.wfid, this.jobid_pass, this.userid).subscribe(
      res => {
        this.SpinnerService.hide();
        this.availablelotlist=[];this.assignedlotlist =[]; this.userlist =[];
    //Availablelot
    if (res.lotlst[0] !== undefined && res.lotlst[0] !== null) {
      this.availablelotlist = JSON.parse(res.lotlst);
      console.log(JSON.stringify(this.availablelotlist));
      } 
      //assignedlot
      if (res.lotassignlst[0] !== undefined && res.lotassignlst[0] !== null) {
      this.assignedlotlist = JSON.parse(res.lotassignlst);
      console.log(JSON.stringify(this.assignedlotlist));
      }
      //user
      if (res.userlst[0] !== undefined && res.userlst[0] !== null) {
        this.userlist = JSON.parse(res.userlst);
        console.log(JSON.stringify(this.userlist));
        }
  },
  (err) => {
    this.SpinnerService.hide();
    this.toastr.error("Error in getting info");
  }
  );
  }
  onUserSelect(item: any) {
    this.empmodel = item.userid;
    this.selectedusername = item.username;

  }
  onUserDeSelect(item: any) {
    this.empmodel = 0;
    this.selectedusername = '';

  }
  selectionChangedHandler(){
    console.log('selected assigend lot',this.selected_assginlot);
  }

validatecomplete(){
debugger;
  this.collectionprocessservice.validatecompletebutton(this.jobid).subscribe(
    (res) => {
      debugger;
    if (res.body==false){

      this.completevalidate=false;
    }
     else {
      this.completevalidate=true;
     }
    },
    (err) => {
      this.SpinnerService.hide();
      this.toastr.error("Error in complete lot");
    });

}

  assign(){
    debugger;
    console.log( this.transactionkey )
    console.log( this.empmodel )
    if(this.empmodel==0){
      this.toastr.error("Select atleast one vendor to assign");
      return;
    }
    if(this.selected_assginlot.length==0){
      this.toastr.error("Select atleast one journal to assign");
      return;
    }
    this.SpinnerService.show();
   let fields = [];
   debugger;
      this.selected_assginlot.forEach((lot) => {
        fields.push({
          trankey: this.transactionkey,
          jobworkflowid: this.jobworkflowid,
          userid:this.empmodel,
          tranid:this.transactionid_pass,
          filename:lot.filename,
          lottitle:lot.title,
          lotid:lot.lotid,
          jobtitle:this.jobtitle,
        });
      });

    let fileData = new FormData();
    fileData.append("model", JSON.stringify(fields));
    this.collectionprocessservice.VendorAllocation(fileData).subscribe(
      (res) => {
        debugger;
        console.log(res)
        this.SpinnerService.hide();
        if (res.body !== undefined && res.body !== null) {
          this.toastr.success("Successfully assigned.");
          this.getlot();
          this.validatecomplete();

        }
      },
      (err) => {
        this.SpinnerService.hide();
        this.toastr.error("Error in assign vendor");
      });

  }
  retryVendor(ta: any) {
    console.log('Retrying for vendor:', ta);
    if(this.empmodel==0){
      this.toastr.error("Select atleast one vendor to assign");
      return;
    }
  

    let arr: any[] = [];

    let newDocument =ta;
    arr.push(newDocument);
    let fields = [];
    arr.forEach((lot) => {
         fields.push({
           trankey: this.transactionkey,
           jobworkflowid: this.jobworkflowid,
           userid:this.empmodel,
           tranid:this.transactionid_pass,
           filename:lot.filename,
           lottitle:lot.title,
           lotid:lot.lotid
         });
       });
       this.SpinnerService.show();
     let fileData = new FormData();
     fileData.append("model", JSON.stringify(fields));
     this.collectionprocessservice.VendorAllocation(fileData).subscribe(
       (res) => {
         console.log(res)
         this.SpinnerService.hide();
         if (res.body !== undefined && res.body !== null) {
           this.toastr.success("Successfully assigned.");
           this.getlot();
         }
       },
       (err) => {
         this.SpinnerService.hide();
         this.toastr.error("Error in assign vendor");
       });
  }
  completelot(){
   let assiglot= this.assignedlotlist.filter(
      (x) =>
        (x.withvendor == 0 || x.withvendor == '0' ));
    if(this.availablelotlist.length!=0 && assiglot.length!=0){
      this.toastr.error("Assign all available or failed lot and then click complete button");
      return;
    }
this.SpinnerService.show();
    this.collectionprocessservice.getcurstagecheckoutony(this.transactionid_pass,this.userid).subscribe(
      (res) => {
        debugger;
        this.SpinnerService.hide();
        if (res.length>0) {
          this.toastr.success("Successfully assigned.");
          this.router.navigate(["/dashboard"]);
        }

      },
      (err) => {
        this.SpinnerService.hide();
        this.toastr.error("Error in complete lot");
      });
  }
}
