import { Component, OnInit, Input } from '@angular/core';
import { LotMaster, Jobmaster } from '../jobmaster';
import { ToastrService } from 'ngx-toastr';
import { JobdefinitionService } from '../../jobdefinition/jobdefinition.service';
import { NgxSpinnerService } from 'ngx-spinner';
import { JobmasterService } from '../jobmaster.service';

@Component({
  selector: 'app-addlotwithexcel',
  templateUrl: './addlotwithexcel.component.html',
  styleUrls: ['./addlotwithexcel.component.css']
})
export class AddlotwithexcelComponent implements OnInit {
  @Input() job = {} as Jobmaster;
  @Input() lotModalRef;
  selectedjobitem = {} as LotMaster;
  mappedchapter = [];
  lotlist = [];
  statelist = [];
  frequencetypelist = [];
  statecode: any;
  frequencetype: any;
  ButtonType = '';
  Batchuploadlist = [];
  uploadlist: any = [];
  userid: any;
  constructor(
    private toastr: ToastrService,
    private jobdefinitionservice: JobdefinitionService,
    private jobmasterservice: JobmasterService,
    private SpinnerService: NgxSpinnerService) { 
  }

  ngOnInit(): void {
    this.userid = +localStorage.getItem('userid');
    this.loadDetails();
    this.getstatefrequencylist();
  }

  loadDetails() {
    debugger;
    console.log(this.job);
    const jobObject = new Object({
      jobid: this.job.jobid
    });
    this.SpinnerService.show();
    this.jobdefinitionservice.GetJobWorkFlowDefCount(jobObject).subscribe(res => {
      if (res.body.length > 0) {
        this.ButtonType = 'Add Lot';
        this.selectedjobitem.jobno = this.job.jobno;
        this.selectedjobitem.jobid = this.job.jobid;
        const job = new Object({
          jobid: this.job.jobid
        });
        this.jobmasterservice.getLotByJobId(job).subscribe(lotres => {
          this.SpinnerService.hide();
          this.mappedchapter = [];
          if (lotres.body[0] != null) {
            const lotress = JSON.parse(lotres.body[0]);
            lotress.forEach(val => {
              const ind = this.mappedchapter.findIndex((x) => {
                return x.chaptertypeid === val.chaptertypeid;
              });
              if (ind >= 0) {
                this.mappedchapter[ind].chapters.push(val);
              } else {
                this.mappedchapter.push({ chaptertype: val.chaptertype, chaptertypeid: val.chaptertypeid, chapters: [] });
                const ind1 = this.mappedchapter.findIndex((x) => {
                  return x.chaptertypeid === val.chaptertypeid;
                });
                this.mappedchapter[ind1].chapters.push(val);
              }
            });
            console.log('this.mappedchapter=', this.mappedchapter);
            this.lotlist = JSON.parse(lotres.body[0]);
            const result = JSON.parse(lotres.body[0]);
          } else {
            this.lotlist = [];
            const result = [];
          }
          /* if (lotres.body[0] != null) {
            // this.joblotForm.value.autoinc = this.lotlist.length + 1;
            this.joblotForm.controls['autoinc'].setValue(this.lotlist.length + 1);
          } else {
            // this.joblotForm.value.autoinc = 1;
            this.joblotForm.controls['autoinc'].setValue(1);
          } */
        }, error => {
          this.toastr.error('Error in getting Chapter Master Records');
        });
      } else {
        this.toastr.error('Please complete job configuration, then proceed.');
      }
    }, error => {
       this.toastr.error('Error while adding lot.');
    });
  }

  fileuploadchange(ix, fileInput: any) {
      for (let i = 0; i < fileInput.target.files.length; i++) {
        const v = fileInput.target.files[i];
        this.uploadlist[i]=fileInput.target.files[i];
      }
  }

  Savelot() {
    debugger;
    const formData = new FormData();
     /* if (this.uploadlist !='') {
      for (let i = 0; i < this.uploadlist.length; i++) {
        const val = this.uploadlist[i];
        if (val !== undefined) {
          formData.append('file', val,
            val.name + '~' + this.job.title + '~' + this.selectedjobitem.jobid + '~' + this.selectedjobitem.jobno + '~' + this.userid + '~' + this.statecode + '~' + this.frequencetype);
        }
      }   */

           formData.append('title', this.job.title);
           formData.append('jobid', this.selectedjobitem.jobid.toString());
           formData.append('projectdefinitionid', this.job.projectdefinitionid.toString());
           formData.append('userid', this.userid);
           formData.append('statecode', this.statecode);
           formData.append('frequencetype', this.frequencetype);
           
      this.jobmasterservice.UploadLotInfoExcelFile(formData).subscribe(d => {
        debugger;
        console.log(d);
        this.toastr.success(d.body.length+ ' Lot(s) Added Successfully.');
        this.clearForm();
        this.SpinnerService.hide();
      }, error => {
        this.toastr.error('Error in Adding Chapter Records');
  
      });
    //}
  }

  getstatefrequencylist() {
    debugger;
    this.statelist = [];
    this.frequencetypelist=[];
    var abbreviationlist=(this.job.jobno).split("-");
    console.log(abbreviationlist[0]);
    var ftype=(this.job.jobno).substring(5,1);
    this.jobmasterservice.GetActiveState().subscribe(res => {
      debugger;
        if (res != null && res !== undefined) {
            this.statelist = JSON.parse(res);
            for (let i = 0; i < this.statelist.length; i++) {
              if(this.statelist[i].stateabbreviation==abbreviationlist[0].toString()){
                this.statecode=this.statelist[i].statename;
              }
            }
        }
    }, error => { this.toastr.error('Error while getting data'); });

    this.jobmasterservice.GetActiveFrequency().subscribe(ress => {
      debugger;
        if (ress != null && ress !== undefined) {
            this.frequencetypelist = JSON.parse(ress);
            for (let i = 0; i < this.frequencetypelist.length; i++) {
              if(this.frequencetypelist[i].frequencyabbreviation==abbreviationlist[1].toString()){
                this.frequencetype=this.frequencetypelist[i].frequencytype;
              }
            }
        }
    }, error => { this.toastr.error('Error while getting data'); });
}

  clearForm() {
    this.lotModalRef.hide();
  }
  moveUpChoice(pindex, index) {
    if (index > 0) {
      this.mappedchapter[pindex].chapters.splice(index - 1, 0, this.mappedchapter[pindex].chapters.splice(index, 1)[0]);
    }
  }

  moveDownChoice(pindex, index) {
    const newPosition = index + 1;
    if (index < this.mappedchapter[pindex].chapters.length) {
      this.mappedchapter[pindex].chapters.splice(newPosition, 0, this.mappedchapter[pindex].chapters.splice(index, 1)[0]);
    }
  }

  removeMapped(pindex, index) {
    /* if (this.g.isbatch.value === false) {
      this.uploadlist.push(this.mappedchapter[pindex].chapters[index]);
      this.mappedchapter[pindex].chapters.splice(index, 1);
    } else { */
      this.Batchuploadlist.push(this.mappedchapter[pindex].chapters[index]);
      this.mappedchapter[pindex].chapters.splice(index, 1);
    // }
  }

}
