import { Component, OnInit, Input, OnChanges, ViewChild, TemplateRef, IterableDiffers } from '@angular/core';
import { WorkareaService } from './workarea.service';
import { ToastrService } from 'ngx-toastr';
import { ModalModule, BsModalService, BsModalRef, ModalOptions } from 'ngx-bootstrap/modal';
import { ActivatedRoute } from '@angular/router';
import { saveAs } from 'file-saver';
import { NgxSpinnerService } from 'ngx-spinner';
import { environment } from '../../environments/environment';
import { HttpClient, HttpParams } from '@angular/common/http';
import { take } from 'rxjs/operators';
// import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
declare var $: any;
declare var JSZip: any;

@Component({
  selector: 'app-workarea',
  templateUrl: './workarea.component.html',
  styleUrls: ['./workarea.component.css']
})
export class WorkareaComponent implements OnInit {
  colspan = '6';
  colspan_style = '{\'margin-left\':\'25%\'}';
  // loginuserid: string = localStorage.getItem('userid');
  loginuserid = 4;
  tostageorder: number;
  p_tranid = 397;

  p_lotid: string;
  p_jobid: string;
  p_jobworkflowid: string;
  fromorder = 4;
  p_lotstatus: string;
  p_transactiontimer: any;
  p_holdreason: string;
  p_userid: string;

  selectedType: string = '';
  selectedStatus: string = '';

  queryTypes = ['File Errors', 'Incomplete Scans', 'Missing Pages', 'Others'];
  queryStatuses = ['Resolved', 'Addressed', 'Submitted'];
  isSubmitted = false;
  p_status: string;
  p_option: string;
  p_comments: string;
  jobworkflowid: number;
  panel_field: string;
  smessage: string;
  jobaccesstype: string;
  checkoutAppDetails: any;
  jobtitle: string;
  lottitle: string;
  jobid: number;
  lotid: number;
  project_subtitle1: string;
  entity: any;
  lotmetafields: any;
  lotmastermetafields: any;
  jobno: string;
  lotstatus: string;
  duedate: string;
  tat: string;
  stagename_alias: string;
  tranid: number;
  crtcomments: string;
  movebackstage: any;
  inprocessapp: any;
  appname: string;
  mailattachment: string;
  transactionkey: any;
  mergedlot: number;
  tojobworkflowid: number;
  lc_comments: string;
  lc_lotid: number;
  serverroot: string;
  downloderpath: string;
  isbrons: any;
  bronskey: any;
  isbronsupdate = false;
  saveoutfile = false;
  bronsdetailsAll: any;
  load_tool: string;
  dragHandle: any;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };

  workAreaPopUpModalRef: BsModalRef;
  aModalRef: BsModalRef;
  @ViewChild('alerttemplate', { static: true }) alertTemplate!: TemplateRef<any>;

  alerttemplate_: TemplateRef<any> = this.alertTemplate;
  comments: string;
  loading = false;
  loadings = false;
  comments_header: string;
  filespath: string;
  buttonType: string;
  calltype: string;
  lotlist_output = [];
  lotlist = [];
  lotlistTmp = [];
  lotlist_filter = [];
  uniqueStageTitles = [];
  lot_comments = [];
  ddlLotListTypeSettings: {};
  userSelectedItems: any = [];
  procomment: any;
  itemData: any;
  cflag = '';
  selback = '';
  token: any;
  userid: any;
  transid: any;
  pdid: any;
  enviroment: any;
  serverappUrl = environment.serverappUrl;
  private sub: any;
  // public Editor = ClassicEditor;
  downloadPopUpModalRef: BsModalRef;
  FileOutList: any = [];
  filedownloadstage = true;
  filedownloadinstage = false;
  showdownload = true;
  uploadoutputfile = true;
  xFileInList: any = [];
  xFileOutList: any = [];
  infilesactive = true;
  outfilesactive = false;
  filevalidate = true;
  checklist_title = '';
  checklistLstview = [];
  checklistLstQry = [];
  mystatus: boolean;
  checkListPopupMOdalRef: BsModalRef;
  OutfileExtension: any;
  Outfiletypes: any;
  checklistbuttonhide = [];
  p_prevtranid = 0; docid: any;
  projectdefnitionid = 0;
  appgetdata: any;
  error: any;
  isProcessing: boolean = false;
  alertvisible: boolean = false;
  transactionId: any = null;
  errorMessage: string = '';
  //hari

  uploadedFiles: { name: string, type: string }[] = [];

  stageTypes = [
    { value: '1', label: 'LARE Review' },
    { value: '2', label: 'Redaction and Styling' }
  ];

  skipid = '';

  uploadProgress: number = -1;
  currentFileName: string = '';

  ckeConfig = {
    allowedContent: false,
    forcePasteAsPlainText: true,
    font_names: 'Arial;Times New Roman;Verdana',
    toolbarGroups: [
      { name: 'document', groups: ['mode', 'document', 'doctools'] },
      { name: 'clipboard', groups: ['clipboard', 'undo'] },
      { name: 'editing', groups: ['find', 'selection', 'spellchecker', 'editing'] },
      { name: 'forms', groups: ['forms'] },
      '/',
      { name: 'basicstyles', groups: ['basicstyles', 'cleanup'] },
      { name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi', 'paragraph'] },
      { name: 'links', groups: ['links'] },
      { name: 'insert', groups: ['insert'] },
      '/',
      { name: 'styles', groups: ['styles'] },
      { name: 'colors', groups: ['colors'] },
      { name: 'tools', groups: ['tools'] },
      { name: 'others', groups: ['others'] },
      { name: 'about', groups: ['about'] }
    ],
    removeButtons: 'Source,Save,NewPage,Preview,Print,Templates,Cut,Copy,Paste,PasteText,PasteFromWord,Undo,Redo,Find,Replace,SelectAll,Scayt,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Strike,Subscript,Superscript,CopyFormatting,RemoveFormat,Outdent,Indent,CreateDiv,Blockquote,BidiLtr,BidiRtl,Language,Unlink,Anchor,Image,Flash,Table,HorizontalRule,Smiley,SpecialChar,PageBreak,Iframe,Maximize,ShowBlocks,About'
  };


  lotcount: any;


  constructor(private workareaservice: WorkareaService,
    private toastr: ToastrService,
    private modalService: BsModalService,
    private route: ActivatedRoute,
    private SpinnerService: NgxSpinnerService,
    private http: HttpClient
  ) { }

  ngOnInit(): void {
    this.alerttemplate_ = this.alertTemplate;
    this.panel_field = '0';
    this.sub = this.route.params.subscribe(params => {
      this.token = params['token'];
      this.loginuserid = +params['userid'];
      this.p_tranid = +params['transid'];
      this.pdid = +params['pdid'];
      this.enviroment = params['enviroment'];
      // (+) converts string 'id' to a number
      // In a real app: dispatch action to load the details here.
    });
    // this.getCheckout();
    this.getcurrentjobdetails();
    // this.getocrconversionpath();
    // this.getPreviousStageTranid(); 
    // this.getChecklistDetail(); 
  }


  getCheckout() {
    // this.p_tranid = 1;
    this.p_status = 'P';
    this.p_option = 'checkin';
    this.p_comments = '';
    this.jobworkflowid = 0;
    const inputvalue = [];
    inputvalue.push(
      {
        p_tranid: + this.p_tranid,
        p_userid: + this.loginuserid,
        p_status: this.p_status,
        p_option: this.p_option,
        p_comments: this.p_comments,
        jobworkflowid: +this.jobworkflowid
      });
    this.workareaservice.getCheckout(inputvalue[0]).subscribe(res => {
      // this.departments = JSON.parse(res[0]);

    }, error => { this.toastr.error('Error while getting data'); });
  }
  getcurrentjobdetails() {
    this.load_tool = '1';
    // this.p_tranid = 858;
    this.p_option = 'getlotdata';
    const inputvalue = [];
    inputvalue.push(
      {
        p_tranid: this.p_tranid.toString(),
        p_userid: this.loginuserid.toString(),
        p_option: this.p_option
      });
    console.log(inputvalue[0]);
    this.workareaservice.usrstagemove(inputvalue[0], this.token).subscribe(res => {
      debugger;
      if (res.body !== null && res.body !== undefined && res.body[0] !== null && res.body[0] !== undefined) {
        this.panel_field = '1';
        const resData = JSON.parse(res.body[0]);
        console.log(resData);
        this.smessage = '';
        this.jobaccesstype = '2';
        this.checkoutAppDetails = resData;
        this.jobtitle = resData.jobtitle;
        this.lottitle = resData.lottitle;
        this.jobid = resData.jobid;
        this.lotid = resData.lotid;
        this.project_subtitle1 = resData.projecttitle;
        this.entity = resData.jobmetafields;
        this.lotmetafields = resData.lotmetafields;
        this.lotmastermetafields = resData.lotmastermetafields;
        this.jobno = resData.jobno;
        this.lotstatus = resData.lotstatus;
        this.duedate = resData.Duedate;
        this.tat = resData.tat;
        this.stagename_alias = resData.stagename;
        this.tranid = resData.transactionid;
        this.crtcomments = resData.crtcomments === null ? '' : resData.crtcomments;
        this.movebackstage = resData.movebackstage;
        this.inprocessapp = resData.inprocessapp;
        this.appname = resData.appname;
        this.mailattachment = resData.mailattachment === null ? '0' : resData.mailattachment;
        console.log(this.mailattachment);
        this.transactionkey = resData.transactionkey;
        this.mergedlot = resData.merged_lot;
        this.lotcount = resData.lotcount;
        console.log("lotcount" + resData.lotcount);
        this.tojobworkflowid = resData.tojobworkflowid;
        this.lc_comments = resData.comments;
        this.lc_lotid = resData.lc_lotid;
        this.docid = resData.docid;
        this.projectdefnitionid = resData.projectdefinitionid
        this.getallOutFiles();
        this.getOutfileExtension();
        if (this.projectdefnitionid.toString() == "367") {

          debugger;
          this.getocrconversionpath();
          //this.getocrpdffile();

        }



        // this.previousstageChecklistdts();
      }

      //     if (d.data.message != undefined && d.data.message === "Access denied.")
      //     { $scope.jobaccesstype = "0"; $scope.smessage = d.data.message; }
      //     else if (d.data.message != undefined && d.data.message === "Invaild path.")
      //     { $scope.jobaccesstype = "1"; $scope.smessage = d.data.message; }
      //     else if (d.data.message != undefined && d.data.message === "Completed.")
      //     { $scope.jobaccesstype = "3"; $scope.smessage = d.data.message; }
      //     else if (d.data.message != undefined && d.data.message === "Locked by other user.")
      //     { $scope.jobaccesstype = "4"; $scope.smessage = d.data.message; }
      //     else {
      //         $scope.smessage = '';
      //         $scope.jobaccesstype = "2";
      //         $scope.checkoutAppDetails = d.data[0];
      //         $scope.jobtitle = d.data[0].jobtitle;
      //         $scope.lottitle = d.data[0].lottitle;
      //         $scope.jobid = d.data[0].jobid;
      //         $scope.lotid = d.data[0].lotid;
      //         $scope.project_subtitle1 = d.data[0].projecttitle;
      //         $scope.entity = d.data[0].jobmetafields;
      //         $scope.lotmetafields = d.data[0].lotmetafields;
      //         $scope.lotmastermetafields = d.data[0].lotmastermetafields;
      //         $scope.jobno = d.data[0].jobno;
      //         $scope.lotstatus = d.data[0].lotstatus;
      //         $scope.duedate = d.data[0].Duedate;
      //         $scope.tat = d.data[0].tat;
      //         $scope.stagename_alias = d.data[0].stagename;
      //         $scope.tranid = d.data[0].transactionid;
      //         $scope.crtcomments = d.data[0].crtcomments;
      //         $scope.movebackstage = d.data[0].movebackstage;
      //         $scope.inprocessapp = d.data[0].inprocessapp;
      //         $scope.appname = d.data[0].appname;
      //         $scope.mailattachment = d.data[0].mailattachment;
      //         $scope.transactionkey = d.data[0].transactionkey;
      // $scope.mergedlot = d.data[0].merged_lot;
      // $scope.tojobworkflowid = d.data[0].tojobworkflowid;
      // $scope.lc_comments = d.data[0].comments;
      // $scope.lc_lotid = d.data[0].lc_lotid;

      // $scope.serverroot = serverroot + '/Home/Uploader/Downloader?F=' + $scope.jobtitle 
      // + '.zip&L=' + $scope.transactionkey + '&U=' + usrid;

      // $scope.downloderpath = approot + '/Downloader/Index?tranid=' + $scope.tranid;
      //     }
    }, error => {
      this.smessage = 'Error while getting data';
      this.toastr.error('Error while getting data');
    });
  }

  getocrconversionpath() {

    debugger;
    let res1 = this.workareaservice.getOcrStage(this.jobid).subscribe(res1 => {
      debugger;



      this.filespath = res1;


      // this.load_tool = '1';
      //this.toastr.success('Saved succe ssfully.');
      // top.location.href = this.serverappUrl + '/dashboard';
      // this.workAreaPopUpModalRef.hide();
    });

  }

  // method the hold the stage
  holdStage(template: TemplateRef<any>) {
    debugger;
    this.comments = 'Hold Comments';
    this.comments_header = 'Comments';
    this.buttonType = 'Hold';
    this.calltype = 'hold';
    this.itemData = this.checkoutAppDetails;
    console.log('test');
    console.log(this.itemData);
    this.workAreaPopUpModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
    this.ddlLotListTypeSettings = {
      singleSelection: false,
      idField: 'lotid',
      textField: 'title',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true
    };
    this.loadJobDetails();
  }
  //kiruthiga
  IgnoreStage(template: TemplateRef<any>) {
    debugger;
    debugger;
    this.comments = 'Ignore Comments';
    this.comments_header = 'Comments';
    this.buttonType = 'Ignore';
    this.calltype = 'Ignore';
    this.itemData = this.checkoutAppDetails;
    console.log('test');
    console.log(this.itemData);
    this.workAreaPopUpModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
    this.ddlLotListTypeSettings = {
      singleSelection: false,
      idField: 'lotid',
      textField: 'title',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true
    };
    this.loadJobDetails();
  }

  ForwardStage(template: TemplateRef<any>) {
    debugger;
    debugger;
    this.comments = 'Forward Comments';
    this.comments_header = 'Comments';
    this.buttonType = 'Forward';
    this.calltype = 'Forward';
    this.itemData = this.checkoutAppDetails;
    console.log('test');
    console.log(this.itemData);
    this.workAreaPopUpModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
    this.ddlLotListTypeSettings = {
      singleSelection: false,
      idField: 'lotid',
      textField: 'title',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true
    };
    this.loadJobDetails();
  }


  downloadPopUp(template: TemplateRef<any>, jobid) {
    this.comments_header = 'Download';
    this.comments = 'Stage based Download';
    this.downloadPopUpModalRef = this.modalService.show(template, this.config);
    this.GetInOutFiles();
  }
  // method to load job details
  loadJobDetails() {
    debugger;
    this.lotlist_output = [];
    this.lotlist = [];
    this.lotlist_filter = [];
    let lotid_lot = 0;
    if (this.mergedlot === 0) {
      lotid_lot = this.lotid;
    }
    const inputData = [];
    inputData.push({
      jobid: this.jobid,
      lotid: lotid_lot,
      projectdefinitionid: this.projectdefnitionid
    })
    this.workareaservice.getJobDetails(inputData[0]).subscribe(res => {
      if (res.body[0] !== undefined && res.body[0] !== null && JSON.parse(res.body[0]).length > 0) {
        this.lotlist = JSON.parse(res.body[0]);
        if (this.mergedlot === 0) {
          this.lotlist.forEach((i, ind) => {
            if (i.lotid === this.lotid) {
              i.ticked = true;
            } else {
              i.ticked = false;
            }
          });
        }
        this.lotlistTmp = this.lotlist.map(t => ({ lotid: t.lotid, title: t.title }));

      }
      if (res.body[1] !== undefined && res.body[1] !== null && JSON.parse(res.body[1]).length > 0) {
        this.uniqueStageTitles = JSON.parse(res.body[1]);

      }
      if (res.body[3] !== undefined && res.body[3] !== null && JSON.parse(res.body[3]).length > 0) {
        this.lot_comments = JSON.parse(res.body[3]);
      }
      if (this.buttonType === 'Hold') {
        this.selback = this.itemData.jobworkflowid.toString();
      } else {
        this.selback = this.itemData.nextstage.toString();
      }
    }, err => { this.toastr.error('Loading Lot detail failed.'); });

  }

  onItemSelect(item: any) {
    this.lotlist_output.push(item);
    this.selectLotDetails();
  }
  onItemDeSelect(item: any) {
    let res;
    res = this.lotlist_output.findIndex(d => d.lotid === item.lotid);
    let splic = [];
    splic = this.lotlist_output.splice(res, 1);
    this.selectLotDetails();
  }
  onSelectAll(item: any) {
    item.forEach(element => {
      this.lotlist_output.push(element);
    });
    this.selectLotDetails();
  }
  onDeSelectAll(item: any) {
    this.lotlist_output = [];
  }
  selectLotDetails() {
    if (this.lotlist_output.length > 0) {
      let lotids = '';
      this.lotlist_output.forEach(i => {
        lotids = i.lotid + ',' + lotids;
      });
      const inputData = [];
      inputData.push({ jobid: this.jobid, lotid: lotids });
      this.workareaservice.getLotDetailsComments(inputData[0]).subscribe(res => {
        console.log(res.body);
        if (res.body !== undefined && res.body !== null && JSON.parse(res.body).length > 0) {
          this.lot_comments = JSON.parse(res.body);
          this.lot_comments.forEach(i => {
            if (i.tojobworkflowid === null) {
              i.tojobworkflowid = 0;
            }
          })
          console.log(this.lot_comments);
        }
      }, err => { this.toastr.error('Loading Lot detail failed.'); });
    }
  }
  getdispatch() {
    debugger;
    let res1 = this.workareaservice.getdispatchwating(this.jobid, this.tranid, this.lotid, this.project_subtitle1).subscribe(res1 => {
      debugger;
      this.load_tool = '1';
      this.toastr.success('Saved successfully.');
      top.location.href = this.serverappUrl + '/dashboard';
      this.workAreaPopUpModalRef.hide();
    });
  }
  // method to save the hold or complete stage
  async add() {
    let entity_temp = null;
    if (this.entity !== null) {
    }
    if (this.procomment === null) {
      this.procomment = '';
    }

    if (this.procomment === "" && this.cflag === "F" && this.buttonType != 'Complete' && this.buttonType != 'Hold') {
      debugger;
      this.toastr.error('Kindly fill the Ignore comments');
      return;
    }

    if ((this.stagename_alias === 'XML Correction') && this.calltype === 'checkout') {
    } else {
      debugger;
      if (this.buttonType !== 'Hold' && this.cflag !== 'F' && this.cflag !== 'S')
      // your logic here


      {
        debugger;
        await this.checkOutFileExist();
      }


      if (this.filevalidate == false) {
        return;
      }
      let fields = {
        transid: this.itemData.transactionid, fields: JSON.stringify(entity_temp),
        option: this.calltype, cflag: this.cflag, userid: this.loginuserid
      };
      // let fileUpload: any = document.getElementById('inputGroupFile01');
      //  var file: File = input.files[0];
      // let fileUpload = $('#inputGroupFile01').get(0);
      // let files = fileUpload.files;
      let fileData = new FormData();
      // if (files.length > 0) {
      //   fileData.append('file', files[0]);
      // }
      fileData.append('model', JSON.stringify(fields));
      if ((this.stagename_alias === 'Redaction and Styling') && this.cflag == 'F') {

        debugger;

        if (this.project_subtitle1 == "LN_BPM") {

          debugger;

          this.tostageorder = 10;

        }
        else {
          this.tostageorder = 12;
        }

        //let res=await this.workareaservice.getdispatchid(this.jobid).toPromise().then(res=>res);
        const jobObject = new Object({
          tranid: +this.itemData.transactionid,
          fromorder: +this.itemData.stageorder,
          toorder: this.tostageorder,
          option: 'F'
        });
        this.workareaservice.jobBackForward(jobObject, this.token).subscribe(res => {

          debugger;
          if (res.body !== undefined && res.body !== null) {
            this.getdispatch();


          }
        });


        return;
      }

      else if ((this.stagename_alias === 'LARE Review') && this.cflag == 'S') {

        debugger;
        console.log('tranid:', this.tranid);
        console.log('lotid:', this.lotid);
        console.log('jobworkflowid:', this.jobworkflowid);
        console.log('itemData:', this.itemData);
        //console.log('itemData.stageorder:', this.itemData?.stageorder);

        const jobObject = {
          p_tranid: this.tranid.toString(),          // add () to call method
          p_lotid: this.lotid.toString(),            // add ()
          p_jobid: this.jobid,                        // assuming jobid is already string or number
          p_jobworkflowid: this.itemData.jobworkflowid.toString(), // add ()
          fromorder: this.itemData.stageorder.toString(), // add ()
          p_lotstatus: 'D',
          p_option: 'fail',
          p_userid: this.userid,                      // assuming userid is number or string (if number, backend must accept number)
          p_holdreason: '0',
          p_transactiontimer: ''
        };



        this.workareaservice.forwardstage(jobObject).subscribe({
          next: (res) => {
            if (res !== undefined && res !== null && res.body !== undefined && res.body !== null) {
              this.toastr.success('Chapter Forwarded successfully');
              top.location.href = this.serverappUrl + '/dashboard';
              return;  // stop further execution in this callback
            } else {
              this.toastr.error('Forward failed: empty response.');
              top.location.href = this.serverappUrl + '/dashboard';
              return;  // stop further execution
            }
          },
          error: (err) => {
            //console.error('Error forwarding chapter:', err);
            this.toastr.success('Chapter Forwarded successfully');
            //this.toastr.error('An error occurred while forwarding the chapter.');
            top.location.href = this.serverappUrl + '/dashboard';
            return;  // stop further execution
          }
        });
        return;
      }


      else {
        fileData.append('tostage', this.selback);
      }
      debugger;
      fileData.append('querytype', this.selectedType);
      fileData.append('Status', this.selectedStatus);
      fileData.append('jobid', this.itemData.jobid);
      fileData.append('comment', this.procomment);
      if (this.itemData.merged_lot === '1') {
        fileData.append('batchid', this.itemData.lotid);
      } else {
        fileData.append('batchid', '');
        fileData.append('lotid', this.itemData.lotid);
      }
      this.workareaservice.PostUpdateLotTransaction(fileData, this.token).subscribe(res => {
        if (res.body !== undefined && res.body !== null) {
          this.load_tool = '1';
          this.toastr.success('Saved successfully.');
          top.location.href = this.serverappUrl + '/dashboard';
          this.workAreaPopUpModalRef.hide();
        }
      }, err => { this.toastr.error('Error in Start App details'); });

    }
  }
  // async checkOutFileExist() {
  //   debugger;
  //   try {
  //     if (this.stagename_alias === 'Redaction and Styling'||this.stagename_alias === 'Styling and Conversion'||this.stagename_alias === 'Finalization'||this.stagename_alias === 'VISF QC and Review'||this.stagename_alias === 'QA'|| this.stagename_alias === 'LARE Review' ) {
  //      // const res = await this.workareaservice.ValidateOutFileExist(this.jobid, this.tranid).toPromise();
  // let res=await this.workareaservice.ValidateOutFileExist(this.jobid, this.tranid,this.stagename_alias,this.projectdefnitionid).toPromise().then(res=>res);
  // debugger;
  // console.log(res);
  //       if (res.result === true) {
  //         this.filevalidate=true;
  //       } else {
  //         this.filevalidate=false;
  //         this.toastr.error('Kindly upload out files and complete the stage.');
  //         return;
  //       }
  //     }
  //   } catch (err) {
  //     this.toastr.error('Error in Getting out file validation');
  //   }
  // }
  async checkOutFileExist() {

    try {

      // Trim stage name to avoid space issues
      const currentStage = this.stagename_alias.trim();

      // Check if current stage requires validation
      if (environment.validateOutFileStages.includes(currentStage)) {
        const res = await this.workareaservice
          .ValidateOutFileExist(
            this.jobid,
            this.tranid,
            currentStage,
            this.projectdefnitionid,
            this.lottitle
          )
          .toPromise();

        console.log('Validation Response:', res);

        if (res.result === true) {
          this.filevalidate = true;
        } else {
          this.filevalidate = false;
          this.toastr.error('Kindly upload out files and complete the stage.');
          return;
        }

      } else {
        // If stage is not in validation list
        this.filevalidate = true;
      }

    } catch (err) {
      debugger;
      console.error(err);
      this.toastr.error('Error in Getting out file validation');
    }
  }
  completeStage(cFlag, template: TemplateRef<any>) {
    debugger;

    if (this.stagename_alias === "OCR1") {

      if (this.skipid === '') {
        this.toastr.error("Please select a stage to skip");
        return;
      }

      // Check if already uploaded doc/pdf
      if (!this.checkRequiredFiles()) {
        this.toastr.error("Please upload a DOC/DOCX and PDF file");
        return;
      }



      this.saveWorkflowDecision();
    }


    if (this.entity !== null) {
    }
    this.comments_header = 'Comments';
    if (cFlag === 'B') {
      this.buttonType = 'Correction';
    }
    else if (cFlag === 'S') {
      this.buttonType = 'Forward';
    }

    else {
      this.buttonType = 'Complete';
    }
    if (cFlag === 'F' && this.buttonType == 'Complete' && this.stagename_alias != "QA" && this.stagename_alias != "VISF QC and Review" && this.stagename_alias != "Finalization" && this.stagename_alias != "XML SQC" && this.stagename_alias != "XML QC") {
      this.buttonType = 'Ignore';
    }
    if (this.buttonType == "Complete" && this.stagename_alias == "QA") {
      debugger;
      this.workareaservice.getOutfileupdated(this.tranid, "OUT").subscribe(res => {
      });
    }
    if (this.buttonType == "Complete" && this.stagename_alias == "Dispatch") {
      debugger;
      this.workareaservice.sendmailfordispatch(this.jobtitle).subscribe(res => {
        debugger;
      });
    }






    this.comments = this.buttonType + ' Comments';
    this.calltype = 'checkout';
    this.itemData = this.checkoutAppDetails;
    this.cflag = cFlag;
    this.workAreaPopUpModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
    this.ddlLotListTypeSettings = {
      singleSelection: false,
      idField: 'lotid',
      textField: 'title',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true
    };
    this.loadJobDetails();

    //this.getChecklistDetail(this.p_tranid,' '); 
  }

  fileDownload(cid, tranid, filename) {
    this.SpinnerService.show();
    const fileData: any = [];
    fileData.push({
      'cid': cid, 'Transactionid': tranid, 'fileName': filename
    });
    this.workareaservice.DownloadFormFile(fileData[0]).subscribe(res => {
      var content = res.body.file;
      let objectURL = 'data:application/octet-stream;base64,' + res.body.file;
      saveAs(objectURL, filename);
      this.SpinnerService.hide();
    },
      error => {
        this.toastr.error('File not found');
        this.SpinnerService.hide();
      });
  }
  // saveOutputFile() {
  //   let frmdt = new FormData();
  //   let chkbxuploadoutputfile = $('#chkbxuploadoutputfile');
  //   frmdt = new FormData();
  //   let fileUpload = $('#outputFile').get(0);
  //   let files = fileUpload.files;
  //   var lotinfo = {
  //     jobid: this.jobid,
  //     tranid: this.tranid
  //   };
  //   let fileObject = [];
  //   if (files.length > 0) {

  //     for (let i = 0; i < files.length; i++) {
  //       frmdt.append('file', files[i]);
  //     }
  //     frmdt.append('jobid', this.jobid.toString());
  //     frmdt.append('tranid', this.tranid.toString());
  //     frmdt.append('pdid', this.pdid.toString());
  //     this.workareaservice.saveOutputFile(frmdt, this.token).subscribe(res => {
  //       debugger;
  //       console.log(res);
  //       if (res.body !== undefined && res.body !== null) {
  //         $('#outputFile')[0].value = '';
  //         this.toastr.success('Output File Uploaded');
  //         chkbxuploadoutputfile.checked = false;
  //         this.uploadoutputfile = false;
  //         this.getallOutFiles();
  //       } else {
  //         $('#outputFile')[0].value = '';
  //         this.toastr.error('Output File not Uploaded');
  //         chkbxuploadoutputfile.checked = false;
  //         this.uploadoutputfile = false;
  //       }
  //     },
  //       err => {
  //         $('#outputFile')[0].value = '';
  //         //raji
  //         this.toastr.error(err.error.text);
  //         //this.toastr.error(err.toString());
  //         chkbxuploadoutputfile.checked = false;
  //         this.uploadoutputfile = false;
  //       });


  //   }
  // }
  //commented by kiruthiga for outfile validation by raji

  // async saveOutputFile() {
  //   let frmdt = new FormData();
  //   let chkbxuploadoutputfile = $('#chkbxuploadoutputfile');
  //   frmdt = new FormData();
  //   let fileUpload = $('#outputFile').get(0);
  //   let files = fileUpload.files;
  //   var lotinfo = {
  //     jobid: this.jobid,
  //     tranid: this.tranid
  //   };
  //   let fileObject = [];
  //   if (files.length > 0) {
  //       const file = files[0]; // take first file (extend if multiple)
  //       const chunkSize = 5 * 1024 * 1024; // 5 MB
  //       const totalChunks = Math.ceil(file.size / chunkSize);
  //       const fileId = Date.now() + "-" + file.name; // unique ID

  //     for (let index = 0; index < totalChunks; index++) {
  //       const start = index * chunkSize;
  //       const end = Math.min(start + chunkSize, file.size);
  //       const chunk = file.slice(start, end);
  //       let frmdt = new FormData();
  //       frmdt.append("filechunk", chunk, file.name);
  //       frmdt.append("fileId", fileId);
  //       frmdt.append("index", index.toString());
  //       frmdt.append('tranid', this.tranid.toString());

  //       await this.workareaservice.uploadChunk(frmdt, this.token).toPromise();
  //       console.log(`Uploaded chunk ${index + 1}/${totalChunks}`);
  //     }      
  //       //frmdt.append('file', files[0]); 
  //       frmdt.append('filename', file.name);
  //       frmdt.append('totalChunks', totalChunks.toString());
  //       frmdt.append('tranid', this.tranid.toString());
  //       frmdt.append('jobid', this.jobid.toString());
  //       if (this.stagename_alias == "Redaction and Styling") {
  //       this.saveoutfile = true;
  //       frmdt.append('kvpvalue', '_Redacted');
  //       frmdt.append('kvpmode', 'file');
  //       }
  //       else if (this.stagename_alias == "VISF QC and Review" || this.stagename_alias == "QA") {
  //         this.saveoutfile = true;
  //         frmdt.append('kvpvalue', '.visf');
  //         frmdt.append('kvpmode', 'folder');
  //       }
  //       else {
  //         frmdt.append('kvpvalue', '');
  //         frmdt.append('kvpmode', '');
  //         this.saveoutfile = false;
  //         }
  //       // send each chunk

  //     if (this.saveoutfile) {
  //       this.workareaservice.savefilechecker(frmdt, this.token).subscribe(res => {
  //         debugger
  //         if (res.body.dirresult == true && res.body.fileresults==true) {
  //           debugger
  //           frmdt.append('pdid', this.pdid.toString());
  //           this.workareaservice.saveOutputFile(frmdt, this.token).subscribe(res => {
  //             debugger;
  //             console.log(res);
  //             if (res.body !== undefined && res.body !== null) {
  //               $('#outputFile')[0].value = '';
  //               this.toastr.success('Output File Uploaded');
  //               chkbxuploadoutputfile.checked = false;
  //               this.uploadoutputfile = false;
  //               this.getallOutFiles();
  //             } else {
  //               $('#outputFile')[0].value = '';
  //               this.toastr.error('Output File not Uploaded');
  //               chkbxuploadoutputfile.checked = false;
  //               this.uploadoutputfile = false;
  //             }
  //           },
  //             err => {
  //               $('#outputFile')[0].value = '';
  //               this.toastr.error(err.toString());
  //               chkbxuploadoutputfile.checked = false;
  //               this.uploadoutputfile = false;
  //             });
  //         }
  //         else {
  //           $('#outputFile')[0].value = '';
  //           this.toastr.error(res.body.message);
  //           chkbxuploadoutputfile.checked = false;
  //           this.uploadoutputfile = false;
  //         }
  //       },
  //         err => {
  //           $('#outputFile')[0].value = '';
  //           this.toastr.error(err.toString());
  //           chkbxuploadoutputfile.checked = false;
  //           this.uploadoutputfile = false;
  //         });
  //     }
  //     else {
  //       // frmdt.append('jobid', this.jobid.toString());
  //       // frmdt.append('tranid', this.tranid.toString());
  //       frmdt.append('pdid', this.pdid.toString());
  //       this.workareaservice.saveOutputFile(frmdt, this.token).subscribe(res => {
  //         debugger;
  //         console.log(res);
  //         if (res.body !== undefined && res.body !== null) {
  //           $('#outputFile')[0].value = '';
  //           this.toastr.success('Output File Uploaded');
  //           chkbxuploadoutputfile.checked = false;
  //           this.uploadoutputfile = false;
  //           this.getallOutFiles();
  //         } else {
  //           $('#outputFile')[0].value = '';
  //           this.toastr.error('Output File not Uploaded');
  //           chkbxuploadoutputfile.checked = false;
  //           this.uploadoutputfile = false;
  //         }
  //       },
  //         err => {
  //           $('#outputFile')[0].value = '';
  //           this.toastr.error(err.toString());
  //           chkbxuploadoutputfile.checked = false;
  //           this.uploadoutputfile = false;
  //         });
  //     }
  //   }
  // }

  uploadMessage: string = '';
  mismatchedFiles: string[] = [];
  matchedFiles: string[] = [];

  selectedFiles: File[] = [];




  onFileSelected(event: any) {
    debugger
    const files: FileList = event.target.files;

    //  Safety check
    if (!files || files.length === 0) {
      return;
    }

    //  CASE 1: Single NON-ZIP file
    if (files.length === 1 && !files[0].name.toLowerCase().endsWith(".zip")) {

      const file = files[0];

      // Remove extension safely
      const fileNameWithoutExtension = file.name.replace(/\.[^/.]+$/, "");

      if (
        fileNameWithoutExtension.trim().toLowerCase() !==
        this.lottitle.trim().toLowerCase()
      ) {
        this.toastr.error(
          `Selected file name must be exactly "${this.lottitle}"`,
          "Invalid File Name"
        );
        this.clearSelection(event);
        return;
      }

      this.selectedFiles = [file];
      this.toastr.success("File accepted successfully", "Success");
    }

    //  CASE 2: Single ZIP file
    else if (files.length === 1 && files[0].name.toLowerCase().endsWith(".zip")) {

      this.checkZipFiles(files[0], event);
    }

    //  CASE 3: Multiple files
    else {

      if (files.length === this.lotcount) {

        this.selectedFiles = Array.from(files);
        this.toastr.success("Files accepted successfully", "Success");

      } else {

        this.toastr.error(
          `Expected ${this.lotcount} files but selected ${files.length}`,
          "Invalid Selection"
        );

        this.clearSelection(event);
      }
    }
  }


  checkZipFiles(file: File, event: any) {
    debugger;
    const zip = new JSZip();
    zip.loadAsync(file).then((content: any) => {
      let count = 0;
      Object.keys(content.files).forEach(name => {
        if (!content.files[name].dir) count++;
      });

      if (count === this.lotcount) {
        this.selectedFiles = [file];
        this.toastr.success("ZIP file accepted", "Success");
      } else {
        this.toastr.error(`ZIP contains ${count} files, expected ${this.lotcount}`, "Invalid ZIP");
        this.clearSelection(event);
      }
    }).catch(err => {
      this.toastr.error("Failed to read ZIP file", "Error");
    });
  }

  clearSelection(event: any) {
    this.selectedFiles = [];
    event.target.value = "";
  }

  async saveOutputFile() {
    let fileUpload = $('#outputFile').get(0);
    let files = fileUpload.files;

    if (!files || files.length == 0) return;

    if (this.stagename_alias === "OCR1") {
      const fileToCompare = this.lottitle.replace(/-img$/, ""); // remove '-img' only at end

      for (const file of files) {
        const uploadedName = file.name.replace(/\.[^/.]+$/, ""); // remove file extension
        if (uploadedName !== fileToCompare) {
          this.toastr.error(`Uploaded file name must match  - '${fileToCompare}'`);
          return;
        }
      }
    }


    for (let f = 0; f < files.length; f++) {

      const file = files[f];
      this.currentFileName = file.name;
      this.uploadProgress = 0;
      const chunkSize = 5 * 1024 * 1024; // 5 MB
      const totalChunks = Math.ceil(file.size / chunkSize);
      const fileId = Date.now() + "-" + f + "-" + file.name;

      // -------------------------
      //  Upload all chunks
      // -------------------------
      for (let index = 0; index < totalChunks; index++) {
        const start = index * chunkSize;
        const end = Math.min(start + chunkSize, file.size);
        const chunk = file.slice(start, end);

        let chunkForm = new FormData();
        chunkForm.append("filechunk", chunk, file.name);
        chunkForm.append("fileId", fileId);
        chunkForm.append("index", index.toString());
        chunkForm.append("tranid", this.tranid.toString());

        await this.workareaservice.uploadChunk(chunkForm, this.token).toPromise();
        console.log(`Uploaded chunk ${index + 1}/${totalChunks} for ${file.name}`);

        // Update progress
        this.uploadProgress = Math.round(((index + 1) / totalChunks) * 100);

      }

      // -------------------------
      //  After chunks → Save final info / merge
      // -------------------------
      let finalForm = new FormData();
      finalForm.append('filename', file.name);
      finalForm.append('totalChunks', totalChunks.toString());
      finalForm.append('tranid', this.tranid.toString());
      finalForm.append('jobid', this.jobid.toString());
      finalForm.append('pdid', this.pdid.toString());
      finalForm.append('fileId', fileId);
      finalForm.append('currentstagename', this.stagename_alias);
      finalForm.append('files', fileUpload.files[0]);
      // Set flags based on stage
      if (this.stagename_alias == "Redaction and Styling") {
        finalForm.append('kvpvalue', '_Redacted');
        finalForm.append('kvpmode', 'file');
      }
      else if (this.stagename_alias == "VISF QC and Review" || this.stagename_alias == "QA") {
        finalForm.append('kvpvalue', '.visf');
        finalForm.append('kvpmode', 'folder');
      }
      else {
        finalForm.append('kvpvalue', '');
        finalForm.append('kvpmode', '');
      }

      // -------------------------
      //  Call server merge/save endpoint
      // -------------------------
      try {
        const res = await this.workareaservice.saveOutputFile(finalForm, this.token).toPromise();
        if (res.body !== undefined && res.body !== null) {
          // After file uploaded success
          const ext = file.name.split('.').pop();
          this.uploadedFiles.push({
            name: file.name,
            type: ext ? ext.toLowerCase() : ''
          });



          this.toastr.success(`File Uploaded: ${file.name}`);
        } else {
          this.toastr.error(`Failed to Upload ${file.name}`);
        }
      } catch (error) {
        this.toastr.error(`Error uploading ${file.name}`);
      }
      // Reset after each file
      this.uploadProgress = -1;
      this.currentFileName = '';
    }


    $('#outputFile')[0].value = '';
    this.getallOutFiles();
  }

  checkRequiredFiles(): boolean {
    const hasDocOrDocx = this.uploadedFiles.some(file => {
      const ext = file.name.split('.').pop().toLowerCase();
      return ext === "doc" || ext === "docx";
    });

    const hasPdf = this.uploadedFiles.some(file => {
      const ext = file.name.split('.').pop().toLowerCase();
      return ext === "pdf";
    });

    return hasDocOrDocx && hasPdf;
  }


  /*saveOutputFile() {
    let frmdt = new FormData();
    let chkbxuploadoutputfile = $('#chkbxuploadoutputfile');
    frmdt = new FormData();
    let fileUpload = $('#outputFile').get(0);
    let files = fileUpload.files;
    var lotinfo = {
      jobid: this.jobid,
      tranid: this.tranid
    };
    let fileObject = [];
    if (files.length > 0) {
      for (let i = 0; i < files.length; i++) {
        frmdt.append('file', files[i]);
      }
      frmdt.append('jobid', this.jobid.toString());
      frmdt.append('tranid', this.tranid.toString());
      if (this.stagename_alias == "Redaction and Styling") {
        this.saveoutfile = true;
        frmdt.append('kvpvalue', '_Redacted');
        frmdt.append('kvpmode', 'file');
      }
      else if (this.stagename_alias == "VISF QC and Review" || this.stagename_alias == "QA") {
        this.saveoutfile = true;
        frmdt.append('kvpvalue', '.visf');
        frmdt.append('kvpmode', 'folder');
      }
      else {
        frmdt.append('kvpvalue', '');
        frmdt.append('kvpmode', '');
        this.saveoutfile = false;
      }
      if (this.saveoutfile) {
        this.workareaservice.savefilechecker(frmdt, this.token).subscribe(res => {
          debugger
          if (res.body.dirresult == true && res.body.fileresults==true) {
            debugger
            frmdt.append('pdid', this.pdid.toString());
            this.workareaservice.saveOutputFile(frmdt, this.token).subscribe(res => {
              debugger;
              console.log(res);
              if (res.body !== undefined && res.body !== null) {
                $('#outputFile')[0].value = '';
                this.toastr.success('Output File Uploaded');
                chkbxuploadoutputfile.checked = false;
                this.uploadoutputfile = false;
                this.getallOutFiles();
              } else {
                $('#outputFile')[0].value = '';
                this.toastr.error('Output File not Uploaded');
                chkbxuploadoutputfile.checked = false;
                this.uploadoutputfile = false;
              }
            },
              err => {
                $('#outputFile')[0].value = '';
                this.toastr.error(err.toString());
                chkbxuploadoutputfile.checked = false;
                this.uploadoutputfile = false;
              });
          }
          else {
            $('#outputFile')[0].value = '';
            this.toastr.error(res.body.message);
            chkbxuploadoutputfile.checked = false;
            this.uploadoutputfile = false;
          }
        },
          err => {
            $('#outputFile')[0].value = '';
            this.toastr.error(err.toString());
            chkbxuploadoutputfile.checked = false;
            this.uploadoutputfile = false;
          });
      }
      else {
        // frmdt.append('jobid', this.jobid.toString());
        // frmdt.append('tranid', this.tranid.toString());
        frmdt.append('pdid', this.pdid.toString());
        this.workareaservice.saveOutputFile(frmdt, this.token).subscribe(res => {
          debugger;
          console.log(res);
          if (res.body !== undefined && res.body !== null) {
            $('#outputFile')[0].value = '';
            this.toastr.success('Output File Uploaded');
            chkbxuploadoutputfile.checked = false;
            this.uploadoutputfile = false;
            this.getallOutFiles();
          } else {
            $('#outputFile')[0].value = '';
            this.toastr.error('Output File not Uploaded');
            chkbxuploadoutputfile.checked = false;
            this.uploadoutputfile = false;
          }
        },
          err => {
            $('#outputFile')[0].value = '';
            this.toastr.error(err.toString());
            chkbxuploadoutputfile.checked = false;
            this.uploadoutputfile = false;
          });
      }
    }
  }*/

  getallOutFiles() {
    this.workareaservice.GetAllOutFilesForDownload(this.jobid, this.tranid).subscribe(res => {
      if (res !== undefined && res !== null) {
        this.FileOutList = res;
      }
    });
  }

  getocrpdffile() {
    debugger;
    this.workareaservice.getocrpdffile(this.jobid, this.lotid).subscribe(res => {
      if (res !== undefined && res !== null) {
        this.FileOutList = res;
      }
    });

  }



  GetInOutFiles() {
    this.workareaservice.GetAllFilesForDownload(this.jobid, this.tranid).subscribe(res => {
      debugger;
      if (res !== undefined && res !== null) {
        this.xFileInList = res;
        console.log(this.xFileInList);
      } else {
        this.xFileInList = [];
      }
    });
    this.workareaservice.GetAllOutputFiles(this.jobid, this.tranid).subscribe(res => {
      if (res !== undefined && res !== null) {
        debugger;
        this.xFileOutList = res;
        console.log(this.xFileOutList);
      } else {
        this.xFileOutList = [];
      }
    });
  }
  downloadIndividualFiles(type, filepath, filename) {
    let fileData: any = [];
    fileData.push({
      'type': type, 'path': filepath, 'jobid': +this.jobid
    });
    this.workareaservice.DownloadSingleFile(fileData[0]).subscribe(res => {
      var content = res.body.file;
      let objectURL = 'data:application/octet-stream;base64,' + res.body.file;
      saveAs(objectURL, filename);
      //this.SpinnerService.hide();
    },
      error => {
        this.toastr.error('File not found');
        //this.SpinnerService.hide();
      });
  }
  downloadInOutFiles(type, tranid, option) {
    debugger;

    let fileData: any = [];
    fileData.push({
      'jobid': this.jobid, 'tranid': this.tranid, 'pdid': this.pdid, 'option': option, 'jobtitle': this.jobtitle
    });
    this.workareaservice.DownloadInOutFiles(fileData[0]).subscribe((blob: Blob) => {
      debugger;

      const a = document.createElement('a');
      const objectUrl = URL.createObjectURL(blob);
      a.href = objectUrl;
      a.download = this.jobtitle + '.zip'; // 👈 desired name
      a.click();
      URL.revokeObjectURL(objectUrl);

    });
  }





  downloadIndividualOutFiles(type, filepath, filename) {
    let fileData: any = [];
    fileData.push({
      'type': type, 'path': filepath, 'jobid': this.jobid
    });
    this.workareaservice.DownloadSingleOutFile(fileData[0])
      .subscribe(res => {
        var content = res.body.file;
        let objectURL = 'data:application/octet-stream;base64,' + res.body.file;
        saveAs(objectURL, filename);
        // this.SpinnerService.hide();
      },
        error => {
          this.toastr.error('File not found');
          // this.SpinnerService.hide();
        });
  }
  RemovingIOFiles(filepath) {
    let fileData: any = [];
    fileData.push({
      'path': filepath, 'jobid': this.jobid
    });
    this.workareaservice.RemoveIOFiles(fileData[0]).subscribe(res => {
      if (res.body !== undefined && res.body !== null) {
        if (res.body.result === true) {
          this.toastr.success('File removed sucessfully');
          this.GetInOutFiles();
          this.getallOutFiles();
        }
        else {
          this.toastr.error('File not removed');
        }
      }
    }, err => { console.log(err); });
  }


  selectTab(type) {
    if (type === 'infiles') {
      this.infilesactive = true;
      this.outfilesactive = false;

    }
    if (type === 'outfiles') {
      this.infilesactive = false;
      this.outfilesactive = true;

    }
  }
  resetRadio = function (val, ind, eve: any) {
    this.checklistLstQry[ind].yes = false;
    this.checklistLstQry[ind].na = false;
    this.checklistLstQry[ind].no = false;
    if (eve.currentTarget.value === 'YES') {
      this.checklistLstQry[ind].yes = true;
    } else if (eve.currentTarget.value === 'NA') {
      this.checklistLstQry[ind].na = true;
    } else {
      this.checklistLstQry[ind].no = true;
    }
    this.checklistLstQry[ind].tranid = this.p_tranid;
    // console.log(this.checklistLstQry);
  };

  getChecklistDetail(trnid, checklisttitle: string) {
    // var trnid = this.p_tranid;  // new
    this.workareaservice.getchecklisttransaction(trnid, this.token).subscribe(res => {
      if (res !== undefined && res !== null && res.length > 0) {
        if (checklisttitle !== 'Checklist filled in the previous stage') {
          this.checklistLstview = []; // new
          this.checklistLstQry = [];
          this.checklistLstQry = JSON.parse(res[0]);
          // console.log(this.checklistLstQry);
          this.checklistLstQry.forEach((element) => {
            if (element.yes === true || element.na === true || element.no === true) {
              if (element.yes === true) {
                element.mystatus_checked = 'YES';
              } if (element.na === true) {
                element.mystatus_checked = 'NA';
              } if (element.no === true) {
                element.mystatus_checked = 'NO';
              }
            }
          });
          // console.log(this.checklistLstQry);
        } else {
          this.checklistLstQry = []; // new
          this.checklistLstview = [];
          this.checklistLstview = JSON.parse(res[0]);
          // console.log(this.checklistLstview);
          this.checklistLstview.forEach((element) => {
            if (element.yes === true || element.na === true || element.no === true) {
              if (element.yes === true) {
                element.mystatus_checked = 'YES';
              } if (element.na === true) {
                element.mystatus_checked = 'NA';
              } if (element.no === true) {
                element.mystatus_checked = 'NO';
              }
            }
          });
          // console.log(this.checklistLstview);
        }
      }
    });
  }
  fillChecklist(template: TemplateRef<any>) {
    /*  this.workareaservice.getchecklisttransaction(this.p_tranid, this.token).subscribe(res => {
       if (res !== undefined && res !== null) {
         if (res.length > 0) {
           this.checklist_title = 'Checklist to be filled';
           this.getChecklistDetail(this.p_tranid, this.checklist_title) ;
           this.checkListPopupMOdalRef = this.modalService.show(template, this.config);
         } else {
           this.add();
         }
       } else {
         this.add();
       }
     }); */
    this.add();
  }
  saveChecklist() {
    let validate = true;
    var rownumber = '';
    // let index = 0;
    this.checklistLstQry.forEach((element, index) => {
      element.createdby = this.loginuserid.toString();
      if ((element.yes === false || element.yes === '') && (element.na === false || element.na === '')) {
        var comma = '';
        if (rownumber !== '') {
          comma = ',';
        }
        rownumber = rownumber + comma + (index + 1);
        validate = false;
        // index++;
      }
    });

    if (validate === true) {
      this.workareaservice.PostInsertchecklist(this.checklistLstQry, this.token).subscribe(res => {
        if (res !== undefined && res !== null) {
          if (res.body > 0) {
            this.add();
            // this.toastr.success('CheckList Saved successfully.', this.toastr.toastrConfig.positionClass = 'toast-top-right');
            this.checkListPopupMOdalRef.hide();
          }
        }
      });
    } else {
      this.toastr.error('Select the status for the checklist in the row' + rownumber);
    }
  }

  download(path: string) {
    debugger;
    this.loading = true;
    this.SpinnerService.show();
    this.workareaservice.downloadFile(path, this.jobtitle, this.jobid.toString()).subscribe((blob: Blob) => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = this.jobtitle + '.zip';
      a.click();
      window.URL.revokeObjectURL(url);
      this.loading = false;
      this.SpinnerService.hide();
    },
      err => {
        console.error(err);
        this.loading = false;
        this.SpinnerService.hide();

      });
  }
  getPreviousStageTranid(template: TemplateRef<any>) {
    this.workareaservice.getPreviousStageTranid(this.p_tranid, this.token).subscribe(res => {
      if (res !== undefined && res !== null) {
        if (res > 0) {
          this.checklist_title = 'Checklist filled in the previous stage';
          // this.p_tranid = res;
          this.p_prevtranid = res; // new
          this.getChecklistDetail(this.p_prevtranid, this.checklist_title);
          this.checkListPopupMOdalRef = this.modalService.show(template, this.config);
        }
      }
    });
  }

  getOutfileExtension() {
    this.workareaservice.getOutfileExtension(this.tranid).subscribe(res => {
      if (res !== undefined && res !== null) {
        console.log(res);
        this.OutfileExtension = '';
        res.forEach((i) => {
          this.OutfileExtension = this.OutfileExtension + i + ',';
        });
        this.OutfileExtension = this.OutfileExtension.slice(0, this.OutfileExtension.length - 1);
        this.Outfiletypes = this.OutfileExtension;
        this.OutfileExtension = 'Select folder contains these files : ' + this.OutfileExtension;
      }
    });
  }
  previousstageChecklistdts() {
    var checklist_exists = false;
    this.workareaservice.getPreviousStageTranid(this.p_tranid, this.token).subscribe(res => {
      if (res !== undefined && res !== null) {
        if (res > 0) {
          var trnid = res;
          this.workareaservice.getchecklisttransaction(trnid, this.token).subscribe(data => {
            if (data !== undefined && data !== null && data.length > 0) {
              this.checklistbuttonhide = [];
              this.checklistbuttonhide = JSON.parse(data[0]);

              this.checklistbuttonhide.forEach((element, index) => {
                if (element.yes !== '' || element.na !== '' || element.no !== '') {
                  checklist_exists = true;
                }
              });
              if (!checklist_exists) {
                this.checklistbuttonhide = [];
              }
            }

          });
        }
      }
    });
  }

  getredatoutfile() {
    debugger;
    console.error('Error occurred:', this.p_tranid);
    this.workareaservice.getredatOutfile(this.p_tranid).subscribe(res => {
      if (res.exists === true) {
        this.alertvisible = true;
        this.aModalRef = this.modalService.show(this.alerttemplate_, this.config);  // Show the modal
        const aa = document.getElementsByClassName('modal-content');
        aa[0].classList.remove('modal-content');
      } else {
        // handle case when res.exists is false
        this.alertvisible = false;
      }
    });
  }


  // Close the modal
  closeModal() {
    this.aModalRef.hide();
  }


  //load comments 
  openchaperdetail(template: TemplateRef<any>, lotId) {
    this.comments = 'View Comments';
    this.comments_header = 'View Comments';
    this.buttonType = 'View';
    this.calltype = 'View';
    this.itemData = this.checkoutAppDetails;
    this.workAreaPopUpModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
    this.ddlLotListTypeSettings = {
      singleSelection: false,
      idField: 'lotid',
      textField: 'title',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      itemsShowLimit: 7,
      allowSearchFilter: true
    };
    this.loadJobDetails();
  }

  openPushbackPopup() {
  $('#pushbackModal').modal('show');
}
  pushBack() {

    debugger;
    const formData = new FormData();

    formData.append('jobid', String(this.jobid));
    formData.append('lotid', String(this.lotid));
    formData.append('tranid', String(this.tranid));
    formData.append('lottitle', String(this.lottitle));

    this.workareaservice.pushBack(formData, this.token).subscribe(
      (res: any) => {
        debugger;
  const newTranId =res.body.out_transactionid;
  const jobWorkflowId = res.body.out_jobworkflowid;
      console.log(newTranId);
    console.log(jobWorkflowId);

       
        const fields = {
          transid: newTranId,

          cflag: this.cflag = 'A',
          userid: this.loginuserid,
        fields:'null',
        option:"checkout"
        };

        const updateFormData = new FormData();
        updateFormData.append('model', JSON.stringify(fields));
        updateFormData.append('tostage', jobWorkflowId);
        updateFormData.append('jobid',  String(this.jobid));
        updateFormData.append('comment', '');
        updateFormData.append('lotid', String(this.lotid));
        updateFormData.append('batchid', '');
        updateFormData.append('extravalues', '');
        updateFormData.append('isnochange', '');
        updateFormData.append('Status', '');
        updateFormData.append('querytype', '');

        debugger;
        this.workareaservice.PostUpdateLotTransaction(updateFormData, this.token)
          .subscribe(
          
            (updateRes: any) => {
              debugger;
              console.log("Update Success", updateRes.body);
              top.location.href = this.serverappUrl + '/dashboard';
            },
            (updateErr) => {
              debugger;
              console.error("Update Error", updateErr);
              top.location.href = this.serverappUrl + '/dashboard';
            }
          );

      },
      (err) => {
        debugger;
        console.error("PushBack Error", err);
        top.location.href = this.serverappUrl + '/dashboard';
      }
    );
  }
  savestage() {
    debugger;
    if (this.isProcessing) {
      debugger;
      console.log('Click ignored: Request already in progress.');
      return;
    }
    const params = new HttpParams()
      .set('transactionId', this.tranid.toString())
      .set('userId', this.loginuserid.toString())
      .set('env', this.enviroment)
      .set('action', 'open');

    const url = `http://localhost:60024/`;
    this.isProcessing = true;
    this.http.get<any>(url, { params })
      .pipe(take(1))
      .subscribe(

        response => {
          debugger;
          if (this.stagename_alias == "Redaction and Styling") {
            debugger;
            this.getredatoutfile();
          }

          console.log('Tool opened successfully:', response);
          this.isProcessing = false; // Re-enable after success
        },
        error => {
          debugger;
          console.error('Error occurred:', error);
          this.isProcessing = false; // Re-enable after failure
        }
      );
  }


  skiplot(item1) {
    debugger;


    const jobObject = new Object({
      p_tranid: item1.transactionid.toString(),
      p_lotid: item1.lotid.toString(),
      p_jobid: this.jobid,
      p_jobworkflowid: item1.jobworkflowid.toString(),
      fromorder: item1.stageorder.toString(),
      p_lotstatus: 'D',
      p_option: 'fail',
      p_userid: item1.userid == null || item1.userid == '' || item1.userid == undefined ? this.userid.toString() : item1.userid.toString(),
      p_holdreason: '0',
      p_transactiontimer: ''

    });









  }

  saveWorkflowDecision() {
    const inputData = [];
    inputData.push({
      transactionid: this.tranid,
      lotid: this.lotid,
      jobid: this.jobid,
      skipid: this.skipid,
      active: true
    })
    this.workareaservice.saveWorkflowDecision(inputData[0]).subscribe(res => {
      if (res.body[0] !== undefined && res.body[0] !== null && JSON.parse(res.body[0]).length > 0) {
      }
    }, err => { this.toastr.error('Failed to save workflow decision'); });
  }
}

