import { Component, OnInit, Input, OnChanges, ViewChild, TemplateRef } from '@angular/core';
import { DashboardService } from '../dashboard.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { BsModalService, BsModalRef, ModalOptions } from 'ngx-bootstrap';
import { ToastrService } from 'ngx-toastr';
import { DialogService } from 'ng2-bootstrap-modal';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { NgxSpinnerService } from 'ngx-spinner';
import { NgxPaginationModule } from 'ngx-pagination';
import { JobmasterService } from 'src/app/jobconfiguration/jobmaster/jobmaster.service';
import {MatPaginatorModule} from '@angular/material/paginator';
@Component({
  selector: 'app-jobstatusreport',
  templateUrl: './jobstatusreport.component.html',
  styleUrls: ['./jobstatusreport.component.css']
})
export class JobstatusreportComponent implements OnInit, OnChanges, ViewChild {
  @Input() jobid: number;
  @Input() jobstatus: boolean;
  @Input() supplementlotids: any = [];
  // @Input() isbn: string;
  @Input() swapeboardval: number;
  @Input() userid: number;
  @Input() admin_rights: boolean;
  AssignedLotLoading_3 = true;
  uniqueStagename = [];
  uniqueFilename = [];
  uniqueFilename_st: any;
  uniqueStagename_st = [];
  jsonObj = [];
  jsonObj_st = [];
  uniqueStagename_st_temp: any;
  dtitle = 'Title';
  stageconfigForm: FormGroup;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered modal-lg',
    ignoreBackdropClick: true
  };
  reAllocateModalRef: BsModalRef;
  uniqueStageTitles: any;
  allocatetype: string;
  stagename: string;
  lottitle: string;
  assignee: string;
  backstage: any;
  forwardstage: any;
  selforward: string;
  selback: string;
  stype: string;
  stoorder: number;
  fromOrder: number;
  tranid: number;
  show = true;
  stagenamelist= [];
  p: number = 1; // Current page number
  itemsPerPage: number = 10; // Number of items to display per page
  itemsPerPageOptions: number[] = [5,10, 25, 50, 100]; // Options for the "Show Entries" dropdown
  total=0;
  constructor(
    private dashboardservice: DashboardService,
    private formBuilder: FormBuilder,
    private modalService: BsModalService,
    private toastr: ToastrService,
    private dialogService: DialogService,
    private SpinnerService: NgxSpinnerService,
    private jobmasterservice: JobmasterService,
  ) { }
  descendants: boolean;
  first: boolean;
  read: any;
  isViewQuery: boolean;
  selector: any;
  static: boolean;
  ngOnChanges(changes: import('@angular/core').SimpleChanges): void {
    this.loadlottotalcount();
    this.loadstagedetails();
  }

  ngOnInit() {
    this.loadlottotalcount();
    // this.dtitle = 'Process';
    this.loadstagedetails();
  }
  onItemsPerPageChange(evt) {
    // Reset the page number when the items per page changes
    this.p = evt;
    //console.log(evt)
    //this.p = evt.pageIndex+1;
    //this.itemsPerPage= evt.pageSize;
    this.loadlottotalcount();
    this.loadstagedetails();
  }
  onShowEntriesChange(){
    this.loadlottotalcount();
    this.loadstagedetails();
  }
  loadlottotalcount(){
    const job = new Object({
      jobid: this.jobid
    });
    this.jobmasterservice.getLotByJobId(job).subscribe(lotres => {
      const lotress = JSON.parse(lotres.body[0]);
      var lotlist=[];
      lotress.forEach(val => {
       // if(val.lotstatus !='C'){
          lotlist.push(val);
       // }
      });
      //console.log(lotlist.length);
      this.total=lotlist.length;
    });
    
      }
  loadstagedetails() {
    debugger;
    this.SpinnerService.show();
    this.AssignedLotLoading_3 = false;
    this.show = true;
    const inputvalue = [];
    this.dtitle = '';
    let page =Number(this.itemsPerPage);
    //inputvalue.push({ p_jobid: this.jobid, p_jobstatus: this.jobstatus });
    if(this.admin_rights == true){
      if(this.userid == null&&this.userid == undefined){
       inputvalue.push({ p_jobid: Number(this.jobid), p_jobstatus: this.jobstatus,p_userid:null ,p_pagenumber :this.p
        ,p_pagesize:page,mode:'Withpagination' });
      /* inputvalue.push({ p_jobid: Number(this.jobid), p_jobstatus: this.jobstatus,p_userid:null });*/
      }else{
       inputvalue.push({ p_jobid: Number(this.jobid), p_jobstatus: this.jobstatus,p_userid:Number(this.userid),p_pagenumber :this.p,
          p_pagesize:page ,mode:'Withpagination' });
        /* inputvalue.push({ p_jobid: Number(this.jobid), p_jobstatus: this.jobstatus,p_userid:Number(this.userid)});*/
      }
    }else{
     inputvalue.push({ p_jobid: Number(this.jobid), p_jobstatus: this.jobstatus, p_userid:Number(localStorage.getItem('userid')),p_pagenumber :this.p,
      p_pagesize:page,mode:'Withpagination'  });
       /*inputvalue.push({ p_jobid: Number(this.jobid), p_jobstatus: this.jobstatus, p_userid:Number(localStorage.getItem('userid'))});*/
    }
    this.dashboardservice.loadStageDetails(inputvalue[0]).subscribe(res => {
      if (res !== undefined && res !== null && res.body !== undefined && res.body !== null) {
       // if (JSON.parse(res.body[0]).length > 0) {
       // const resData = JSON.parse(res.body[0]);
       debugger;
        if (res.body.length > 0) {
          const resData = res.body;
          console.log('tas'+JSON.stringify(res.body))
          this.uniqueStagename = [];
          this.uniqueFilename = [];
          this.uniqueStagename_st = [];
          resData.forEach(j => {
            if (this.uniqueStagename.indexOf(j.stagename_alias) === -1) {
             this.uniqueStagename.push(j.stagename_alias);
             //j.stage_type !=2 &&
             //if(this.stagenamelist.indexOf(j.stagename_alias) === -1)this.stagenamelist.push(j.stagename_alias);
            }
            if (this.uniqueFilename.indexOf(j.lottitle) === -1) {
              this.uniqueFilename.push(j.lottitle);
            }
          });
          this.jsonObj = [];

          let cmt_st :any;
          let comments_status = [];
          let coutn=0;
         /*  if (this.swapeboardval === 1) {
            this.uniqueFilename.forEach(k => {
              const filestatus = resData.filter(n => n.lottitle === k);
              const item = {};
              item['stagename'] = k;
              item['files'] = filestatus;
              this.jsonObj.push(item);
            });
            this.uniqueStagename_st = this.uniqueStagename;
            this.uniqueFilename_st = this.uniqueFilename;
          }
          if (this.swapeboardval === 2) {
            this.uniqueStagename.forEach(k => {
              const filestatus = resData.filter(n => n.stagename_alias === k);
              const item = {};
              item['stagename'] = k;
              item['files'] = filestatus;
              this.jsonObj.push(item);
            });
            this.uniqueStagename_st = this.uniqueFilename;
            this.uniqueFilename_st = this.uniqueStagename;
          } */
          if (this.swapeboardval === 1) {
            this.uniqueFilename.forEach(k => {
              debugger;
              const filestatus = resData.filter(n => n.lottitle === k);
              const item = {};
              let commentlst =[];
              let temp_com={};
              let comment_view = false;
              let fin = 0;
              filestatus.forEach(element => {
                if(element.lotstatus != 'F'){
                  fin =fin+1;
                }
              });
              filestatus.forEach(comments => {
                debugger;
                coutn = coutn +1;
                 
                  if(comments.stagename_alias === this.uniqueStagename[fin - 1]){
                    temp_com={
                      comments:comments.comments,
                      stagename_alias:comments.stagename_alias,
                      lotstatus:comments.lotstatus,
                      lotmasterstatus:comments.lotmasterstatus,
                      stageorder:comments.stageorder,
                      tostage: comments.tostage,
                      comments_status: comments.lotmasterstatus
                    }
                  }else{
                     temp_com={
                      comments:comments.comments,
                      stagename_alias:comments.stagename_alias,
                      lotstatus:comments.lotstatus,
                      lotmasterstatus:comments.lotmasterstatus,
                      stageorder:comments.stageorder,
                      tostage: comments.tostage,
                      comments_status: 'Completed'
                    }
                  }
              //if(comments.comments != '' && comments.comments != null && comments.comments != undefined && comments.lotstatus == 'C'){
                if(comments.comments != '' && comments.comments != null && comments.comments != undefined && (comments.lotstatus == 'C' || comments.lotstatus == 'R' || comments.lotstatus == 'B' || comments.lotstatus == 'F') ){ 
              comment_view = true;
              }
              cmt_st ={
                    stagename: k,
                    comments_status: comment_view,
                    lotmasterstatus: comments.lotmasterstatus
                  }
                comments_status.push(cmt_st);              
                commentlst.push(temp_com);
              });
              item['stagename'] =cmt_st;
              item['files'] = filestatus;
              item['comments'] = commentlst;
              this.jsonObj.push(item);
              commentlst =[];
              comments_status =[]
            });
           this.uniqueStagename_st = this.uniqueStagename;
           //this.uniqueStagename_st = stagenamelist;
            this.uniqueFilename_st = this.uniqueFilename;
          }
          if (this.swapeboardval === 2) {
           
            this.uniqueFilename.forEach(k => {
              debugger;
              const filestatus = resData.filter(n => n.lottitle === k);
              const item = {};
              let commentlst =[];
              let temp_com={};
              let comment_view = false;
              let fin = 0;
              filestatus.forEach(element => {
                if(element.lotstatus != 'F'){
                  fin =fin+1;
                }
              });
              filestatus.forEach(comments => {
                debugger;
                coutn = coutn +1;
                 
                  if(comments.stagename_alias === this.uniqueStagename[fin - 1]){
                    temp_com={
                      comments:comments.comments,
                      stagename_alias:comments.stagename_alias,
                      lotstatus:comments.lotstatus,
                      lotmasterstatus:comments.lotmasterstatus,
                      stageorder:comments.stageorder,
                      tostage: comments.tostage,
                      comments_status: comments.lotmasterstatus
                    }
                  }else{
                     temp_com={
                      comments:comments.comments,
                      stagename_alias:comments.stagename_alias,
                      lotstatus:comments.lotstatus,
                      lotmasterstatus:comments.lotmasterstatus,
                      stageorder:comments.stageorder,
                      tostage: comments.tostage,
                      comments_status: 'Completed'
                    }
                  }
              if(comments.comments != '' && comments.comments != null && comments.comments != undefined && comments.lotstatus == 'C'){
               comment_view = true;
              }
              cmt_st ={
                    stagename: k,
                    comments_status: comment_view,
                    lotmasterstatus: comments.lotmasterstatus
                  }
                comments_status.push(cmt_st);
                commentlst.push(temp_com);
              });
              item['stagename'] =cmt_st;
              item['files'] = filestatus;
              item['comments'] = commentlst;
              this.jsonObj.push(item);
              commentlst =[];
              comments_status =[]
            });
            this.uniqueStagename_st = this.uniqueStagename;
            this.uniqueFilename_st = this.uniqueFilename;
          }
          this.jsonObj_st = [];
          this.jsonObj_st = this.jsonObj;
          if( this.jsonObj_st[0].stagename == undefined){
            this.AssignedLotLoading_3 = true;
            this.show = false;
          }
          // if (this.supplementlotids.length) {
          //   // Array of array filter
          //   this.jsonObj_st = this.jsonObj_st.filter(role =>
          //     role.files.find(
          //       group =>
          //       this.supplementlotids.includes(group.lotid)));
          //   console.log(this.jsonObj_st);
          // }
          this.SpinnerService.hide();
          for (let i = 0; i < this.jsonObj_st.length; i++) {
            for (let j = 0; j < this.jsonObj_st[i].files.length; j++) {
              if (this.jsonObj_st[i].files[j].lotstatus === 'P') {
                this.jsonObj_st[i].files[j].livestatus = '';
                //  this.jsonObj_st[i].files[j].livestatus = //this.searchDic(this.jsonObj_st[i].files[j].transactionid,
                // this.jsonObj_st[i].files[j].userid);
              } else {
                this.jsonObj_st[i].files[j].livestatus = 'false';
              }
            }
          }
          const data = this.jsonObj_st.filter(i => i.files[0].merged_lot === 1);
          let mergeddetails: any;
          if (data.length > 0 && data[0].files !== undefined && data[0].files !== null) {
            mergeddetails = data[0].files;
          } else {
            mergeddetails = [];
          }
          let previousstage = 0;
          mergeddetails.forEach((i, ind) => {
            const currentstage = mergeddetails[ind].stageorder === null ? 0 : mergeddetails[ind].stageorder;
            if (mergeddetails[ind].lotstatus !== 'C') {
              this.jsonObj_st.forEach((j, index) => {
                console.log(j);
                const result = j.files.filter(word => word.stageorder !== null &&
                  word.stageorder < currentstage && word.stageorder >
                  previousstage && word.islotenable != null);
                
                if (result.length > 0) { 
                  if(result[index] !== undefined){
                 
                  result[index].isready_yts = currentstage;
                  }
                 }
              });
            }
            previousstage = mergeddetails[ind].stageorder;
          });
          if (this.swapeboardval === 1) {
            this.uniqueStagename_st_temp = this.uniqueStagename_st;
            this.dtitle = 'Title';
          } else {
            this.uniqueStagename_st_temp = this.uniqueFilename_st;
            this.dtitle = 'Process';
            // this.stageconfigForm.controls.set='process';
          }
          console.log('load job list',this.jsonObj_st)
        }
      } else {
        this.dtitle = '';
        this.jsonObj_st = [];
        this.uniqueStagename = [];
        this.uniqueFilename = [];
        this.uniqueStagename_st = [];
        this.AssignedLotLoading_3 = true;
      }
    });
    this.SpinnerService.hide();
  }
  // loadstagedetails() {
  //   this.SpinnerService.show();
  //   this.AssignedLotLoading_3 = false;
  //   const inputvalue = [];
  //   this.dtitle = '';
  //   inputvalue.push({ p_jobid: this.jobid, p_jobstatus: this.jobstatus });
  //   this.dashboardservice.loadStageDetails(inputvalue[0]).subscribe(res => {
  //     if (res !== undefined && res !== null && res.body[0] !== undefined && res.body[0] !== null) {
  //       if (JSON.parse(res.body[0]).length > 0) {
  //         const resData = JSON.parse(res.body[0]);
  //         this.uniqueStagename = [];
  //         this.uniqueFilename = [];
  //         this.uniqueStagename_st = [];
  //         resData.forEach(j => {
  //           if (this.uniqueStagename.indexOf(j.stagename_alias) === -1) {
  //             this.uniqueStagename.push(j.stagename_alias);
  //           }
  //           if (this.uniqueFilename.indexOf(j.lottitle) === -1) {
  //             this.uniqueFilename.push(j.lottitle);
  //           }
  //         });
  //         this.jsonObj = [];
  //         if (this.swapeboardval === 1) {
  //           this.uniqueFilename.forEach(k => {
  //             const filestatus = resData.filter(n => n.lottitle === k);
  //             const item = {};
  //             item['stagename'] = k;
  //             item['files'] = filestatus;
  //             this.jsonObj.push(item);
  //           });
  //           this.uniqueStagename_st = this.uniqueStagename;
  //           this.uniqueFilename_st = this.uniqueFilename;
  //         }
  //         if (this.swapeboardval === 2) {
  //           this.uniqueStagename.forEach(k => {
  //             const filestatus = resData.filter(n => n.stagename_alias === k);
  //             const item = {};
  //             item['stagename'] = k;
  //             item['files'] = filestatus;
  //             this.jsonObj.push(item);
  //           });
  //           this.uniqueStagename_st = this.uniqueFilename;
  //           this.uniqueFilename_st = this.uniqueStagename;
  //         }
  //         this.jsonObj_st = [];
  //         this.jsonObj_st = this.jsonObj;
  //         // if (this.supplementlotids.length) {
  //         //   // Array of array filter
  //         //   this.jsonObj_st = this.jsonObj_st.filter(role =>
  //         //     role.files.find(
  //         //       group =>
  //         //       this.supplementlotids.includes(group.lotid)));
  //         //   console.log(this.jsonObj_st);
  //         // }
  //         this.SpinnerService.hide();
  //         for (let i = 0; i < this.jsonObj_st.length; i++) {
  //           for (let j = 0; j < this.jsonObj_st[i].files.length; j++) {
  //             if (this.jsonObj_st[i].files[j].lotstatus === 'P') {
  //               this.jsonObj_st[i].files[j].livestatus = '';
  //               //  this.jsonObj_st[i].files[j].livestatus = //this.searchDic(this.jsonObj_st[i].files[j].transactionid,
  //               // this.jsonObj_st[i].files[j].userid);
  //             } else {
  //               this.jsonObj_st[i].files[j].livestatus = 'false';
  //             }
  //           }
  //         }
  //         const data = this.jsonObj_st.filter(i => i.files[0].merged_lot === 1);
  //         let mergeddetails: any;
  //         if (data.length > 0 && data[0].files !== undefined && data[0].files !== null) {
  //           mergeddetails = data[0].files;
  //         } else {
  //           mergeddetails = [];
  //         }
  //         let previousstage = 0;
  //         mergeddetails.forEach((i, ind) => {
  //           const currentstage = mergeddetails[ind].stageorder === null ? 0 : mergeddetails[ind].stageorder;
  //           if (mergeddetails[ind].lotstatus !== 'C') {
  //             this.jsonObj_st.forEach((j, index) => {
  //               console.log(j);
  //               const result = j.files.filter(word => word.stageorder !== null &&
  //                 word.stageorder < currentstage && word.stageorder >
  //                 previousstage && word.islotenable != null);
                
  //               if (result.length > 0) { 
  //                 if(result[index] !== undefined){
                 
  //                 result[index].isready_yts = currentstage;
  //                 }
  //                }
  //             });
  //           }
  //           previousstage = mergeddetails[ind].stageorder;
  //         });
  //         if (this.swapeboardval === 1) {
  //           this.uniqueStagename_st_temp = this.uniqueStagename_st;
  //           this.dtitle = 'Title';
  //         } else {
  //           this.uniqueStagename_st_temp = this.uniqueFilename_st;
  //           this.dtitle = 'Process';
  //           // this.stageconfigForm.controls.set='process';
  //         }
  //       }
  //     } else {
  //       this.dtitle = '';
  //       this.jsonObj_st = [];
  //       this.uniqueStagename = [];
  //       this.uniqueFilename = [];
  //       this.uniqueStagename_st = [];
  //       this.AssignedLotLoading_3 = true;
  //     }
  //   });
  //   this.SpinnerService.hide();
  // }

  /*loadstagedetails() {

    this.AssignedLotLoading_3 = false;
    const inputvalue = [];
    this.dtitle = '';
    inputvalue.push({ p_jobid: this.jobid, p_jobstatus: this.jobstatus });
    this.dashboardservice.loadStageDetails(inputvalue[0]).subscribe(res => {
      if (res !== undefined && res !== null && res.body[0] !== undefined && res.body[0] !== null) {
        if (JSON.parse(res.body[0]).length > 0) {
          const resData = JSON.parse(res.body[0]);
          this.uniqueStagename = [];
          this.uniqueFilename = [];
          this.uniqueStagename_st = [];
          resData.forEach(j => {
            if (this.uniqueStagename.indexOf(j.stagename_alias) === -1) {
              this.uniqueStagename.push(j.stagename_alias);
            }
            if (this.uniqueFilename.indexOf(j.lottitle) === -1) {
              this.uniqueFilename.push(j.lottitle);
            }
          });
          this.jsonObj = [];
          if (this.swapeboardval === 1) {
            this.uniqueFilename.forEach(k => {
              const filestatus = resData.filter(n => n.lottitle === k);
              const item = {};
              item['stagename'] = k;
              item['files'] = filestatus;
              this.jsonObj.push(item);
            });
            this.uniqueStagename_st = this.uniqueStagename;
            this.uniqueFilename_st = this.uniqueFilename;
          }
          if (this.swapeboardval === 2) {
            this.uniqueStagename.forEach(k => {
              const filestatus = resData.filter(n => n.stagename_alias === k);
              const item = {};
              item['stagename'] = k;
              item['files'] = filestatus;
              this.jsonObj.push(item);
            });
            this.uniqueStagename_st = this.uniqueFilename;
            this.uniqueFilename_st = this.uniqueStagename;
          }
          this.jsonObj_st = [];
          this.jsonObj_st = this.jsonObj;
          for (let i = 0; i < this.jsonObj_st.length; i++) {
            for (let j = 0; j < this.jsonObj_st[i].files.length; j++) {
              if (this.jsonObj_st[i].files[j].lotstatus === 'P') {
                this.jsonObj_st[i].files[j].livestatus = '';
                //  this.jsonObj_st[i].files[j].livestatus = //this.searchDic(this.jsonObj_st[i].files[j].transactionid,
                // this.jsonObj_st[i].files[j].userid);
              } else {
                this.jsonObj_st[i].files[j].livestatus = 'false';
              }
            }
          }
          const data = this.jsonObj_st.filter(i => i.files[0].merged_lot === 1);
          let mergeddetails: any;
          if (data.length > 0 && data[0].files !== undefined && data[0].files !== null) {
            mergeddetails = data[0].files;
          } else {
            mergeddetails = [];
          }
          let previousstage = 0;
          mergeddetails.forEach((i, ind) => {
            const currentstage = mergeddetails[ind].stageorder === null ? 0 : mergeddetails[ind].stageorder;
            if (mergeddetails[ind].lotstatus !== 'C') {
              this.jsonObj_st.forEach((j, index) => {
                console.log(j);
                const result = j.files.filter(word => word.stageorder !== null &&
                  word.stageorder < currentstage && word.stageorder >
                  previousstage && word.islotenable != null);
                if (result.length > 0) { result[index].isready_yts = currentstage; }
              });
            }
            previousstage = mergeddetails[ind].stageorder;
          });
          if (this.swapeboardval === 1) {
            this.uniqueStagename_st_temp = this.uniqueStagename_st;
            this.dtitle = 'Title';
          } else {
            this.uniqueStagename_st_temp = this.uniqueFilename_st;
            this.dtitle = 'Process';
            // this.stageconfigForm.controls.set='process';
          }
        }
      } else {
        this.dtitle = '';
        this.jsonObj_st = [];
        this.uniqueStagename = [];
        this.uniqueFilename = [];
        this.uniqueStagename_st = [];
        this.AssignedLotLoading_3 = true;
      }
    });
  }*/

  // method to show the pop up for reset for move back stgae
  dashboardMove(item, template: TemplateRef<any>) {
    this.selback = '0';
    this.selforward = '0';
    const sval = item.transactionid, sstatus = 1, stageorder = item.stageorder,
      batchlot = item.merged_lot, stagename_alias = item.stagename_alias, lottitle = item.lottitle, emp_name = item.emp_name;
    const val = sval + '~' + sstatus + '~' + stageorder + '~' + batchlot + '~' + stagename_alias + '~' + lottitle + '~' + emp_name;
   // this.uniqueStageTitles = this.stagenamelist;
   this.uniqueStageTitles=this.uniqueStagename_st; 
   this.allocatetype = '';
    let array: any;
    array = val.split('~');
    console.log(array);
    if (array[1] === 1) {
      this.allocatetype = 'Re Allocation';
    } else {
      this.allocatetype = 'Reverse or Bypass Stage';
    }
    this.stagename = array[4];
    this.lottitle = array[5];
    this.assignee = array[6];
    this.fromOrder = array[2];
    this.tranid = array[0];
    this.backstage = [];
    for (let i = 0; i < array[2] - 1; i++) {
      this.backstage.push(this.uniqueStageTitles[i]);
    }
    this.forwardstage = [];
    for (let i = array[2]; i < this.uniqueStageTitles.length; i++) {
this.forwardstage.push(this.uniqueStageTitles[i]);
    }
    this.reAllocateModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }

  // method to select back
  changeSelBack(eve) {
    this.selforward = '';
    this.selback = eve.target.value;
  }

  changeSelForward(eve) {
    this.selback = '';
    this.selforward = eve.target.value;
  }

  // method to get the to order
  getToOrder() {
    let toOrder = 0;
    if (this.selback !== '') {
      this.stype = 'B';
      const index = this.uniqueStageTitles.indexOf(this.selback);
      toOrder = index + 1;
    }
    if (this.selforward !== '') {
      this.stype = 'F';
      const index1 = this.uniqueStageTitles.indexOf(this.selforward);
      toOrder = index1 + 1;
    }
    return toOrder;
  }
  // method to save the stage movement
  selMove() {
    this.stoorder = this.getToOrder();
    const inputData = [];
    inputData.push({
      tranid: +this.tranid,
      fromorder: +this.fromOrder,
      toorder: +this.stoorder,
      option: this.stype,
      p_userid:+this.userid,
    });
    this.dashboardservice.jobBackForward(inputData[0]).subscribe(res => {
      if (res !== undefined && res !== null && res.body !== undefined && res.body !== null
        && res.body > 0) {
        this.reAllocateModalRef.hide();
        this.loadstagedetails();
      }
    }, err => { this.toastr.error('Error in loading job details'); });
  }

  relMove() {
    this.stoorder = this.getToOrder();
    const inputData = [];
    inputData.push({
      tranid: +this.tranid,
      fromorder: +this.fromOrder,
      toorder: +this.stoorder,
      option: 'D'
    });
    this.dashboardservice.jobBackForward(inputData[0]).subscribe(res => {
      if (res !== undefined && res !== null && res.body !== undefined && res.body !== null
        && res.body > 0) {
        this.reAllocateModalRef.hide();
        this.loadstagedetails();
      }
    }, err => { this.toastr.error('Error in loading job details'); });
  }
  ready_to_yts(param) {
    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Please Confirm',
        message: 'Are you sure do you want to Reopen the following article? ' + '\n' + param.lottitle,
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe(async (isConfirmed) => {
        if (isConfirmed) {
          const jobObject = new Object({
            jobworkflowid: param.jobworkflowid,
            lotid: param.lotid,
            stageorder: param.isready_yts,
            jobid: param.currentjobno,
          });
          this.dashboardservice.getReadyYTS(jobObject).subscribe(wfresponse => {
            console.log('res=', wfresponse);
            const MappedStage = JSON.parse(wfresponse.body[0]);
            if (MappedStage != null) {
              this.toastr.success('Successfully Reopen the article');
              this.loadstagedetails();
            } else {
                // toastr["warning"]("Already completed the Stage : " + d.data, "Message");
                this.toastr.error('Already completed the Stage');
            }
          }, error => { this.toastr.error('Error while getting data'); });
        } else {
        }
      }
      );
    console.log('calling ready_to_yts');
  }
  TriggerApp(item1) {
    console.log('calling TriggerApp');

    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Please Confirm',
        message: 'Are you sure want to restart this  ' + item1.lottitle + ' chapter?',
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe(async (isConfirmed) => {
        if (isConfirmed) {
       const jobObject = new Object({
            transid: item1.transactionid,
            fields: '',
            option: 'checkout',
            comment: '',
            cflag: 'A',
          userid: localStorage.getItem('userid'),
          });
          this.dashboardservice.PostUpdateLotTransaction(jobObject).subscribe(wfresponse => {
            debugger;
            console.log('res=', wfresponse);
            const MappedStage = JSON.parse(wfresponse.body[0]);
            if (MappedStage != null) {
              this.toastr.success('Successfully reassigned');
              this.loadstagedetails();
            } else {
                // toastr["warning"]("Already completed the Stage : " + d.data, "Message");
                this.toastr.error('Already completed the Stage');
            }
          }, error => { this.toastr.error('"Error in Start App details'); });

        } else {
        }
      }
      );
  }
  showerror(item1) {
    console.log('calling showerror');
    const jobObject = new Object({
      tranid: item1.transactionid,
    });
    this.dashboardservice.geterror(jobObject).subscribe(wfresponse => {
      console.log('res=', wfresponse);
      const MappedStage = JSON.parse(wfresponse.body[0]);
      if (MappedStage != null) {
        this.toastr.success('Chapter Reverted successfully');
        this.loadstagedetails();
      } else {
          // toastr["warning"]("Already completed the Stage : " + d.data, "Message");
          this.toastr.error('Error in loading job details');
      }
    }, error => { this.toastr.error('Error in loading job details'); });
  }
  backword(item1) {
    console.log('calling backword');
    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Please Confirm',
        message: 'Are you want to Revertback this ' + item1.lottitle + ' chapter?',
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe(async (isConfirmed) => {
        if (isConfirmed) {

          const jobObject = new Object({
            tranid: +item1.transactionid,
            fromorder: +item1.stageorder,
            toorder: 0,
            option: 'B'
          });
          this.dashboardservice.jobBackForward(jobObject).subscribe(res => {
            if (res !== undefined && res !== null && res.body !== undefined && res.body !== null
              && res.body > 0) {
                this.toastr.success('Chapter Reverted successfully');
              this.loadstagedetails();
            } else {
              this.toastr.error('Error in loading job details');
            }
          }, err => { this.toastr.error('Error in loading job details'); });

        } else {
        }
      }
      );
}
manualcheckout(item1){
  console.log(item1);
    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Please Confirm',
        message: 'Are you sure want to fail this ' + item1.lottitle + ' chapter?',
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe(async (isConfirmed) => {
        if (isConfirmed) {

          const jobObject = new Object({
            p_tranid: item1.transactionid.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:''

          });
          this.dashboardservice.manualcheckout(jobObject).subscribe(res => {
            if (res !== undefined && res !== null && res.body !== undefined && res.body !== null) {
                this.toastr.success('Chapter Failed successfully');
              this.loadstagedetails();
            } else {
              this.toastr.error('Error in occur while failing the chapter');
            }
          }, err => { this.toastr.error('Error in occur while failing the chapter'); });

        } else {
        }
      }
      );
}

skiplot(item1){
debugger;

 this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Please Confirm',
        message: 'Are you sure want to forward this ' + item1.lottitle + ' chapter?',
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe(async (isConfirmed) => {
        if (isConfirmed) {
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:''

          });
        
this.dashboardservice.forwardstage(jobObject).subscribe(res => {
  debugger;
            if (res !== undefined && res !== null && res.body !== undefined && res.body !== null) {
              debugger;
                this.toastr.success('Chapter Forwarded successfully');
              this.loadstagedetails();
            } 
            
          }, err => { 
            debugger;
            this.toastr.success('Chapter Forwarded successfully')
this.loadstagedetails();

          });
        } 
      }
      );
    






}

}