import { Component, OnInit, Input } from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { JobdefinitionService } from '../../jobdefinition/jobdefinition.service';
import { LotMaster, Jobmaster } from '../jobmaster';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
import { Options } from 'ng5-slider';
import * as $ from 'jquery';
import { JobmasterService } from '../jobmaster.service';
import { NgxSpinnerService } from 'ngx-spinner';
@Component({
  selector: 'app-addlot',
  templateUrl: './addlot.component.html',
  styleUrls: ['./addlot.component.css']
})
export class AddlotComponent implements OnInit {
  @Input() job = {} as Jobmaster;
  @Input() lotModalRef;
  selectedjobitem = {} as LotMaster;
  joblotForm: FormGroup;
  value = 1;
  options: Options = {
    floor: 1,
    ceil: 10
  };
  submitted = false;
  Batchuploadlist = [];
  uploadlist: any = [];
  Imagecollection = [];
  chaptertypelist = [];
  mappedchapter = [];
  xmlvalidate = false;
  Selectedchaptertype: any;
  ButtonType = '';
  selcahp = [];
  lotlist = [];
  isuplaod = false;
  result = false;
  constructor(
    private formBuilder: FormBuilder,
    private toastr: ToastrService,
    private jobdefinitionservice: JobdefinitionService,
    private jobmasterservice: JobmasterService,
    private SpinnerService: NgxSpinnerService,
  ) { }

  ngOnInit(): void {
    this.joblotForm = this.formBuilder.group({
      lotid: [],
      jobid: [],
      title: [],
      sequence: [],
      instructions: [],
      isbatch: [false],
      basedonfile: [false],
      autoinc: [1],
      chapterCount: [1],
      filedetails: [],
      chaptype: [1],
      fileList: this.formBuilder.array([]),
    });
    this.loadDetails();
    this.LoadChaptertypes();
    this.AdduploadfileInitial(this.joblotForm.value);
  }

  initCaseRows() {
    return this.formBuilder.group({
      instruction: [''],
      log: [[]],
      title: [''],
      Fileslist: [],
      chaptype: [],
      filedetails: [],
    });
  }

  get g() { return this.joblotForm.controls; }

  loadDetails() {
    // this.xmlvalidate = true;
    const jobObject = new Object({
      jobid: this.job.jobid
    });
    this.SpinnerService.show();
    // code to get jobworkflow by jobid
    this.jobdefinitionservice.GetJobWorkFlowDefCount(jobObject).subscribe(res => {

      if (res.body.length > 0) {
        this.ButtonType = 'Add Chapter';
        // this.callType.stype = 'Add Chapter';
        this.selectedjobitem.jobno = this.job.jobno;
        this.selectedjobitem.jobid = this.job.jobid;
        // $rootScope.projecdefid = this.job.projectdefinitionid;
        // $rootScope.job = this.job.jobid;
        // Code to get lot details by job id
        const job = new Object({
          jobid: this.job.jobid
        });

        this.jobmasterservice.getLotByJobId(job).subscribe(lotres => {
          // const   getlot = jobmasterservice.getlotdetailsbyid(item.jobid);
          // getlot.then(function (d) {
          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 => x.chaptertypeid === val.chaptertypeid);
              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 => x.chaptertypeid === val.chaptertypeid);
                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 = [];
          }
          // this.callType.lotitem = result;
          // this.lotcreated = false;


          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.');
        // this.complete();
      }

    }, error => {
      this.toastr.error('Error while adding lot.');
    });
  }

  get fileList(): FormArray {
    return this.joblotForm.get('fileList') as FormArray;
  }

  AdduploadfileInitial(joblotForm: LotMaster) {
    const newitem = { id: 1, filedet: undefined, instructions: '' };
    const count1 = joblotForm.chapterCount - this.uploadlist.length;
    for (let ii = 0; ii < count1; ii++) {
      this.uploadlist.push(newitem);
    }
  }

  Adduploadfile(joblotForm: LotMaster) {

    let newitem = { id: 0, filedet: undefined, instructions: '' };
    if (this.joblotForm.value.isbatch === false) {
      this.joblotForm.value.basedonfile = false;
      if (joblotForm.chapterCount === 1) {
        const count = this.uploadlist.length - joblotForm.chapterCount;
        for (let i = 0; i < count; i++) {
          this.uploadlist.splice(this.uploadlist.length - 1, 1);
        }
        return;
      }
      if (this.uploadlist.length < joblotForm.chapterCount) {
        const count1 = joblotForm.chapterCount - this.uploadlist.length;
        for (let ii = 0; ii < count1; ii++) {
          newitem = { id: ii + 1, filedet: undefined, instructions: '' };
          this.uploadlist.push(newitem);
        }
      } else {
        const count2 = this.uploadlist.length - joblotForm.chapterCount;
        for (let iii = 0; iii < count2; iii++) {
          this.uploadlist.splice(this.uploadlist.length - 1, 1);
        }
      }
    } else {
      this.joblotForm.value.basedonfile = true;
      // if (this.Batchuploadlist.length > 0 &&
      // (this.Batchuploadlist.length > this.slider.value || this.Batchuploadlist.length < this.slider.value)) {
      //    exDialog.openMessage(this, "File upload count should be equal to lot count.", "Add Lot", "warning");
      //    $('#batchfile').val('');
      //    this.Batchuploadlist = [];
      // }
    }
  }

  clearForm() {
    this.lotModalRef.hide();
  }

  readFileContent(file, key) {
    // let r = new FileReader();
    // r.onload =  (e) => {
    //     let content =  r.target.result;
    //     const regex2 = RegExp('<blob(?: [^><]+)? (?:src|blob-ref-id)="([^"]*)"(?: [^><]+)(?:src|blob-ref-id)="([^"]*)', 'gi');
    //   //  const match = regex2.exec(content)
    //   //   while (match) {
    //   //       const    id = this.Imagecollection.findIndex  (x => x.name === match[1] || x.name === match[2]);
    //   //       if (id >= 0) {

    //   //               const    obj = { name: this.Imagecollection[id].file.name, file: this.Imagecollection[id].file, found: true };
    //   //               this.Batchuploadlist[key].Imagelist.push(obj);
    //   //               this.Batchuploadlist = this.Batchuploadlist.sort();

    //   //       }
    //   //   }
    // };
    // r.readAsText(file);
  }

  readFileContent1(file) {
    // const reader = new FileReader();
    // return new Promise( (resolve, reject) => {
    //   reader.onload = (event) => { resolve(event.target.result); };
    //   reader.onerror =  (error) => { reject(error); };
    //   reader.readAsText(file);
    // });
  }

  fileuploadchange(ix, fileInput: any) {
    console.log('index=', ix);
    const ind = ix;
    // console.log('index=', fileInput.target.files);
    console.log('item=', this.g.isbatch.value);
    if (this.g.isbatch.value === false) {
      this.Batchuploadlist = [];
      this.Imagecollection = [];
      this.uploadlist[ind].log = '';
      this.uploadlist[ind].instruction = '';
      this.uploadlist[ind].title = '';
      for (let i = 0; i < fileInput.target.files.length; i++) {
        const v = fileInput.target.files[i];
        if (this.uploadlist[ind].title === '') {
          this.uploadlist[ind].title = v.name;
        }
      }
      this.uploadlist[ind].Fileslist = fileInput;
      this.uploadlist[ind].chaptype = this.chaptertypelist[1];

    } else {
      this.uploadlist = [];
      this.Batchuploadlist = [];
      this.Imagecollection = [];
      for (let i = fileInput.target.files.length; i--;) {
        let obj: any;
        let id: number;
        if (fileInput.target.files[i].name !== 'Thumbs.db') {
          const res = fileInput.target.files[i].webkitRelativePath.split('/');
          if (res.length === 4) {
            if (res[2] === 'Graphics') {

              id = this.Batchuploadlist.findIndex(x => x.title === res[1]);

              if (id >= 0) {
                obj = new Object({ name: fileInput.target.files[i].name, file: fileInput.target.files[i], found: false });
                this.Batchuploadlist[id].Imagelist.push(obj);
              } else {
                obj = new Object(
                  { title: res[1], chaptype: this.chaptertypelist[1], Fileslist: [], Imagelist: [], instructions: '', log: '' }
                );
                obj.Imagelist.push(fileInput.target.files[i]);
                this.Batchuploadlist.push(obj);
              }
            } else {
              // return;
            }
          }
          if (res.length === 3) {

            if (res[1] === 'Graphics') {
              obj = { name: fileInput.target.files[i].name, file: fileInput.target.files[i], found: false };
              this.Imagecollection.push(obj);
            } else {

              id = this.Batchuploadlist.findIndex(x => x.title === res[1]);
              if (id >= 0) {
                this.Batchuploadlist[id].Fileslist.push(fileInput.target.files[i]);
              } else {
                obj = { title: res[1], chaptype: this.chaptertypelist[1], Fileslist: [], Imagelist: [], instructions: '', log: '' };
                obj.Fileslist.push(fileInput.target.files[i]);
                // obj.Fileslist.push(fileInput);
                this.Batchuploadlist.push(obj);
              }
            }
          }

          if (res.length === 2) {

            id = this.Batchuploadlist.findIndex(x => x.title === res[1]);
            if (id >= 0) {
              this.Batchuploadlist[id].Fileslist.push(fileInput.target.files[i]);
            } else {
              obj = { title: res[1], chaptype: this.chaptertypelist[1], Fileslist: [], Imagelist: [], instructions: '', log: '' };
              obj.Fileslist.push(fileInput.target.files[i]);
              // obj.Fileslist.push(fileInput);
              this.Batchuploadlist.push(obj);
            }
          }
        }
      }


      const result = this.Batchuploadlist.filter((item1) => {
        return item1.Fileslist.length > 1;
      });

      if (result.length > 0) {
        for (let i = this.Batchuploadlist.length; i--;) {
          if (this.Batchuploadlist[i].Fileslist.length > 1) {
            const value = this.Batchuploadlist[i];
            value.Fileslist.target.files.forEach((itm, k) => {

              const obj = { title: itm.name, chaptype: this.chaptertypelist[1], Fileslist: [], Imagelist: [], instructions: '', log: '' };
              obj.Fileslist.push(itm);
              if (value.Imagelist.length > 0) {
                //   this.readFileContent1(itm).then((content:any) => {
                //     const regex2 =
                //       RegExp('<blob(?: [^><]+)? (?:src|blob-ref-id)="([^"]*)"(?: [^><]+)(?:src|blob-ref-id)="([^"]*)', 'gi');
                //     const match = regex2.exec(content);
                //     while (match) {
                //       const id = value.Imagelist.findIndex(function (x) { return x.name === match[1] || x.name === match[2]; });
                //       if (id >= 0) {
                //         obj.Imagelist.push(
                //           { name: value.Imagelist[id].file.name, file: value.Imagelist[id].file, found: false });
                //       }
                //     }
                //    //  this.$apply(function ()
                //    // { this.Batchuploadlist.push(obj); this.Batchuploadlist = this.Batchuploadlist.sort(); });
                // }).catch(function (error) { console.log(error); });
              } else { this.Batchuploadlist.push(obj); }

            });
            this.Batchuploadlist.splice(i, 1);
          } else {
            this.Batchuploadlist[i].title = this.Batchuploadlist[i].Fileslist[0].name;
          }
        }
      }

      if (this.Imagecollection.length > 0) {
        this.Batchuploadlist.forEach((value, key) => {
          value.Fileslist.target.files.forEach((val, ind) => {
            this.readFileContent(val, key);
          });
        });
      }
      this.Batchuploadlist = this.Batchuploadlist.sort();
    }
  }

  next() {
    if (this.Batchuploadlist[0].title) {
      $('#step-1').css('display', 'none');
      $('#step-2').css('display', 'block');
      $('#step2').removeAttr('disabled');
      $('#step1').removeClass('btn-primary');
      $('#step1').addClass('btn-danger');
      $('#step2').addClass('btn-primary');
      $('#step2').removeClass('btn-danger');
    } else {
      this.toastr.warning('Please select files then proceed');
      return;
    }
  }

  Fnext() {
    if (this.uploadlist.length > 0) {
      this.uploadlist.forEach((v, k) => {
        v.log = '';
        if (v.title === '') {
          v.log = 'Please select file.';
          this.result = true;
        }
      });
      if (this.result === true) {
        this.toastr.error('Please clear log error then proceed');
        return;
      } else {
        const isvalidate = false;
        $('#step-3').css('display', 'none');
        $('#step-4').css('display', 'block');
        $('#step4').removeAttr('disabled');
        $('#step3').removeClass('btn-primary');
        $('#step3').addClass('btn-danger');
        $('#step4').addClass('btn-primary');
        $('#step4').removeClass('btn-danger');
      }
    }
  }

  LoadChaptertypes() {
    this.jobmasterservice.getChapterType().subscribe(res => {
      if (res.status === 200) {
        if (res !== undefined) {
          if (res.body !== 0) {
            this.chaptertypelist = JSON.parse(res.body[0]);
            console.log('this.chaptertypelist=', this.chaptertypelist);
            if (res.body.length > 0) {
              this.Selectedchaptertype = JSON.parse(res.body[0]);
            }
          }
        }
      }
    },
      error => {
        this.toastr.error('Error while getting chapter list');
        this.chaptertypelist = [];
      });
  }

  showhid(val) {
    if (val === 'step-1') {
      $('#step-1').css('display', 'block');
      $('#step-2').css('display', 'none');
      $('#step2').removeClass('btn-primary');
      $('#step2').addClass('btn-danger');
      $('#step1').addClass('btn-primary');
      $('#step1').removeClass('btn-danger');
    } else if (val === 'step-2') {

      if (this.Batchuploadlist[0].title) {
        $('#step-1').css('display', 'none');
        $('#step-2').css('display', 'block');
        $('#step1').removeClass('btn-primary');
        $('#step1').addClass('btn-danger');
        $('#step2').addClass('btn-primary');
        $('#step2').removeClass('btn-danger');
      }
    } else if (val === 'step-3') {
      $('#step-4').css('display', 'none');
      $('#step-3').css('display', 'block');
      $('#step4').removeClass('btn-primary');
      $('#step4').addClass('btn-danger');
      $('#step3').addClass('btn-primary');
      $('#step3').removeClass('btn-danger');
    } else if (val === 'step-4') {
      if (this.uploadlist[0].title) {
        $('#step-3').css('display', 'none');
        $('#step-4').css('display', 'block');
        $('#step3').removeClass('btn-primary');
        $('#step3').addClass('btn-danger');
        $('#step4').addClass('btn-primary');
        $('#step4').removeClass('btn-danger');
      }
    }
  }

  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);
    }
  }

  mapchapter(currind, chap, chapt) {
    console.log('chap.chaptype.chaptertypeid=', chap.chaptype.chaptertypeid);
    console.log('chap=', chap);
    this.selectedjobitem.docid=chap.docid;
    chap.chaptype = this.chaptertypelist.filter(c => c.chaptertypeid === +chap.chaptype.chaptertypeid)[0];
    if (this.g.isbatch.value === false) {
      const ch = this.mappedchapter.filter(x => x.chaptertype === chap.chaptype.chaptertype);
      if (ch.length === 0) {
        this.mappedchapter.push({docid:chap.docid, chaptertype: chap.chaptype.chaptertype, chaptertypeid: chap.chaptype.chaptertypeid, chapters: [] });
      }
      const ind = this.mappedchapter.findIndex((x) => x.chaptertype === chap.chaptype.chaptertype);
      chap.chaptertype = chap.chaptype.chaptertype;
      chap.chaptertypeid = chap.chaptype.chaptertypeid;
      this.mappedchapter[ind].chapters.push(chap);
      this.uploadlist.splice(currind, 1);
    } else {
      const ch1 = this.mappedchapter.filter(x => x.chaptertype === chap.chaptype.chaptertype);
      if (ch1.length === 0) {
        this.mappedchapter.push({docid:chap.docid, chaptertype: chap.chaptype.chaptertype, chaptertypeid: chap.chaptype.chaptertypeid, chapters: [] });
      }
      const ind1 = this.mappedchapter.findIndex((x) => x.chaptertype === chap.chaptype.chaptertype);
      chap.chaptertype = chap.chaptype.chaptertype;
      chap.chaptertypeid = chap.chaptype.chaptertypeid;
      this.mappedchapter[ind1].chapters.push(chap);
      this.Batchuploadlist.splice(currind, 1);
    }
  }
  guid() {
    return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' + this.s4() + this.s4() + this.s4();
  }
  s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  
  Savelot(joblotForm) {

    if (this.joblotForm.value.basedonfile === false) {
      if ((joblotForm.value.title === null) || (joblotForm.value.title.trim() === '')) {
        this.toastr.error('Mandatory fields should not be empty');
        return;
    }}

    const lotcnt = this.lotlist.length;
    this.selcahp = [];
    let i = 1;
    this.mappedchapter = this.mappedchapter.sort();
    this.mappedchapter.forEach((val, index) => {
      val.chapters.forEach((val1, index1) => {
        val1.sequence = i;
        this.selcahp.push(val1);
        i = i + 1;
      });
    });
    if (this.selcahp.length <= lotcnt) {
      this.toastr.warning('Please select chapter then proceed');
      return;
    }
    this.selectedjobitem.lotkey = this.guid();
    let auto = 0;
    if (this.joblotForm.value.autoinc === undefined) {
      auto = 1;
    } else {
      auto = this.joblotForm.value.autoinc;
    }
    this.SpinnerService.show();
    // this.showlog = false;
    const obj1 = {
      lotid: this.selectedjobitem.lotid,
      jobid: this.selectedjobitem.jobid,
      docid: this.selectedjobitem.docid,
      title: this.joblotForm.value.title,
      sequence: 1,
      instructions: this.joblotForm.value.isbatch === false ? '' : this.selectedjobitem.instructions,
      filename: this.selectedjobitem.filename,
      priority: 1,
      foldername: this.selectedjobitem.foldername,
      totalunits: 0,
      lotstatus: this.selectedjobitem.lotstatus,
      pickedby: 0,
      withvendor: 0,
      lotkey: this.selectedjobitem.lotkey,
      createdby: this.selectedjobitem.createdby,
      createdon: this.selectedjobitem.createdon,
      updatedby: this.selectedjobitem.updatedby,
      updatedon: this.selectedjobitem.updatedon,
      tathours: this.selectedjobitem.tathours,
      chaptertypeid: this.Selectedchaptertype.chaptertypeid
    };

    if (this.ButtonType === 'Add Chapter') {
      this.createlot(obj1, auto);
    }
   // this.SpinnerService.hide();
  }

  createlot(obj1, auto) {
    const filenamelist = [];
    this.selcahp.forEach((val, ke) => {
      if (this.joblotForm.value.basedonfile) {
        let filename = '';
        if (val.Fileslist !== undefined) {
          if (val.Fileslist.length !== undefined) {
            if (val.Fileslist.length > 1) {
              for (let i = 0; i < val.Fileslist.length; i++) {
                const vals = val.Fileslist[i];
                if (vals.name.split('.')[1] === 'html') {
                  filename = vals.name.split('.')[0];
                }
              }
            } else {
              for (let i = 0; i < val.Fileslist.length; i++) {
                const vals = val.Fileslist[i];
                filename = vals.name.split('.')[0];
              }
            }
            filenamelist.push(
              {
                title: val.title.replace('.xml', ''),
                filename: filename,
                seq: val.sequence,
                docid: val.docid,
                lotid: val.lotid, chaptertypeid: val.chaptertypeid,
                instruction: val.instruction
              });

          } else {
            filename = val.title.split('.')[0];
            filenamelist.push(
              {
                title: val.title.split('.')[0],
                filename: filename,
                seq: val.sequence,
                docid: val.docid,
                lotid: val.lotid, chaptertypeid: val.chaptertypeid,
                instruction: val.instruction
              });
          }
        } else {
          if (val.isexist === undefined || val.isexist === false) {
            filenamelist.push(
              {
                title: obj1.title + '-' + auto,
                filename: val.title.split('.')[0],
                seq: val.sequence, docid: obj1.docid,
                lotid: val.lotid, chaptertypeid: val.chaptertypeid, instruction: val.instruction
              }); auto = auto + 1;
          } else {
            filenamelist.push(
              {
                title: val.title.replace('.xml', ''),
                filename: val.title.split('.')[0],
                seq: val.sequence, docid: val.docid,
                lotid: val.lotid, chaptertypeid: val.chaptertypeid, instruction: val.instruction
              });
          }
        }
      } else {
        if (val.isexist === undefined || val.isexist === false) {
          filenamelist.push(
            {
              title: obj1.title + '-' + auto,
              filename: val.title.split('.')[0],
              seq: val.sequence, docid: obj1.docid,
              lotid: val.lotid, chaptertypeid: val.chaptertypeid, instruction: val.instruction
            }); auto = auto + 1;
        } else {
          filenamelist.push(
            {
              title: val.title.replace('.xml', ''),
              filename: val.title.split('.')[0],
              seq: val.sequence, docid: val.docid,
              lotid: val.lotid, chaptertypeid: val.chaptertypeid, instruction: val.instruction
            });
        }
      }
    });

    const mappedStageList = filenamelist.map(f => (
      {
        lotid: f.lotid,
        jobid: this.selectedjobitem.jobid,
        title: f.title,
        chaptertypeid: f.chaptertypeid,
        sequence: f.seq,
        instructions: f.instruction,
        filename: f.filename,
        priority: 1,
        foldername: this.selectedjobitem.foldername,
        totalunits: 0,
        lotstatus: this.selectedjobitem.lotstatus,
        pickedby: 0,
        withvendor: 0,
        lotkey: this.guid(),
        createdby: this.selectedjobitem.createdby,
        createdon: this.selectedjobitem.createdon,
        updatedby: this.selectedjobitem.updatedby,
        updatedon: this.selectedjobitem.updatedon,
        tathours: this.selectedjobitem.tathours,
        docid: f.docid
      }));
    // this.SpinnerService.hide();
    // return;
    console.log('newOject', mappedStageList);
    // this.SpinnerService.show();
    this.jobmasterservice.postLotMaster(mappedStageList).subscribe(lotres => {
      // if (d.data.Message != undefined && d.data.Message === 'Warning') {
      //   this.toastr.error('Chapter name already exist');
      //   return;
      // }
      const lotress = JSON.parse(lotres.body[0]);
      const lotdetails = lotress.filter((itm) => itm.Transid > 0);
      const formData = new FormData();
      // this.selcahp = this.selcahp.filter(s => s.jobid == null);
      this.selcahp.forEach((value, key) => {
        if (value !== undefined && (value.isexist === undefined || value.isexist === false)) {
          value.lotid = lotress[key].lotid;
          this.isuplaod = true;
          // value.Fileslist.target === undefined ? value.Fileslist = value.Fileslist[0] : '';
          if (value.Fileslist.target) {
            for (let i = 0; i < value.Fileslist.target.files.length; i++) {
              const val = value.Fileslist.target.files[i];
              if (val !== undefined) {
                formData.append('file', val,
                  val.name + '~' + lotress[key].lotid + '~' + this.selectedjobitem.jobid + '~' +
                  value.instructions + '~' + value.chaptype.chaptertypeid + '~' + false);
              }
            }
          } else {
            value.Fileslist.target === undefined ? value.Fileslist.target = value.Fileslist : '';
            for (let i = 0; i < value.Fileslist.target.length; i++) {
              const val = value.Fileslist.target[i];
              if (val !== undefined) {
                formData.append('file', val,
                  val.name + '~' + lotress[key].lotid + '~' + this.selectedjobitem.jobid + '~' +
                  value.instructions + '~' + value.chaptype.chaptertypeid + '~' + false);
              }
            }
          }
          if (value.Imagelist !== undefined) {
            if (value.Imagelist.length > 0) {
              value.Imagelist.forEach((val, k) => {
                if (val !== undefined && val.file !== undefined) {
                  formData.append('file',
                    val.file, val.file.name + '~' + lotress[key].lotid + '~' + this.selectedjobitem.jobid + '~' +
                    value.instructions + '~' + value.chaptype.chaptertypeid + '~' + true);
                }
              });
            }
          }
        }
      });

      if (this.isuplaod === true) {
        this.jobmasterservice.UploadLotFile(formData).subscribe(d => {
          console.log(formData);
          //   this.triggerapp(lotdetails);
          this.toastr.success('Successfully Added the Chapter');
          this.clearForm();
          this.SpinnerService.hide();
          //   // this.lotcreated = true;
          //   this.closeThisDialog('close');
          //   // window.location = "#/Allotement/" + this.projecdefid + "/" + this.job;
        });
      } else {
        this.triggerapp(lotdetails);
        this.toastr.success('Successfully Added the Chapter');
        this.clearForm();
        // this.lotcreated = true;
        // this.closeThisDialog('close');
        // window.location = "#/Allotement/" + this.projecdefid + "/" + this.job;
      }
    }, error => {
      this.toastr.error('Error in Adding Chapter Records');

    });
  }

  triggerapp(data) {
    // angular.forEach(data, function (value, key) {
    //    const   response = $http({
    //        method: "post",
    //        url: "api/Lot_MasterApi/Trigerqueue",
    //        params: {
    //            tranid: value.Transid,
    //            userid: value.userid

    //        }
    //    });
    //    response.then(function (d) {

    //        if (d.data === false) {
    //            const   turl = triggerappurl.replace("$$tranid$$", value.Transid);
    //            turl = turl.replace("$$userid$$", value.userid);
    //            turl = turl.replace("&amp;", "&");
    //            $http.post(turl);
    //        }
    //    });
    // });
  }

  instructionchange(index, item) {
    if (this.joblotForm.value.isbatch === false) {
      this.uploadlist[index].instruction = item.value;
    }
  }

  FBack() {
    $('#step-3').css('display', 'block');
    $('#step-4').css('display', 'none');
    $('#step4').removeClass('btn-primary');
    $('#step4').addClass('btn-danger');
    $('#step3').addClass('btn-primary');
    $('#step3').removeClass('btn-danger');
  }
  Back() {
    $('#step-1').css('display', 'block');
    $('#step-2').css('display', 'none');
    $('#step2').removeClass('btn-primary');
    $('#step2').addClass('btn-danger');
    $('#step1').addClass('btn-primary');
    $('#step1').removeClass('btn-danger');
  }

  changeChapter(eve, i, type) {
    if (type === 'batch') {
      const chappterId = eve.target.selectedOptions[0].value;
      const chaptype = this.chaptertypelist.filter(c => c.chaptertypeid === +chappterId)[0];
      this.Batchuploadlist[i]['chaptype'] = chaptype;
    } else {
      const chappterId = eve.target.selectedOptions[0].value;
      const chaptype = this.chaptertypelist.filter(c => c.chaptertypeid === +chappterId)[0];
      this.uploadlist[i]['chaptype'] = chaptype;
    }
  }

  changeIsBatch(isbatch) {
    console.log('isbatch', isbatch);
    this.joblotForm.controls['basedonfile'].setValue(isbatch);

  }
}
