import {
  Component,
  OnInit,
  Inject,
  TemplateRef,
  Input,
  ViewChild,
  ElementRef,
  HostListener
} from "@angular/core";
import { DashboardService } from "../dashboard.service";
import { CollectionprocessService } from "src/app/ccstageprocess/collectionprocess/collectionprocess.service";
import {
  MAT_DIALOG_DATA,
  MatDialogRef,
  MatDialog,
  MatDialogConfig,
} from "@angular/material";
import { DragDropModule } from "@angular/cdk/drag-drop";
import { ToastrService } from "ngx-toastr";
import { BsModalRef, BsModalService, ModalOptions } from "ngx-bootstrap";
import { skip } from "rxjs/operators";
import { JobmasterService } from "src/app/jobconfiguration/jobmaster/jobmaster.service";
import { Ccjoburlmaster } from "src/app/ccstageprocess/collectionprocess/collectionprocess";
import { NgxSpinnerService } from "ngx-spinner";
import { environment } from "src/environments/environment";
import toast from "devextreme/ui/toast";
import { Console, error } from "console";
import { elementEventFullName } from "@angular/compiler/src/view_compiler/view_compiler";
import { ErrormasterService } from "src/app/masters/errormaster/errormaster.service";
import { DialogService } from "ng2-bootstrap-modal";
import { CommondialogComponent } from "src/app/Shared/commondialog/commondialog.component";
import form from "devextreme/ui/form";
import { ErrorremarksService } from "src/app/masters/errorremarks/errorremarks.service";
import { Errorremarks_model } from "src/app/masters/errorremarks/errorermarks";
import { element } from "protractor";
import { RecorderrorreportService} from "../../reports/recorderrorreport/recorderrorreport.service"
import { saveAs } from "file-saver";
@Component({
  selector: "app-completionPopup",
  templateUrl: "./completionPopup.component.html",
  styleUrls: ["./completionPopup.component.css"],
})
export class CompletionPopupComponent implements OnInit {
  @ViewChild("worlAreaPopUpTemplate", { static: true })
  worlAreaPopUpTemplate: TemplateRef<any>;
  @Input() swapeboardval: number;
  @ViewChild('input_file_upload', {static: false})
  input_file_upload: ElementRef;

   @ViewChild('output_file_upload', {static: false})
   output_file_upload: ElementRef;

  userid: string = localStorage.getItem("userid");
  dragHandle: any;
  description: any;
  transactionid: number;
  moveback: string;
  jobworkflowid: number;
  comments_header: string;
  buttonType: string;
  cflag: string;
  selback: string;
  comments: string;
  calltype: string;
  procomment: string;
  lotstatus: string;
  projectcode: string;
  biddate: string;
  joburl: string;
  lotid: number;
  jobid: number;
  lot_comments: any;
  uniqueStageTitles = [];
  stagelist = [];
  lotlist_output = [];
  lotlist = [];
  lotlist_filter = [];
  categorylist: any = [];
  stageorderlotlistorg: any = [];
  stageorderlotlist: any = [];
  projetdefid: number;
  stageorder: number;
  p = 1;
  public searchText: string;
  itemsPerPage = 10;
  insert: boolean = false;
  insertall: boolean = false;
  fileData = new FormData();
  insert_s: any = [];
  infotable: boolean = false;
  infotablelst: any = [];
  lotmetafields: any = [];
  fields: any = [];
  movemessagefields: any = [];
  jobstatus: any;
  uniqueStagename = [];
  uniqueFilename = [];
  uniqueFilename_st: any;
  uniqueStagename_st: any;
  jsonObj = [];
  accept_btn: boolean = true;
  jsonObj_st = [];
  selforward: any;
  allocatetype: any;
  backstage: any = [];
  forwardstage: any = [];
  stagename = [];
  lottitle = [];
  assignee = [];
  fromOrder = [];
  tranid = [];
  skiptitle_lst = [];
  stype: any;
  stoorder: any;
  infoselectedjob: string;
  infoselectedlot: string;
  metaall: any[] = [];
  job_lotlist: any[] = [];
  reAllocateModalRef: BsModalRef;
  default_div1: any;
  default_div2: any;
  nilerror=true;
  config: ModalOptions = {
    backdrop: "static",
    keyboard: false,
    animated: true,
    class: "modal-dialog-centered",
    ignoreBackdropClick: true,
  };
  Skippopup: BsModalRef;
  commentsPopUpModalRef: BsModalRef;
  editlotmetadataPopUpModalRef: BsModalRef;
  metadatalist: any[] = [];
  metadatalistorg: any[] = [];
  ccjoburlmaster = {} as Ccjoburlmaster;
  infoselectedjobid: number;
  infoselectedlotid: number;
  mail_url: string;
  mailid: string;
  parentid: string;
  lotmaster_status: string;
  selectedcategoryid = 0;
  mail_parent_url: string = environment.mail_parenturl;
  mail_parenturl_start: string = environment.mail_parenturl_start;
  mail_parenturl_end: string = environment.mail_parenturl_end;
  automailprojectid: number = environment.automail_projectid;
  projectid_not_unique:number=environment.projectid_notunique;
  fpr_wfid:number=environment.fpr_wfid;
  projectid_iteration:number = environment.projectid_iteration;
  old_category: string;
  command = false;
  subject: string;
  mailbody: string;
  from_user: string;
  rec_date: string;
  re_area: boolean = false;
  be_area: boolean = false;
  re_count :any= [];
  workAreaPopUpModalRef: BsModalRef;

  //for record error
  errorrecord_pass: any = [];
  recorderrordetailslst: any = [];
  qaremarklst: any = [];
  uploaded_filename: any;
  file_hide: boolean = true;
  _ddlQASettings: any = [];
  _qaremarkselected: any = [];
  qaremark: boolean = false;
  errorremark: string = "";
  input_upload: any = [];
  output_upload: any = [];
  file: any;
  btn: string = "Save";
  recorderrorid: string = "";
  errorlst: any = [];
  btnqa: boolean = false;
  re_btn:boolean = false;
  p1 = 1; 
  public searchText1: string;
  operation:any;
  itemsPerPage1 = 5;
  key = 'errortype';
  reverse = false;

  errorremarkslst: any=[];
  _ddlerrorremarkSettings: any=[];
  e_remarks :any=[]
  _errorremarkselected :any=[];

  in_files: any=[];
  out_files: any=[];
 
  major_error : number;
  minor_error: number;
  wfid:number;
  qa_corr_area: boolean=false;
  iReflectData:any = [];
  projectname:string;
  uniqueAgentstages: { key: string; count: number }[];
  selected_categorygroup:number=0;
  to_order=0;
  iReflect: any = []; // Monicaa
  recorderror_exist :number=0;
  constructor(
    private dashboardservice: DashboardService,
    private dialog: MatDialog,
    private errorservice: ErrormasterService,
    private dialog1: MatDialog,
    private modalService: BsModalService,
    private Collectionservice: CollectionprocessService,
    private toastr: ToastrService,
    private dialogRef: MatDialogRef<CompletionPopupComponent>,
    private jobmasterservice: JobmasterService,
    private SpinnerService: NgxSpinnerService,
    private dialogService: DialogService,
    private errorremarksservice: ErrorremarksService,
	private recorderrorservice:RecorderrorreportService,														
    @Inject(MAT_DIALOG_DATA) data
  ) {
    console.log(data);
    this.comments_header = "Comments";
    this.description = "CC –  " + data.stagename + " Process";
    this.transactionid = data.tranid;
    this.jobworkflowid = data.jobworkflowid;
    this.lotid = data.lotid;
    this.jobid = data.jobid;
    this.lotstatus = data.status;
    this.projectcode = data.projectcode;
    this.projectname = data.projectname;
    this.biddate = data.biddate;
    this.joburl = data.joburl;
    this.moveback = data.moveback;
    this.projetdefid = data.projetdefid;
    this.stageorder = data.stageorder;
    this.lotmaster_status = data.lotmaster_status;
    this.old_category = data.lotmaster_status;
    this.jobstatus = data.jobstatus;
    this.stagename = data.stagename;
    this.mailid = data.id;
    this.parentid = data.parentid;
    this.wfid=data.wfid;
    if (this.projetdefid != this.automailprojectid)
      this.selectedcategoryid = -1;
    if (
      this.mailid !== "" &&
      this.mailid !== undefined &&
      this.mailid !== null &&
      this.mail_parenturl_start !== "" &&
      this.mail_parenturl_start !== undefined &&
      this.mail_parenturl_start !== null &&
      this.mail_parenturl_end !== "" &&
      this.mail_parenturl_end !== undefined &&
      this.mail_parenturl_end !== null
    ) {
      //this.mail_url=this.mail_parent_url+this.mailid;
      this.mail_url =
        this.mail_parenturl_start + this.mailid + this.mail_parenturl_end;
      window.open(this.mail_url);
      //this.mailbody="<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><meta name=\"Generator\" content=\"Microsoft Word 15 (filtered medium)\"><style><!--@font-face{font-family:\"Cambria Math\"}@font-face{font-family:Calibri}p.MsoNormal, li.MsoNormal, div.MsoNormal{margin:0in;font-size:11.0pt;font-family:\"Calibri\",sans-serif}a:link, span.MsoHyperlink{color:blue;text-decoration:underline}span.EmailStyle21{font-family:\"Calibri\",sans-serif;color:windowtext}.MsoChpDefault{font-size:10.0pt}@page WordSection1{margin:1.0in 1.0in 1.0in 1.0in}div.WordSection1{}--></style></head><body lang=\"EN-US\" link=\"blue\" vlink=\"purple\" style=\"word-wrap:break-word\"><div class=\"WordSection1\"><div><p class=\"MsoNormal\" style=\"\">Good afternoon,</p><p class=\"MsoNormal\" style=\"\">&nbsp;Please create a project from the information provided below. Project ID may be 5855148.</p><p class=\"MsoNormal\" style=\"\">&nbsp;Thank you,</p></div><p class=\"MsoNormal\">&nbsp;</p><p class=\"MsoNormal\">&nbsp;</p><div><div><p class=\"MsoNormal\" style=\"margin-bottom:8.0pt; line-height:106%\">&nbsp;</p><p class=\"MsoNormal\" style=\"margin-bottom:8.0pt; line-height:106%\"><br><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" style=\"font-family:Arial,Helvetica,sans-serif; box-sizing:initial; border-collapse:collapse; width:580px\"><tbody><tr><td valign=\"top\" style=\"border-bottom:2px solid #ED7800; padding-bottom:10px\"><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"580\" style=\"font-family:Arial,Helvetica,sans-serif; border-collapse:collapse; width:580px\"><tbody><tr><td align=\"left\" valign=\"top\" width=\"458\" style=\"width:458px\"><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"458\" style=\"font-family:Arial,Helvetica,sans-serif; color:#000000; font-size:13px; line-height:18px; border-collapse:collapse; width:458px\"><tbody><tr><td style=\"font-size:16px; line-height:20px; font-weight:bold\"><span style=\"text-decoration:none; color:#000000\">Mary Ann Duke</span> </td></tr><tr><td>Team Lead, Editorial Content</td></tr></tbody></table></td></tr></tbody></table></td></tr><tr><td valign=\"top\" style=\"padding-top:10px\"><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"580\" style=\"font-family:Arial,Helvetica,sans-serif; border-collapse:collapse; width:580px\"><tbody><tr><td align=\"left\" valign=\"middle\" width=\"380\" style=\"width:380px\"><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"380\" style=\"font-family:Arial,Helvetica,sans-serif; color:#000000; font-size:13px; line-height:18px; border-collapse:collapse; width:380px\"><tbody><tr><td></td></tr></tbody></table></td><td align=\"right\" valign=\"middle\" width=\"200\" style=\"width:200px\"><a href=\"https://www.constructconnect.com/\" target=\"_blank\"><img border=\"0\" height=\"25\" width=\"200\" src=\"cid:6156a93ca5bbfc3bb98d145b3e17aaa3fc231168\" alt=\"logo\" style=\"width:200px; height:25px; max-width:200px\"> </a></td></tr></tbody></table></td></tr></tbody></table><br></p></div><div><div style=\"border:none; border-top:solid #E1E1E1 1.0pt; padding:3.0pt 0in 0in 0in\"><p class=\"MsoNormal\"><b>From:</b> Trip Burton &lt;Trip.Burton@ConstructConnect.com&gt; <br><b>Sent:</b> Monday, July 17, 2023 7:45 PM<br><b>To:</b> MERX API &lt;merxapi@constructconnect.com&gt;; Trip Burton &lt;Trip.Burton@ConstructConnect.com&gt;; BidInvite &lt;bidinvite@constructconnect.com&gt;; Michael Stubbs &lt;Michael.Stubbs@constructconnect.com&gt;<br><b>Subject:</b> Merx Project 0000252184 - Published 2023-07-17 15h47-5855148</p></div></div><p class=\"MsoNormal\">&nbsp;</p><p style=\"margin-bottom:12.0pt\"><u>Merx Id:</u> 0000252184 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<u>Source Id:</u> 2553682563<br><u>Verson:</u> 0<br><br><strong><span style=\"font-size:12.0pt; font-family:&quot;Calibri&quot;,sans-serif\">IWS/IS/DCMB CP000701 Hunt Club Stormwater Management Facility Retrofit</span></strong><br><u>Solicitation:</u>&nbsp;&nbsp;&nbsp;00123-91381-T01<br><u>Bid Date:&nbsp;</u>&nbsp;&nbsp;2023-08-08 19h00 &nbsp;&nbsp;( America/New_York )<br><u>Region:</u>&nbsp;&nbsp;&nbsp;Ottawa<br>&nbsp;<br>&nbsp;<br><u>Project Value:</u>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;( )<br><br><u>Project Type:</u>&nbsp;&nbsp;&nbsp;NOTICE<br><u>Project Status:</u>&nbsp;&nbsp;&nbsp;ACTIVE<br><u>Pricing Type:</u>&nbsp;&nbsp;&nbsp;LUMP_SUM<br><u>Submission Type:</u> ONLINE<br><u>Include the following note:</u> Official bid documents must be obtained from Merx and bid submissions must be done through the Merx platform.<br><u>Published:</u>&nbsp;&nbsp;&nbsp;2023-07-17 15h47<br><br><u>Project URL:</u>&nbsp;&nbsp;&nbsp;<a href=\"https://www.merx.com/private/solicitations/2553682563/abstract\">https://www.merx.com/private/solicitations/2553682563/abstract</a><br><br><strong><span style=\"font-family:&quot;Calibri&quot;,sans-serif\">Project Scope:</span></strong></p><p>RFT No. 00123-91381-T01&nbsp;<br>CP000701 HUNT CLUB STORMWATER MANAGEMENT FACILITY RETROFIT&nbsp;</p><p class=\"MsoNormal\" style=\"margin-bottom:12.0pt\"><br><br><strong><span style=\"font-family:&quot;Calibri&quot;,sans-serif\">Categories:</span></strong></p><p>Construction Services</p><p class=\"MsoNormal\" style=\"margin-bottom:12.0pt\"><br><br>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------<br><strong><span style=\"font-family:&quot;Calibri&quot;,sans-serif\">Owner:</span></strong><br>Id: &nbsp;&nbsp;&nbsp;415254754<br>City of Ottawa<br>100 Constellation Drive<br><br>Ottawa &nbsp;&nbsp; ON &nbsp;&nbsp;K2G 6J8<br>Phone:&nbsp;&nbsp;&nbsp;613-580-2424 x14689 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fax:&nbsp;&nbsp;&nbsp; 613-560-2126<br><a href=\"http://www.ottawa.ca/\">www.ottawa.ca</a><br><br>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------<br><strong><span style=\"font-family:&quot;Calibri&quot;,sans-serif\">Contacts:</span></strong><br>Contact Type:&nbsp;&nbsp;&nbsp;ISSUING&nbsp;&nbsp;( ACTIVE )<br>Laura Dennee<br>Title:&nbsp;&nbsp;&nbsp;Buyer<br>Phone: &nbsp;&nbsp;&nbsp;613-580-2424 x25181 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fax:&nbsp;&nbsp;&nbsp;<br><a href=\"mailto:laura.dennee@ottawa.ca\">laura.dennee@ottawa.ca</a><br><br>&nbsp;</p><p class=\"MsoNormal\">&nbsp;</p><table class=\"MsoNormalTable\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"580\" style=\"width:435.0pt; border-collapse:collapse; box-sizing:initial\"><tbody><tr><td valign=\"top\" style=\"border:none; border-bottom:solid #ED7800 1.5pt; padding:0in 0in 7.5pt 0in\"><table class=\"MsoNormalTable\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"580\" style=\"width:435.0pt; border-collapse:collapse\"><tbody><tr><td width=\"458\" valign=\"top\" style=\"width:343.5pt; padding:0in 0in 0in 0in\"><table class=\"MsoNormalTable\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"458\" style=\"width:343.5pt; border-collapse:collapse\"><tbody><tr><td style=\"padding:0in 0in 0in 0in\"><p class=\"MsoNormal\" style=\"line-height:15.0pt\"><b><span style=\"font-size:12.0pt; font-family:&quot;Arial&quot;,sans-serif; color:black\">Trip Burton </span></b></p></td></tr><tr><td style=\"padding:0in 0in 0in 0in\"><p class=\"MsoNormal\" style=\"line-height:13.5pt\"><span style=\"font-size:10.0pt; font-family:&quot;Arial&quot;,sans-serif; color:black\">Manager, Editorial Content</span></p></td></tr></tbody></table></td></tr></tbody></table></td></tr><tr><td valign=\"top\" style=\"padding:7.5pt 0in 0in 0in\"><table class=\"MsoNormalTable\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"580\" style=\"width:435.0pt; border-collapse:collapse\"><tbody><tr><td width=\"380\" style=\"width:285.0pt; padding:0in 0in 0in 0in\"><table class=\"MsoNormalTable\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"380\" style=\"width:285.0pt; border-collapse:collapse\"><tbody><tr><td style=\"padding:0in 0in 0in 0in\"><p class=\"MsoNormal\" style=\"line-height:13.5pt\"><b><span style=\"font-size:10.0pt; font-family:&quot;Arial&quot;,sans-serif; color:black\">m: </span></b><span style=\"font-size:10.0pt; font-family:&quot;Arial&quot;,sans-serif; color:black\"><a href=\"tel:772-215-6604\"><span style=\"color:black; text-decoration:none\">772-215-6604</span></a> </span></p></td></tr></tbody></table></td><td width=\"200\" style=\"width:150.0pt; padding:0in 0in 0in 0in\"><p class=\"MsoNormal\" align=\"right\" style=\"text-align:right\"><a href=\"https://www.constructconnect.com/\" target=\"_blank\"><span style=\"font-family:&quot;Arial&quot;,sans-serif; text-decoration:none\"><img border=\"0\" width=\"200\" height=\"25\" id=\"Picture_x0020_1\" src=\"cid:6156a93ca5bbfc3bb98d145b3e17aaa3fc231168\" alt=\"logo\" style=\"width:2.0833in; height:.2604in\"></span></a><span style=\"font-family:&quot;Arial&quot;,sans-serif\"></span></p></td></tr></tbody></table></td></tr></tbody></table><p class=\"MsoNormal\" style=\"margin-bottom:12.0pt\">&nbsp;</p></div></div></body></html>";
    }
  }

  async ngOnInit(): Promise<void> {
    if(this.projetdefid == this.automailprojectid)
   { this.loadcategory();
    this.getmaildetailsbyid();
   }

   
    this._ddlQASettings = {
      singleSelection: true,
      idField: "errorid",
      textField: "errortype",
      itemsShowLimit: 7,
      allowSearchFilter: true,
    };

    this._ddlerrorremarkSettings = {
      singleSelection: true,
      idField: "errorremarksid",
      textField: "errorremarks",
      itemsShowLimit: 7,
      allowSearchFilter: true,
    };
    // this.default_div1 = {'width': '150vh'};
    this.default_div2 = {
      padding: "15px",
   //   "max-height": "40vh",
      "overflow-y": "auto",
    };
    if (this.stageorder === 2) {
      // this.default_div1 = {'width':'165vh'};
      this.default_div2 = {
        padding: "15px",
    //    height: "40vh",
        "overflow-y": "auto",
      };
    } else {
      //this.default_div1 = {'width': '160vh'};
      this.default_div2 = {
        padding: "15px",
      //  "max-height": "40vh",
        "overflow-y": "auto",
      };
    }
    // this.getlotmetadata('onload');
    this.joblststageorder("onload");
    // this.loadstagedetails();
    if (this.lotstatus == "R" || this.lotstatus == "YTS") {
      //await this.getcheckin(this.transactionid,this.jobworkflowid);
      this.getcheckin("onload");
    } else {
      this.loadJobDetails();
    }
  }
  ngOnDestroy(): void {
    this.workarea_checkin('','exit');
   }
  loadJobDetails() {
    //this.mergedlot = 0;
    this.lotlist_output = [];
    this.lotlist = [];
    this.lotlist_filter = [];
    let lotids = "";
    let stageindex;
    lotids = this.lotid + "," + lotids;
    var inputData = [];
    inputData.push({
      jobid: this.jobid,
      //lotid: this.lotid.toString()
      lotid: lotids.toString(),
      projectdefinitionid: this.projetdefid,
    });
    console.log(inputData);
    this.Collectionservice.getJobDetails(inputData[0]).subscribe(
      (res) => {
        debugger;
        if (
          res.body[1] !== undefined &&
          res.body[1] !== null &&
          JSON.parse(res.body[1][0]) !== null
        ) {
          this.stagelist = JSON.parse(res.body[1]);
          var index = this.stagelist.findIndex(
            (p) => p.jobworkflowid == this.jobworkflowid
          );
          stageindex = index;
          this.uniqueStageTitles = this.stagelist.slice(
            index + 1,
            this.stagelist.length
          );
        }
        if (
          res.body[2] !== undefined &&
          res.body[2] !== null &&
          JSON.parse(res.body[2][0]) !== null
        ) {
          var lotcomments = JSON.parse(res.body[2][0]);
          lotcomments.forEach((i) => {
            if (
              this.jobworkflowid == i.tojobworkflowid &&
              this.lotid == i.lotid
            ) {
              this.lot_comments = i.comments;
            }
          });
        }
      },
      (err) => {
        this.toastr.error("Loading Lot detail failed.");
      }
    );
  }
  loadcategory() {
    this.Collectionservice.getCategory().subscribe(
      (res) => {
        //this.dashboardservice.Get_all().subscribe(res => {
        debugger;
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.categorylist = JSON.parse(res.body[0]);
              if (this.lotmaster_status != null){
                this.selectedcategoryid = this.categorylist.filter(
                  (x) => x.categoryname == this.lotmaster_status
                )[0].categoryid;
                this.selected_categorygroup=this.categorylist.filter(x => x.categoryname == this.lotmaster_status)[0].categorygroup;
            }
              console.log(this.categorylist);
            }
          }
        }
      },
      (error) => {
        this.toastr.error("Error while getting category list");
        this.categorylist = [];
      }
    );
  }
  onCheckboxChange(value,name) {
    console.log(value)
    console.log(name)


    this.metadatalist.forEach(element => {
      if(element.FieldName==name){
        element.FieldValue=value;
      }  
    });
    console.log(this.metadatalist)
  }
 getmaildetailsbyid(){
    let field =[{mailid:this.mailid,
      parentid:this.parentid}];
          let fileData = new FormData();
      fileData.append('model', JSON.stringify(field));
              this.Collectionservice.GetMailDetailsByID(fileData).subscribe(res1 => {
                debugger;
                if (res1.body !== undefined && res1.body !== null) {  
                  debugger;
                  this.subject=res1.body.subject;
                  this.from_user=res1.body.from_email;
                  this.rec_date=res1.body.rec_date;
                  this.mailbody=res1.body.body;
                }
              }, error => {this.toastr.error('Error in geting email details'); });
  } 
   getcheckin(mode) {
					
    if (mode != "onload") {
      if (this.stageorderlotlist.length > 0) {
        this.stageorderlotlist.forEach((element) => {
          if (element.lotstatus === "R" && element.insert_p === 1) {
            let fileData = new FormData();
            fileData.append("tranid", element.transactionid.toString());
            fileData.append("userid", this.userid.toString());
            fileData.append("lotstatus", "P");
            fileData.append("p_option", "checkin");
            fileData.append("jobworkflowid", element.jobworkflowid.toString());
            this.dashboardservice.getCheckincur(fileData).subscribe(
              (res) => {
                this.loadJobDetails();
              },
              (error) => {
                this.toastr.error("Error in updating lot transaction");
              }
            );
          }
        });
      }
    } else {
      let fileData = new FormData();
      fileData.append("tranid", this.transactionid.toString());
      fileData.append("userid", this.userid.toString());
      fileData.append("lotstatus", "P");
      fileData.append("p_option", "checkin");
      fileData.append("jobworkflowid", this.jobworkflowid.toString());
      this.dashboardservice.getCheckincur(fileData).subscribe(
        (res) => {
          this.loadJobDetails();
          if(this.stagename.toString()=="Bid Entry"){
            var index = this.stageorderlotlist.findIndex(
              (p) => p.transactionid == this.transactionid
            );
            this.stageorderlotlist[index]["lotstatus"] = "P";
          }
        },
        (error) => {
          this.toastr.error("Error in updating lot transaction");
        }
      );
    }
  }

  //12-10-2023
  error_check(cflag, mode, toorder,error_length){

    debugger;
    this.major_error = 0;
    this.minor_error = 0;
    this.recorderror_exist =0;
    this.errorlst.forEach(element => {
      if(element.errorcategory == 'Serious Error'){
        this.major_error = this.major_error +1;
      }else if(element.errorcategory == 'Minor Error'){
        this.minor_error = this.minor_error + 1;
      }
    });

    // undo
    if(this.major_error > 5 || this.minor_error >3){
      if(this.major_error > 5 && this.minor_error > 3){
        this.toastr.error('Maximum 5 Major and 3 Minor errors exceed.');
      }
     else if(this.major_error > 5){
        this.toastr.error('Maximum 5 Major errors exceed.');
      }
     else if( this.minor_error > 3){
        this.toastr.error('Maximum 3 Minor errors exceed.');
      }
      return;
    }

    let temp_ = [];
      this.stageorderlotlist.forEach((element) => {
        if (element.insert_p === 1) {
          temp_.push(element);
          if(element.re_count!='' &&  element.re_count != 0 && element.re_count != undefined && element.re_count != null){
          if(this.recorderror_exist == 0){
            this.recorderror_exist=parseInt(element.re_count);
          }else{
            this.recorderror_exist+=parseInt(element.re_count);
          }  
        }  
              
        }
      });
    if((this.recorderror_exist == 0 ||this.recorderror_exist == undefined || this.recorderror_exist == null ) && (error_length ==0 || error_length ==undefined || error_length == null)){																			
      this.dialogService
    .addDialog(CommondialogComponent, {
      title: "Please Confirm",
      message:  "There are no errors recorded. Accept the lot without errors?",
      hclass: "modelsuccess",
      oktext: "Yes",
      canceltext: "No",
      okshow: true,
      cancelshow: true,
    })
    .subscribe((isConfirmed) => {
      if (isConfirmed) {
        debugger;
        //   this.toastr.success('yes');
          this.save(cflag,mode,toorder)
        }else{
          // this.toastr.error('no');
        }
      });
      
    }else{
      this.save(cflag,mode,toorder)
    }
  }

  async save(cflag, mode, toorder) {
debugger;
    if(this.command && (this.procomment === null ||  this.procomment == '' ||  this.procomment == undefined ) && (mode=="dup" || mode=="Rej")){
      this.toastr.error('Comment should not be empty');
      return;
    }

    let pass_flag = 0;
    let add_field;
    let move_add_field;
    this.fields = [];
    this.iReflect = []; // Monicaa
    this.movemessagefields = [];
    this.stageorderlotlist.forEach((element) => {
      if (element.insert_p === 1) {
        pass_flag = pass_flag + 1;
      }
    });
    if (pass_flag == 0) {
      this.toastr.error("Please select atleast one job....");
      return;
    }
    if (this.projetdefid == this.automailprojectid) {
      if (this.selectedcategoryid != 0) {
        var selectedcategoryname = this.categorylist.filter(
          (x) => x.categoryid == this.selectedcategoryid
        )[0].categoryname;
        this.selected_categorygroup=this.categorylist.filter(
          (x) => x.categoryid == this.selectedcategoryid
        )[0].categorygroup;
         
        if (cflag === "B") {
          this.calltype = "checkout";
          let index = this.stagelist.findIndex(
            (x) => x.stageorder == this.stageorder
          );
          this.selback = this.stagelist[index + 1].jobworkflowid;
        } else {
          /* if (
            selectedcategoryname == "Already Exist" ||
            selectedcategoryname == "Query" ||
            selectedcategoryname == "Invalid " ||
            selectedcategoryname == "Broken Agent"
          ) { */
          if(this.selected_categorygroup==1){
            this.calltype = selectedcategoryname;
            toorder = this.stagelist[this.stagelist.length - 1].stageorder;
            this.to_order= this.stagelist[this.stagelist.length - 1].stageorder;
            this.selback =
              this.stagelist[this.stagelist.length - 1].jobworkflowid;
          } else {           
            this.calltype = selectedcategoryname;
            let index = this.stagelist.findIndex(
              (x) => x.stageorder == this.stageorder
            );
            this.selback = this.stagelist[index + 1].jobworkflowid;
          }
          this.buttonType = "Complete";
            this.comments = this.buttonType + " Comments";
        }
        this.cflag = cflag;
      }
    } else {
      if (mode !== "dup") {
        if (cflag === "B") {
          this.buttonType = "Rejection";
        } else {
          this.buttonType = "Complete";
        }
        this.comments = this.buttonType + " Comments";
        this.comments_header = "Comments";
        if (mode === "skip") {
          this.calltype = "skip";
          this.selback = "";
        } else {
          this.calltype = "checkout";
          let index = this.stagelist.findIndex(
            (x) => x.stageorder == this.stageorder
          );
          this.selback = this.stagelist[index + 1].jobworkflowid;
        }
      } else {
        this.calltype = "duplicate";
        toorder = this.stagelist[this.stagelist.length - 1].stageorder;
        this.selback = this.stagelist[this.stagelist.length - 1].jobworkflowid;
      }
      this.cflag = cflag;
    }

    let entity_temp = null;
    if (this.procomment === null) {
      this.procomment = "";
    }
    if (this.selback === null) {
      this.selback = "";
    }
    
    //this.getcheckin("accept");

    if (mode == "accept") {
      this.selback = "";
      this.workAreaPopUpModalRef = this.modalService.show(
        this.worlAreaPopUpTemplate,
        this.config
      );
      const aa = document.getElementsByClassName("modal-content");
      aa[0].classList.remove("modal-content");
    }else {
      this.stageorderlotlist.forEach(async (element) => {
        if (element.insert_p === 1) {
          add_field = {
            transid: element.transactionid,
            jobworkflowid: element.jobworkflowid,
            option: this.calltype,
            cflag: this.cflag,
            userid: this.userid,
            tostage: this.selback,
            jobid: element.jobid.toString(),
            comment: this.procomment == undefined ? "" : this.procomment,
            batchid: "",
            lotid: element.lotid.toString(),
            fromorder: element.stageorder,
            toorder: toorder == undefined ? "" : toorder,
            skipto: "",
            selected_categorygroup: this.selected_categorygroup
          };

          this.fields.push(add_field);
          // Monicaa
          this.iReflect.push({
            tranid:element.transactionid,
            projectcode: element.projectcode,
            projdefid:  this.projetdefid,
            projectname: element.projectname,
            jobid: element.jobid.toString(),
            lotid: element.lotid.toString(),
            re_count:(element.re_count !='' && element.re_count !=undefined && element.re_count !=null && element.re_count !=0)?element.re_count:0,
          });
          // Monicaa
          if (this.projetdefid == this.automailprojectid) {
            move_add_field = {
              userid: this.userid,
              lotid: element.lotid,
              tranid: element.transactionid,
              mailid: element.uniquemailid,
              option: this.calltype,
            };
            this.movemessagefields.push(move_add_field);
          }
        }
      });
      this.Post(mode);
    }
  }
  commentsave() {
    let add_field;
    let move_add_field;
    this.fields = [];
    this.iReflect = []; // Monicaa
    this.movemessagefields = [];
    if (this.selback == "") {
      //let index=this.stagelist.findIndex(x=> x.stageorder == this.stageorder);
      //this.selback=this.stagelist[index+1].jobworkflowid;
    }
    this.stageorderlotlist.forEach(async (element) => {
      if (element.insert_p === 1) {
        add_field = {
          transid: element.transactionid,
          jobworkflowid: element.jobworkflowid,
          option: this.calltype,
          cflag: this.cflag,
          userid: this.userid,
          tostage: this.selback,
          jobid: element.jobid.toString(),
          comment: this.procomment == undefined ? "" : this.procomment,
          batchid: "",
          lotid: element.lotid.toString(),
          fromorder: element.stageorder,
          toorder:this.to_order,
          skipto: "",
          selected_categorygroup: this.selected_categorygroup,
          lotstatus_checkin: element.lotstatus
        };

        this.fields.push(add_field);
         // Monicaa
         this.iReflect.push({
          tranid:element.transactionid,
          projectcode: element.projectcode,
          projdefid: this.projetdefid,
          projectname: element.projectname,
          jobid: element.jobid.toString(),
          lotid: element.lotid.toString(),
          re_count:(element.re_count !='' && element.re_count !=undefined && element.re_count !=null && element.re_count !=0)?element.re_count:0,
        });
        // Monicaa
        if (this.projetdefid == this.automailprojectid) {
          move_add_field = {
            userid: this.userid,
            lotid: element.lotid,
            tranid: element.transactionid,
            mailid: element.uniquemailid,
            option: this.calltype,
          };
          this.movemessagefields.push(move_add_field);
        }
      }
    });
    this.Post("accept");
  }

  Post(mode) {
    this.SpinnerService.show();
    this.iReflectData = []; var agentmode='';
    if (this.stagename.toString()=="QA" && mode == "accept") {   
     this.iReflect.forEach(v => {
      var iReflectval = {
        projectid : v.projectcode,
        projectname: v.projectname == null ?'nan':v.projectname,
        jobid: +v.jobid,
        lotid: +v.lotid,
        projdefid: +v.projdefid,
        tranid: +v.tranid,
        re_count:v.re_count
      }
      this.iReflectData.push(iReflectval);
    });
    }//end QA stage
    let fileData = new FormData();
    fileData.append("model", JSON.stringify(this.fields));
    fileData.append("iReflect", JSON.stringify(this.iReflectData));
    this.Collectionservice.PostUpdateLotTransaction(fileData).subscribe(
      (res) => {
        if (res.body !== undefined && res.body !== null) {
          debugger;
          this.toastr.success("Saved successfully.");
          var old_selcategoryid =0;
          if(this.projetdefid == this.automailprojectid && this.categorylist.length>0){
             old_selcategoryid = this.categorylist.filter(
              (x) => x.categoryname == this.old_category
            )[0].categoryid;
          }
          if (
            this.projetdefid == this.automailprojectid &&
            this.stageorder == 2 &&
            old_selcategoryid != this.selectedcategoryid
          ) {
            let fileData = new FormData();
            fileData.append("model", JSON.stringify(this.movemessagefields));
            this.Collectionservice.movemessage(fileData).subscribe(
              (res1) => {
                this.SpinnerService.hide();
                if (res1.body !== undefined && res1.body !== null) {
                  if (res1.body[0] != "Mailid not exist") {
                    this.toastr.success("Successfully mail moved to folder");
                  } else {
                    this.toastr.error(res1.body[0]);
                  }
                }
              },
              (error) => {
                this.SpinnerService.hide();
                this.toastr.error("Error in moving mail details");
              }
            );
          } else {
            this.SpinnerService.hide();
          }
          if (mode == "skip") {
            this.reAllocateModalRef.hide();
          }
          if (mode === "dup") this.commentsPopUpModalRef.hide();
          if (mode == "accept") {
            if(this.workAreaPopUpModalRef ) this.workAreaPopUpModalRef.hide();
          }
          if(this.re_area == true && this.re_btn == true){
            this.re_area = false; 
            this.re_btn = false;
            this.joblststageorder("onload");           
          }else{
           this.workarea_checkin('','exit');
           if(this.commentsPopUpModalRef) this.commentsPopUpModalRef.hide();
          if(this.stagename.toString()== "Bid Entry") {          
            this.transactionid=0;this.jobworkflowid=0;
            this.be_area=false;
            this.joblststageorder("afterload");
          }else{
            this.dialogRef.close();
            this.joblststageorder("onload");
          }
          
           
          }
          
        }
      },
      (err) => {
        this.SpinnerService.hide();
        this.toastr.error("Error in saving lot details");
      }
    );
  }
  /*calculateUniqueAgentstages(): { key: string; count: number }[] {
    const agentstageCounts: { [key: string]: number } = {};

    // Count occurrences of each agentstage
    this.errorlst.forEach(item => {
      const agentstage = item.agentstage;
      agentstageCounts[agentstage] = (agentstageCounts[agentstage] || 0) + 1;
    });

    // Convert to an array of objects with key and count
    const result = Object.keys(agentstageCounts).map(key => ({ key, count: agentstageCounts[key] }));

    // Sort the array in descending order based on count
    result.sort((a, b) => b.count - a.count);

    return result;
  }*/
 // Monicaa
 calculateUniqueAgentstages(lotid): { key: string; count: number }[] {
  const agentstageCounts: { [key: string]: number } = {};
  var loterrorlist = this.errorlst.filter(x=>x.lottitle == lotid);
  // Count occurrences of each agentstage
  loterrorlist.forEach(item => {
    const agentstage = item.agentstage;
    agentstageCounts[agentstage] = (agentstageCounts[agentstage] || 0) + 1;
  });
  // Monicaa
  // Convert to an array of objects with key and count
  const result = Object.keys(agentstageCounts).map(key => ({ key, count: agentstageCounts[key] }));

  // Sort the array in descending order based on count
  result.sort((a, b) => b.count - a.count);

  return result;
}
  close() {
    this.workarea_checkin('','exit');
    this.dialogRef.close();
  }

  getlotmetadata(mode) {
    //this.SpinnerService.show();
    let input = [];
    input.push({ pwdid: this.projetdefid });
    this.dashboardservice.getlotmeta(input[0]).subscribe(
      (res) => {
        if (res.body !== undefined && res.body !== null) {
          this.metaall = res.body;
          this.joblststageorder(mode);
        }
      },
      (err) => {
        this.toastr.error(err);
      }
    );
  }

  joblststageorder(mode) {
    this.SpinnerService.show();
    const input = [];
    input.push({
      p_userid: +this.userid,
      p_projectdefinitionid: this.projetdefid,
    });
    this.dashboardservice.getProjectJobDetails(input[0]).subscribe(
      (res) => {
        debugger;
        if (
          res.body[1] !== undefined &&
          res.body[1] !== null &&
          JSON.parse(res.body[1][0]) !== null
        ) {
          this.stageorderlotlistorg=[];
          this.re_btn =false;
          this.stageorderlotlistorg = JSON.parse(res.body[1][0]);
          this.stageorderlotlist = this.stageorderlotlistorg.filter(
            (x) => x.userid == this.userid && x.stageorder == this.stageorder
          );
          if(this.stagename.toString()=="Bid Entry" && mode=="afterload"){
             this.transactionid=this.transactionid==0?this.stageorderlotlist[0].transactionid:this.transactionid;
            this.jobworkflowid=this.jobworkflowid==0?this.stageorderlotlist[0].jobworkflowid:this.jobworkflowid;
            if(this.stageorderlotlist[0].lotstatus=="R") this.getcheckin('onload');
           // this.select('S', this.stageorderlotlist[0]);
          }
          let item = this.stageorderlotlist.filter(x=> x.transactionid == this.transactionid);
          this.workarea_checkin(item,'checkin');
          if(mode == 'oncall_re'){
            this.errorrecord_pass[0].insert_p = 0;
            this.select('S',this.errorrecord_pass[0])
          }
       /*    this.stageorderlotlist.forEach((i) => {
            debugger;
            //var mdata= this.metaall.filter(o => o.lotid === i.lotid)[0];
            var mdata = i.lotmastermetafields;
            if (mdata != null) {
              mdata.forEach((j) => {
                if (j.FieldName == "Company Name") i.CompanyName = j.FieldValue;
                if (j.FieldName == "Type") i.Type = j.FieldValue;
                if (j.FieldName == "Frequency") i.Frequency = j.FieldValue;
                if (j.FieldName == "Ranking") i.Ranking = j.FieldValue;
                if (j.FieldName == "City") i.City = j.FieldValue;
                if (j.FieldName == "State") i.State = j.FieldValue;
                if (j.FieldName == "Project ID") i.ProjectID = j.FieldValue;
                if (j.FieldName == "URL") i.URL = j.FieldValue;
                if (j.FieldName == "Follow Up Date")
                  i.FollowUpDate = j.FieldValue;
              });
            }
          }); */

          //console.log(JSON.stringify(this.stageorderlotlist));
          /*const result = this.stageorderlotlist.map(item => {
        const obj =  this.metaall.find(o => o.lotid === item.lotid);
        return { ...item, ...obj };
      });
     if(result)this.stageorderlotlist=result;*/
          console.log(this.stageorderlotlist);
          if (mode == "notonload") {
            let arr = this.stageorderlotlist.filter(
              (x) => x.lotid == this.infoselectedlotid
            );
            this.infotable = false;
            this.show_infotable(arr[0]);
            this.SpinnerService.hide();
          }
        }
        this.SpinnerService.hide();
      },
      (error) => {
        this.toastr.error("Error in updating lot transaction");
      }
    );
  }

  select(mode, data) {
    debugger;
    if (mode === "M") {
      this.errorlst=[];
      this.re_btn = false;
       this.re_area = false;
       this.qa_corr_area = false;
       this.reset();
        this.errorrecord_pass = [];
      if (this.insertall === true) {
        this.accept_btn = true;
        this.insertall = false;
        // this.fileData.delete('model');
        this.stageorderlotlist.forEach((element) => {
          if (element.insert_p === 1) {
            debugger;
            var index = this.stageorderlotlist.findIndex(
              (p) => p.lotid == element.lotid
            );
            this.stageorderlotlist[index]["insert_p"] = 0;
          }
        });
      } else {
        this.insertall = true;
        this.accept_btn = false;
        //this.fileData.append('model', JSON.stringify(this.stageorderlotlist));
        this.stageorderlotlist.forEach((element) => {
          // var index=this.stageorderlotlist.findIndex(p => p.lotid == element.lotid);
          if (element.insert_p === 0) {
            // debugger;
            var index = this.stageorderlotlist.findIndex(
              (p) => p.lotid == element.lotid
            );
            this.stageorderlotlist[index]["insert_p"] = 1;
          }
        });
        console.log(this.fileData);
      }
    } else if (mode === "S") {
      if (data.insert_p === 1) {
        this.accept_btn = true;
        // data.insert_p = 0;
        var index = this.stageorderlotlist.findIndex(
          (p) => p.lotid == data.lotid
        );
        this.stageorderlotlist[index]["insert_p"] = 0;
        if(this.stagename.toString()=="Bid Entry"){
          var un_check_selected=[];
          un_check_selected =this.stageorderlotlist.filter(
            (p) => p.insert_p == 1
          );
        if(un_check_selected.length == 0){
         this.be_area=false; 
        }
        }
      } else {
        if(this.stagename.toString()=="Bid Entry"){
        var check_selected=[];
        check_selected =this.stageorderlotlist.filter(
          (p) => p.insert_p == 1
        );
       if(check_selected.length == 0){
        this.be_area=true; 
       }
        }
        this.accept_btn = false;

        var index = this.stageorderlotlist.findIndex(
          (p) => p.lotid == data.lotid
        );
        this.stageorderlotlist[index]["insert_p"] = 1;
        this.transactionid=data.transactionid;
        this.lotid=data.lotid;
        this.jobid=data.jobid;
      }
     
      let key = [];
      key = this.stageorderlotlist.filter((x) => x.insert_p == 1);
      if (key.length != 0 && key.length == 1 && this.stagename.toString()=="QA") {
        this.re_btn = true;
        this.loadrecorderror();
      }else if(key.length != 0 && key.length == 1 && this.stagename.toString()=="QA Correction"){
        this.qa_corr_area = true;
        this.stageorderlotlist.forEach((element) => {
          if (element.insert_p == 1) {
            this.errorrecord_pass.push(element);
          }
        });
        this.geterrorlst();
        this.getrecorderrorlst();
      } else {
       this.re_btn = false;
       this.re_area = false;
       this.qa_corr_area = false;
       this.reset();
       this.errorrecord_pass = [];
	     this.recorderrordetailslst = [];
		   this.errorlst = [];
      }
    }
  }
  show_infotable(job) {
    if (this.projetdefid == this.automailprojectid) {
      this.selectedcategoryid = this.categorylist.filter(
        (x) => x.categoryname == job.lotmaster_status
      )[0].categoryid;

      if (
        job.uniquemailid != null &&
        job.uniquemailid != undefined &&
        job.uniquemailid != ""
      ) {
        this.mailid = job.uniquemailid;
      } else {
        this.mailid = "";
      }
		   
		
	  /*  this.subject = job.subject;
      this.mailbody = job.body;
      this.from_user = job.from_user;
      this.rec_date = job.mailrecievedtime;*/

    }

    this.metadatalist = [];
    this.metadatalistorg = [];
    this.lotmetafields = [];
    console.log(job);
    debugger;
    if (this.infotable === false) {
      this.infotable = true;
      debugger;
      console.log(job.lotmastermetafields);
      if (
        job.lotmastermetafields != null &&
        job.lotmastermetafields.length > 0
      ) {
        this.infoselectedjob = job.jobtitle;
        this.infoselectedlot = job.title;
        this.infoselectedjobid = job.jobid;
        this.infoselectedlotid = job.lotid;
        //this.metadatalist=job.lotmastermetafields;

        job.lotmastermetafields.forEach((vals) => {
          if (vals.isexcelmeta === false) {
            this.lotmetafields.push({
              FieldName: vals.FieldName,
              FieldValue: vals.FieldName == 'Project ID' ? vals.FieldValue.toUpperCase() : vals.FieldValue,
              isexcelmeta: vals.isexcelmeta,
            });
          }
        });
        job.lotmastermetafields.forEach((vals) => {
          if (vals.isexcelmeta === false) {
            this.metadatalist.push(vals);
          }
        });
      }
    } else {
      this.infotable = false;
    }
  }

  loadstagedetails() {
    let inputvalue = [];
    debugger;
    if (this.jobstatus === "R") {
      let status = true;
    }
    inputvalue.push({
      p_jobid: this.jobid,
      p_jobstatus: true,
      p_userid: Number(localStorage.getItem("userid")),
      mode: "Withoutpagination",
    });
    this.dashboardservice.loadStageDetails(inputvalue[0]).subscribe((res) => {
      debugger;
      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.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';
          // }
        }
      } else {
        // this.dtitle = '';
        this.jsonObj_st = [];
        this.uniqueStagename = [];
        this.uniqueFilename = [];
        this.uniqueStagename_st = [];
        //    this.AssignedLotLoading_3 = true;
      }
    });
  }

  changeSelBack(eve) {
    this.selforward = "";
    this.selback = eve;
  }

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

  dashboardMove(template: TemplateRef<any>) {
    this.skiptitle_lst = [];
    let check = 0;
    //var isnotyts=false;
    this.stageorderlotlist.forEach((element) => {
      if (element.insert_p === 1) {
        /*  if(element.lotstatus!="R"){
      isnotyts=true;   
     } */
        this.skiptitle_lst.push(element.title);
        check = check + 1;
      }
    });
    if (check === 0) {
      this.toastr.error("Kindly select atleast one lot...");
      return;
    }
    /* if(isnotyts){
  this.toastr.error('Please select only "YTS" lot....');
return;
} */
    this.selback = "0";
    this.selforward = "0";
    this.allocatetype = "Reverse or Bypass Stage";
    this.backstage = [];
    for (let i = 0; i < this.stageorder - 1; i++) {
      this.backstage.push(this.stagelist[i]);
    }
    this.forwardstage = [];
    for (let i = this.stageorder; i < this.stagelist.length; i++) {
      this.forwardstage.push(this.stagelist[i]);
    }
    this.reAllocateModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName("modal-content");
    aa[0].classList.remove("modal-content");
  }
  /*dashboardMove(item, template: TemplateRef<any>) {
  debugger;
  this.skiptitle_lst =[];
  let check =0;
  this.stageorderlotlist.forEach(element => {
  if(element.insert_p ===1){
    this.skiptitle_lst.push(element.title);
  }else{
  check = check+1;
  }
  });

if(check === this.stageorderlotlist.length){
  this.toastr.error('Please select anyone lot...'); 
  return;
}
  this.selback = '0';
  this.selforward = '0';
  const sval = item.transactionid, sstatus = 2, 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.uniqueStagename_st;
  this.allocatetype = 'Skip stage';
  let array: any;
  array = val.split('~');
  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');
}*/
  getToOrder() {
    let toOrder = 0;
    let selmovelst = [];

    if (Number(this.selback) === 0 && Number(this.selforward) == 0) {
      this.toastr.error(
        "Please select anyone of the stage to move forward or backward"
      );
      return;
    }
    if (this.selback !== "") {
      this.stype = "B";
      // const index = this.stagelist.map(object => object.stageorder).indexOf(Number(this.selback));
      //toOrder = index + 1;
      toOrder = Number(this.selback);
    }
    if (this.selforward !== "") {
      console.log(JSON.stringify(this.selforward));
      this.stype = "F";
      toOrder = Number(this.selforward);
    }
    selmovelst.push(toOrder);
    selmovelst.push(this.stype);
    return selmovelst;
  }
  selMove() {
    debugger;
    let selmovelst = [];
    let calltype: any;
    selmovelst = this.getToOrder();
    this.stoorder = selmovelst[0];
    calltype = selmovelst[1];
    console.log("selmove");
    console.log(selmovelst);
    this.save(calltype, "skip", this.stoorder);
  }
  opencomment(template: TemplateRef<any>, type) {
    let pass_flag = 0;
    this.stageorderlotlist.forEach((element) => {
      if (element.insert_p == 1) {
        pass_flag = pass_flag + 1;
      }
    });
    if (pass_flag == 0) {
      this.toastr.error("Please select atleast one job....");
      return;
    }
    this.comments_header = "Comments";
    if (type === "dup") {
      this.buttonType = "Duplicate";
    }else if(type == 'Reject'){
      this.buttonType = "Reject";
    }
    this.command = true;
    this.comments = this.buttonType + " Comments";
    this.commentsPopUpModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName("modal-content");
    aa[0].classList.remove("modal-content");
  }
  OpenMetaData(template: TemplateRef<any>) {
    this.editlotmetadataPopUpModalRef = this.modalService.show(
      template,
      this.config
    );
    const aa = document.getElementsByClassName("modal-content");
    aa[0].classList.remove("modal-content");
  }
  AddMetaData() {
    debugger;
    let edit = false;var contains_alpha =false;
    var projectidval ='';
    /**Prject id exist check**/
  
    
/* const hasProjectId = this.metadatalist.some((m) => m.hasOwnProperty("Project ID"));
if (hasProjectId) {
  projectidval = this.metadatalist.filter(
      (m) => m.FieldName === "Project ID"
    )[0].FieldValue; 
} */
if(this.metadatalist.length>0){
  this.metadatalist.forEach((x) => {
    
                             if (x.FieldName == "Project ID") {
                              projectidval =x.FieldValue
                               }
    });
} 
    //check projectid pattern
    //const pattern = /^\d{6}[a-zA-Z0-9][a-zA-Z0-9]$/;
    if(projectidval !='' && projectidval !=null && projectidval !=undefined){
     var proid = projectidval.includes("-")?projectidval.split("-")[0]:projectidval;
      const pattern = /^\d{6}[a-zA-Z0-9]{1,2}$/;
      if (!pattern.test(proid)) {
        this.toastr.error ('Kindly check the projectid, it has exactly 8 digits, with the first 7 digits being numeric and the 8th digit being alphanumeric (either a number or a letter).');
        return;
            }
    }
 
    const job_1 = new Object({
      projectid:projectidval,
      lotid: this.infoselectedlotid,
    });
    const job_ = new Object({
      jobid: this.infoselectedjobid,
    });
    var meta_pass = true;
    if (this.projetdefid != this.projectid_not_unique){

    this.Collectionservice.getBylotProjectId(job_1).subscribe(
      (lotres) => {
        debugger;
        if (
          lotres !== undefined &&
          lotres !== null &&
          lotres.body[0] !== undefined &&
          lotres.body[0] !== null
        ) {

          var result=JSON.parse(lotres.body[0]);
          contains_alpha = /[a-zA-Z]/.test(projectidval);
          if(contains_alpha && this.projectid_iteration == this.projetdefid){
            if(result!=undefined && result!='' && result!=null && projectidval !='' && projectidval !=null && projectidval !=undefined  ){
              var exist_pid_count=result.length+1;
              if(exist_pid_count>0){
               var occuran=(exist_pid_count).toString().padStart(2,0)
               var iteration_pid=projectidval+"-"+occuran;
               result.forEach(i => {
                 if(i.projectid == iteration_pid){
                   exist_pid_count=exist_pid_count+1;
                   occuran=(exist_pid_count).toString().padStart(2,0)
                   iteration_pid=projectidval+"-"+occuran;
                 }   
               }); 
             }
            }else{
              iteration_pid=projectidval+"-"+"01";
            }
            projectidval=iteration_pid;
          }else{
            if(result!=undefined && result!='' && result!=null && projectidval !='' && projectidval !=null && projectidval !=undefined  ){
              if(result.length>=1){
                meta_pass = false;
                this.toastr.error('Project ID already exist.');
                return;
              }
            }
          }

          
        /*   if(result!=undefined && result!='' && result!=null && projectidval !='' && projectidval !=null && projectidval !=undefined  ){
            if(contains_alpha && this.projectid_iteration == this.projetdefid ){
              var exist_pid_count=result.length;
              if(exist_pid_count>0){
               var occuran=(exist_pid_count).toString().padStart(2,0)
               var iteration_pid=projectidval+"-"+occuran;
               result.forEach(i => {
                 var pid=i.projectid.includes("-")?i.projectid.split("-")[0]:i.projectid;
                 if(pid == iteration_pid){
                   exist_pid_count=exist_pid_count+1;
                   occuran=(exist_pid_count).toString().padStart(2,0)
                   iteration_pid=projectidval+"-"+occuran;
                 }   
               });
             }
             projectidval=iteration_pid;
             
            }
          } */
          }
          this.jobmasterservice.getLotByJobId(job_).subscribe(
            (lotres) => {
              if (
                lotres !== undefined &&
                lotres !== null &&
                lotres.body[0] !== undefined &&
                lotres.body[0] !== null
              ) {
                if (JSON.parse(lotres.body[0]).length > 0) {
                  this.job_lotlist = JSON.parse(lotres.body[0]);
                  this.metadatalistorg = this.job_lotlist.filter(
                    (e) => e.lotid == this.infoselectedlotid
                  )[0].lotmastermetafields;
                  /**map new key name**/
                  this.metadatalist.forEach((x) => {
                    if (Object.keys(x).indexOf("isupdated") !== -1) {
                      console.log("This key exists");
                      this.metadatalistorg.forEach((k) => {
                        let fieldvaluebk_count = 1;
                        let LAPSstage_count = 1;
                        for (var key in x) {
                          if (key.toString().includes("fieldvaluebk")) {
                            fieldvaluebk_count++;
                          }
                          if (key.toString().includes("LAPSstage")) {
                            LAPSstage_count++;
                          }
                        }
                        if (k.FieldName === x.FieldName) {
                          if (k.FieldValue !== x.FieldValue) {
                            edit = true;
                            x.isupdated = Number(x.isupdated) + 1;
                            x["fieldvaluebk" + fieldvaluebk_count] = k.FieldValue;
                            x["LAPSstage" + LAPSstage_count] = this.stagename;
                          }
                        }
                      });
                    } else {
                      console.log("This key does not exist");
                      this.metadatalistorg.forEach((k) => {
                        if (k.FieldName === x.FieldName) {
                          if (k.FieldValue !== x.FieldValue) {
                            edit = true;
                            x.isupdated = 1;
                            x.fieldvaluebk1 = k.FieldValue;
                            x.LAPSstage1 = this.stagename;
                          }
                        }
                      });
                    }
                  });
                  if (edit) {
                    this.metadatalistorg.forEach((e) => {
                      if (e.isexcelmeta === true) {
                        this.metadatalist.push(e);
                      }
                    });
                    this.ccjoburlmaster.jobid = this.infoselectedjobid;
                    this.ccjoburlmaster.lotid = this.infoselectedlotid;
                    this.ccjoburlmaster.option = "updatelot";
                    this.ccjoburlmaster.createdby = Number(this.userid);
                    this.ccjoburlmaster.lotmastermetafields = JSON.stringify(
                      this.metadatalist
                    );
                    let meta_key = true;
                    this.metadatalist.forEach((element) => {
                      if (element.FieldName == "Company Name") {
                        this.ccjoburlmaster.companyname = element.FieldValue;
                      } else if (element.FieldName == "Type") {
                        this.ccjoburlmaster.type = element.FieldValue;
                      } else if (element.FieldName == "Ranking") {
                        this.ccjoburlmaster.ranking = element.FieldValue;
                      } else if (element.FieldName == "Frequency") {
                        this.ccjoburlmaster.frequency = element.FieldValue;
                      } else if (element.FieldName == "City") {
                        this.ccjoburlmaster.city = element.FieldValue;
                      } else if (element.FieldName == "State") {
                        this.ccjoburlmaster.state = element.FieldValue;
                      } else if (element.FieldName == "Follow Up Date") {
                        this.ccjoburlmaster.followupdate = element.FieldValue;
                      } else if (element.FieldName == "Bid Date") {
                        if (
                          element.FieldValue != "" &&
                          element.FieldValue != null &&
                          element.FieldValue != undefined
                        ) {
                          this.ccjoburlmaster.biddate = element.FieldValue;
                        } else {
                          if (element.isrequired == true) {
                            meta_key = false;
                          }
                        }
                      } else if (element.FieldName == "Project ID") {
                        if (
                          element.FieldValue != "" &&
                          element.FieldValue != null &&
                          element.FieldValue != undefined
                        ) {
                          //this.ccjoburlmaster.projectid = element.FieldValue;
                          this.ccjoburlmaster.projectid = projectidval.toUpperCase();
                          this.projectcode=projectidval;
                        } else {
                          if (element.isrequired == true) {
                            meta_key = false;
                          }
                        }
                      } else if (element.FieldName == "URL") {
                        if (
                          element.FieldValue != "" &&
                          element.FieldValue != null &&
                          element.FieldValue != undefined
                        ) {
                          this.ccjoburlmaster.url = element.FieldValue;
                        } else {
                          if (element.isrequired == true) {
                            meta_key = false;
                          }
                        }
                      }else if(element.FieldName == 'Project Name'){
                        this.ccjoburlmaster.projectname=element.FieldValue;
                        this.projectname=  element.FieldValue;                   
                      }else if(element.FieldName == 'Bid Number'){
                        this.ccjoburlmaster.bidnumber=element.FieldValue;
                      }
                    });
                    if (!meta_key) {
                      this.toastr.error("Job meta should not be empty");
                    }
                    this.Collectionservice.PostCCLotMasterandtrans(
                      this.ccjoburlmaster
                    ).subscribe(
                      (res) => {
                        //if (res.body != null && res.body !== undefined) {
                          this.toastr.success("Lot updated successfully");
                          this.editlotmetadataPopUpModalRef.hide();
                          this.joblststageorder("notonload");
                          this.re_area = false;
                          this.re_btn = false;
                          //this.getlotmetadata('notonload');
                        //}
                      },
                      (error) => {
                        this.toastr.error("Error while doing the operation");
                      }
                    );
                  } else {
                    this.toastr.error("Kindly do changes");
                    return;
                  }  
                  
                }
              }
              },
              (error) => {
                this.toastr.error("Error in getting Chapter Master Records");
              });
          },
          (error) => {
            this.toastr.error("Error in getting Project ID Records");
          });
    }else{
      this.jobmasterservice.getLotByJobId(job_).subscribe(
        (lotres) => {
          if (
            lotres !== undefined &&
            lotres !== null &&
            lotres.body[0] !== undefined &&
            lotres.body[0] !== null
          ) {
            if (JSON.parse(lotres.body[0]).length > 0) {
              console.log(JSON.parse(lotres.body[0]))
              this.job_lotlist = JSON.parse(lotres.body[0]);
              this.metadatalistorg = this.job_lotlist.filter(
                (e) => e.lotid == this.infoselectedlotid
              )[0].lotmastermetafields;
              /**map new key name**/
              this.metadatalist.forEach((x) => {
                if (Object.keys(x).indexOf("isupdated") !== -1) {
                  console.log("This key exists");
                  this.metadatalistorg.forEach((k) => {
                    let fieldvaluebk_count = 1;
                    let LAPSstage_count = 1;
                    for (var key in x) {
                      if (key.toString().includes("fieldvaluebk")) {
                        fieldvaluebk_count++;
                      }
                      if (key.toString().includes("LAPSstage")) {
                        LAPSstage_count++;
                      }
                    }
                    if (k.FieldName === x.FieldName) {
                      if (k.FieldValue !== x.FieldValue) {
                        edit = true;
                        x.isupdated = Number(x.isupdated) + 1;
                        x["fieldvaluebk" + fieldvaluebk_count] = k.FieldValue;
                        x["LAPSstage" + LAPSstage_count] = this.stagename;
                      }
                    }
                  });
                } else {
                  console.log("This key does not exist");
                  this.metadatalistorg.forEach((k) => {
                    if (k.FieldName === x.FieldName) {
                      if (k.FieldValue !== x.FieldValue) {
                        edit = true;
                        x.isupdated = 1;
                        x.fieldvaluebk1 = k.FieldValue;
                        x.LAPSstage1 = this.stagename;
                      }
                    }
                  });
                }
              });
              if (edit) {
                this.metadatalistorg.forEach((e) => {
                  if (e.isexcelmeta === true) {
                    this.metadatalist.push(e);
                  }
                });
                this.ccjoburlmaster.jobid = this.infoselectedjobid;
                this.ccjoburlmaster.lotid = this.infoselectedlotid;
                this.ccjoburlmaster.option = "updatelot";
                this.ccjoburlmaster.createdby = Number(this.userid);
                this.ccjoburlmaster.lotmastermetafields = JSON.stringify(
                  this.metadatalist
                );
                let meta_key = true;
                this.metadatalist.forEach((element) => {
                  if (element.FieldName == "Company Name") {
                    this.ccjoburlmaster.companyname = element.FieldValue;
                  } else if (element.FieldName == "Type") {
                    this.ccjoburlmaster.type = element.FieldValue;
                  } else if (element.FieldName == "Ranking") {
                    this.ccjoburlmaster.ranking = element.FieldValue;
                  } else if (element.FieldName == "Frequency") {
                    this.ccjoburlmaster.frequency = element.FieldValue;
                  } else if (element.FieldName == "City") {
                    this.ccjoburlmaster.city = element.FieldValue;
                  } else if (element.FieldName == "State") {
                    this.ccjoburlmaster.state = element.FieldValue;
                  } else if (element.FieldName == "Follow Up Date") {
                    this.ccjoburlmaster.followupdate = element.FieldValue;
                  } else if (element.FieldName == "Bid Date") {
                    if (
                      element.FieldValue != "" &&
                      element.FieldValue != null &&
                      element.FieldValue != undefined
                    ) {
                      this.ccjoburlmaster.biddate = element.FieldValue;
                    } else {
                      if (element.isrequired == true) {
                        meta_key = false;
                      }
                    }
                  } else if (element.FieldName == "Project ID") {
                    if (
                      element.FieldValue != "" &&
                      element.FieldValue != null &&
                      element.FieldValue != undefined
                    ) {
                      this.ccjoburlmaster.projectid = element.FieldValue;
                    } else {
                      if (element.isrequired == true) {
                        meta_key = false;
                      }
                    }
                  } else if (element.FieldName == "URL") {
                    if (
                      element.FieldValue != "" &&
                      element.FieldValue != null &&
                      element.FieldValue != undefined
                    ) {
                      this.ccjoburlmaster.url = element.FieldValue;
                    } else {
                      if (element.isrequired == true) {
                        meta_key = false;
                      }
                    }
                  }else if(element.FieldName == 'Project Name'){
                    this.ccjoburlmaster.projectname=element.FieldValue;
                  }else if(element.FieldName == 'Bid Number'){
                    this.ccjoburlmaster.bidnumber=element.FieldValue;
                  }
                });
                if (!meta_key) {
                  this.toastr.error("Job meta should not be empty");
                }
                this.Collectionservice.PostCCLotMasterandtrans(
                  this.ccjoburlmaster
                ).subscribe(
                  (res) => {
                    if (res.body != null && res.body !== undefined) {
                      this.toastr.success("Lot updated successfully");
                      this.editlotmetadataPopUpModalRef.hide();
                      this.joblststageorder("notonload");
                      this.re_area = false;
                      this.re_btn = false;
                      //this.getlotmetadata('notonload');
                    }
                  },
                  (error) => {
                    this.toastr.error("Error while doing the operation");
                  }
                );
              } else {
                this.toastr.error("Kindly do changes");
                return;
              }  
              
            }
          }
          },
          (error) => {
            this.toastr.error("Error in getting Chapter Master Records");
          });
    }
 
  }
  showmail() {
    //this.mail_url="https://outlook.office.com/mail/inbox/id/AAQkAGNlOWI1ZWNmLThhMGUtNGE5OC05ZTE0LWE4YWU1YzU5NDYxYgAQAJO7fzWIcU4Prxkl9fhRCNg%3D";
    this.mail_url =
      this.mail_parenturl_start + this.mailid + this.mail_parenturl_end;
    window.open(this.mail_url);
  }


  //record error start
  
    sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }

  openrecorderror() {
    debugger;
    this.re_area =!this.re_area;
    if(this.re_area == true){
      this.loadrecorderror();
    }else{
      // this.errorrecord_pass = [];
      // this.errorremark = "";
      // this._qaremarkselected = [];
      // this.output_file_upload.nativeElement.value = "";
      // this.input_file_upload.nativeElement.value = "";
      // this.btnqa = false;
      // this.qaremark = false;
      // this.recorderrorid = "";
      // this.btn = "Save";
      // this.file_hide = true;
      // this.uploaded_filename = "";
      // this.errorlst = [];
      // this.qaremarklst = [];
      this.re_btn =true;
      this.reset();
    }
    // let recorderrorlst: any = [];
    // this.stageorderlotlist.forEach((element) => {
    //   if (element.insert_p == 1) {
    //     recorderrorlst.push(element);
    //   }
    // });
    // //getcheckin before opening the record error
    // if (
    //   recorderrorlst[0].lotstatus == "YTS" ||
    //   recorderrorlst[0].lotstatus == "R"
    // ) {
    //   let fileData = new FormData();
    //   fileData.append("tranid", recorderrorlst[0].transactionid.toString());
    //   fileData.append("userid", this.userid.toString());
    //   fileData.append("lotstatus", "P");
    //   fileData.append("p_option", "checkin");
    //   fileData.append(
    //     "jobworkflowid",
    //     recorderrorlst[0].jobworkflowid.toString()
    //   );
    //   this.dashboardservice.getCheckincur(fileData).subscribe(
    //     (res) => {
    //       this.loadJobDetails();
    //     },
    //     (error) => {
    //       this.toastr.error("Error in updating lot transaction");
    //     }
    //   );
    // }
    // const dialogConfig1 = new MatDialogConfig();
    // dialogConfig1.disableClose = true;
    // dialogConfig1.autoFocus = true;
    // dialogConfig1.data = {
    //   tranid: recorderrorlst[0].transactionid,
    //   title: "Error Record",
    //   jobworkflowid: recorderrorlst[0].jobworkflowid,
    //   lotid: recorderrorlst[0].lotid,
    //   status: recorderrorlst[0].lotstatus,
    //   projectcode: recorderrorlst[0].projectcode,
    //   biddate: recorderrorlst[0].biddate,
    //   joburl: recorderrorlst[0].joburl,
    //   moveback: recorderrorlst[0].moveback,
    //   jobid: recorderrorlst[0].jobid,
    //   projetdefid: recorderrorlst[0].projectdefinitionid,
    //   stageorder: recorderrorlst[0].stageorder,
    //   stagename: recorderrorlst[0].stagename_alias,
    //   id: recorderrorlst[0].uniquemailid,
    //   parentid: recorderrorlst[0].parentmailid,
    //   lotmaster_status: recorderrorlst[0].lotmaster_status,
    //   subject: recorderrorlst[0].subject,
    //   from: recorderrorlst[0].from_user,
    //   body: recorderrorlst[0].body,
    //   recdate: recorderrorlst[0].mailrecievedtime,
    //   jobtitle: recorderrorlst[0].jobtitle,
    //   lottitle: recorderrorlst[0].title,
    //   uniqueStageTitles: this.uniqueStageTitles,
    //   categorylist: this.categorylist,
    //   selectedcategoryid: this.selectedcategoryid,
    //   stagelist: this.stagelist,
    //   old_category: this.old_category,
    // };
    // const dialogRef1 = this.dialog1.open(
    //   ErrorrecordpopoupComponent,
    //   dialogConfig1
    // );
    // dialogRef1.afterClosed().subscribe(
    //   //  data => this.fn_LoadProjectJobDetails(this.projectid, this.projectname)
    //   (data) => {
    //     this.joblststageorder("onload");
    //     this.key_re = false;
    //   }
    // );
  }


  //  get_recorderrorcount():any{
  //   // let pass = [];
  //   this._reselectedlot = [];
  //   this.re_count =[];
  //   debugger;
  //   this.stageorderlotlist.forEach((element) => {
  //     if (element.insert_p == 1) {
  //       this._reselectedlot.push(element);
  //     }
  //   });

  //   const formdata = new FormData();
  //   formdata.append(
  //     "tranid",
  //     this._reselectedlot[0].transactionid.toString()
  //   );
  //   formdata.append("lotid", this._reselectedlot[0].lotid.toString());
  //   formdata.append("jobid", this._reselectedlot[0].jobid.toString());
  //   formdata.append("mode", "count");
  //   this.dashboardservice.recorderror(formdata).subscribe(res=>{
  //     this.re_count =JSON.parse(res.body[0]);
  //     return this.re_count[0].count;
  //   },error=>{
  //     this.toastr.error('Error while getting the Record error count...');
  //   })
  // }
  loadrecorderror() {
    debugger;
    this.errorrecord_pass = [];
    this.errorremark = "";
    this._qaremarkselected = [];
    this.output_file_upload.nativeElement.value = "";
    this.input_file_upload.nativeElement.value = "";
    this.btnqa = false;
    this.qaremark = false;
    this.recorderrorid = "";
    this.btn = "Save";
    this.file_hide = true;
    this.uploaded_filename = "";
    this.errorlst = [];
    this.qaremarklst = [];

    this.stageorderlotlist.forEach((element) => {
      if (element.insert_p == 1) {
        this.errorrecord_pass.push(element);
      }
    });

  /*   let  multiple_tranid :string = "";
    this.errorrecord_pass.forEach(element => {
      if(multiple_tranid == ""){
        multiple_tranid = element.transactionid.toString();
      }else{
        multiple_tranid =multiple_tranid + ','+element.transactionid.toString();
      }
    }); */

    const formdata = new FormData();
    formdata.append("tranid",this.errorrecord_pass[0].transactionid.toString());
   //formdata.append("multiple_tranid",multiple_tranid);
    formdata.append("lotid", this.errorrecord_pass[0].lotid.toString());
    formdata.append("jobid", this.errorrecord_pass[0].jobid.toString());
    formdata.append("mode", "get");

    this.dashboardservice.recorderror(formdata).subscribe((res) => {
      if (
        res.body != null &&
        res.body != undefined &&
        res.body != ""
      ) {
        this.recorderrordetailslst = [];
        this.recorderrordetailslst = JSON.parse(res.body);
        console.log("recorderrordetailslst", this.recorderrordetailslst);
        this.geterrorlst();
        this.getrecorderrorlst();
      }
    });
  }

  geterrorlst() {
    // this.errorservice.Get_Errorlst(this.lotid,this.transactionid,this.jobid).subscribe(res=>{
    this.errorservice.Get_Errorlst().subscribe(
      (res) => {
        debugger;
        if (res.body != null && res.body != "" && res.body != undefined) {
          this.qaremarklst = [];
          this.qaremarklst = res.body;
        }
      },
      (error) => {
        this.toastr.error("Error while getting the QA Error list.");
      }
    );
  }

  getrecorderrorlst() {
    this.errorlst = [];
    const formData = new FormData();
    formData.append(
      "tranid",
      this.errorrecord_pass[0].transactionid.toString()
    );
    formData.append("lotid", this.errorrecord_pass[0].lotid.toString());
    formData.append("jobid", this.errorrecord_pass[0].jobid.toString());
    formData.append("mode", "select");
    this.dashboardservice.recorderror(formData).subscribe(
      (res) => {
        debugger;
        if (res.body != "" && res.body != undefined && res.body != null) {
          this.errorlst = JSON.parse(res.body);
          console.log('errorlst',this.errorlst);
        }
      },
      (error) => {
        this.toastr.error("Error while getting record error list.");
      }
    );
  }

  remarks() {
    this.qaremark = !this.qaremark;
  }

  upload_file(item, file: any) {
    debugger;
     this.input_upload = item;
     this.errorlst.forEach(element => {
      if(element.errorid == this._qaremarkselected[0].errorid){
        if(element.in_files != null){
          element.in_files.forEach(item_in => {
            for(let i =0;i<item.length;i++){
              if(item_in.filename == item[i].name){
                //gokul
               // this.output_file_upload.nativeElement.value = "";
                this.input_file_upload.nativeElement.value = "";
                this.input_upload = [];
                this.toastr.error("Already image file name is exist in the same error type. Please use different image file name.");
              }
            }
          });
        }
      }
     });
     //this.file = file.target.files[0];
  }

  upload_outfile(item, file: any) {
    debugger;
     this.output_upload = item;
    // this.file = file.target.files[0];
    this.errorlst.forEach(element => {
      if(element.errorid == this._qaremarkselected[0].errorid){
        if(element.out_files != null){
        element.out_files.forEach(item_in => {
          for(let i =0;i<item.length;i++){
            if(item_in.filename == item[i].name){
              //gokul
              this.output_file_upload.nativeElement.value = "";
             // this.input_file_upload.nativeElement.value = "";
              this.output_upload = [];
              this.toastr.error("Already image file name is exist in the same error type. Please use different image file name.");
            }
          }
        });
      }
      }
     });
  }

  save_recorderror() {
    debugger;
    if (this._qaremarkselected.length == 0 && this.nilerror) {
      this.toastr.error("Please fill the mantory field.");
      return;
    }
    if (
      this.input_upload.length != 0 &&
      this.input_upload.length != undefined &&
      this.input_upload.length != null
    ) {
      for(let i = 0 ;  this.input_upload.length >i;i++){
        if (+this.input_upload[i].size > 1000000) {
          this.toastr.error("Please Input Files less than 1 Mb size file.");
          return;
        }
      }
      for(let i = 0 ;  this.output_upload.length >i;i++){
        if (+this.output_upload[i].size > 1000000) {
          this.toastr.error("Please Output Files less than 1 Mb size file.");
          return;
        }
      }
      
    }
    let bidentry = '';
    bidentry = this.recorderrordetailslst[0].bidentry == null ? 0 : this.recorderrordetailslst[0].bidentry;

    let qacheckagenetid = '';
    qacheckagenetid = this.recorderrordetailslst[0].qacheckagenetid == null ? this.userid : this.recorderrordetailslst[0].qacheckagenetid;
	
    let productiondate = '';
    productiondate = this.recorderrordetailslst[0].productiondate == null ? '' :this.recorderrordetailslst[0].productiondate.toString("yyyddmm");
 
    let biddate ='';
    biddate = this.recorderrordetailslst[0].biddate == null ? '' : this.recorderrordetailslst[0].biddate.toString("yyyddmm");

    let qadate = '';
    qadate = this.recorderrordetailslst[0].qadate == null ? '': this.recorderrordetailslst[0].qadate.toString("yyyddmm");

    let productionagent = '';
    productionagent =  this.recorderrordetailslst[0].agentnameid == null ? 0 : this.recorderrordetailslst[0].agentnameid;
    
    let errorid='0'; let errortype='';
    if(this._qaremarkselected.length>0){
    errorid=this._qaremarkselected[0].errorid;
    errortype=this._qaremarkselected[0].errortype;}

    const formData = new FormData();
    formData.append("errorid", errorid);
    formData.append("errortype", errortype);
    formData.append("remarks", this.errorremark);
    formData.append("projectdefinitionid",this.recorderrordetailslst[0].workflowid);
    formData.append("projectid", this.recorderrordetailslst[0].projectid);
    formData.append("productionagent",productionagent);
    formData.append("jobtitle",  this.errorrecord_pass[0].jobid.toString());
    formData.append("qaagent", qacheckagenetid);
    formData.append("lottitle", this.errorrecord_pass[0].lotid.toString());
    formData.append("productiondate",productiondate);
    formData.append("qadate",qadate);

    // if(i=0){
    //   temp =this.output_upload[i].name+',';
    // }else if(i = this.output_upload.length-1){
    //   temp = temp +this.output_upload[i].name;
    // }else{
    //   temp = temp +this.output_upload[i].name+',';
    // }
    let filename = [];
    let temp ="";
    for(let i = 0 ;  this.input_upload.length >i;i++){
      filename.push({'filename':this.input_upload[i].name});
    } 
    formData.append("input_filename",JSON.stringify(filename));
    // formData.append("in_filename",temp);

    filename =[];
    temp='';
    for(let i = 0 ;  this.output_upload.length >i;i++){
      filename.push({'filename':this.output_upload[i].name});
    } 
    formData.append("output_filename",JSON.stringify(filename));
    // formData.append("out_filename",temp);


    for(let i = 0 ;  this.input_upload.length >i;i++){
      formData.append("input_files",this.input_upload[i]);

    } 
    for(let i = 0 ;  this.output_upload.length >i;i++){
      formData.append("output_files",this.output_upload[i]);
    }   
    formData.append("createdby", this.userid);
    formData.append("biddate",biddate
    );

    formData.append("jobid", this.jobid.toString());
    formData.append("bidentryid", bidentry.toString());
    formData.append("transid",  this.errorrecord_pass[0].transactionid.toString());
    // formData.append("input_file", ;
    if(!this.nilerror)this.btn= "Save";
    if (this.btn == "Save") {
      formData.append("mode", "add");
    } else {
      formData.append("recorderrorid", this.recorderrorid);
      formData.append("updatedby", this.userid);
      formData.append("mode", "edit");
      if(this.in_files.length != 0)
        formData.append("bal_in_files", JSON.stringify(this.in_files));
      
      if(this.out_files!=0)
        formData.append("bal_out_files", JSON.stringify(this.out_files));

      formData.append("saved_filename", this.uploaded_filename);
    }
    console.log(JSON.stringify(formData))
    this.dashboardservice.recorderror(formData).subscribe(
      (res) => {
        debugger;
        if (
          res.body.msg != null &&
          res.body.msg != undefined &&
          res.body.msg != ""
        ) {
          if (res.body.msg == "success") {
            if (this.btn == "Save") {
              this.toastr.success("Record Error Successfully inserted.");
            } else {
              this.toastr.success("Record Error Successfully Updated.");
            }
            console.log('bef',this.userid);
          console.log('bef',this.stageorder);
            this.getrecorderrorlst();
            this.joblststageorder('oncall_re'); 
            this.reset();
          }
        } else {
          console.log(res);
          this.toastr.info(res.body.message);
        }
      },
      (error) => {
        this.toastr.error("Error while Saving/Updating the record error.");
      }
    );
  }

  reset() {
    this.errorremark = "";
    this._qaremarkselected = [];
    this.output_file_upload.nativeElement.value = "";
    this.input_file_upload.nativeElement.value = "";
    this.btnqa = false;
    this.qaremark = false;
    this.recorderrorid = "";
    this.btn = "Save";
    this.file_hide = true;
    this.uploaded_filename = "";
    this.input_upload = "";
    this.file = "";
    this.errorremarkslst = [];
    this.in_files =[];
    this.out_files = [];
  }

  onItemDeSelect(item,mode) {
    this.errorremark="";
    if(mode == 'recorderror')
    {
    if (this.btn != "Update" && this.btnqa == false) {
      this.btnqa = !this.btnqa;
    } else if (this.btn != "Update" && this.btnqa == true) {
      this.btnqa = !this.btnqa;
    } else if (this.btn == "Update" && this.btnqa == false) {
      this.btnqa = true;
    }
  }else if( mode == 'remarks'){

  }
  }
  onItemSelect(item,mode) {
    if(mode == 'recorderror')
    {
      this._errorremarkselected = [];
    if (this.btn != "Update" && this.btnqa == false) {
      this.btnqa = !this.btnqa;
    } else if (this.btn != "Update" && this.btnqa == true) {
      this.btnqa = true;
    } else if (this.btn == "Update" && this.btnqa == false) {
      this.btnqa = true;
    }
    //duplicate check for record error
    // if (this.btn != "Update") {
    //   if (this.errorlst.length != 0) {
    //     let index = this.errorlst.findIndex(
    //       (x) => x.errorid == this._qaremarkselected[0].errorid
    //     );
    //     if (index != -1) {
    //       this.toastr.error(
    //         "Please select different Error Type. Its already added."
    //       );
    //       this.reset();
    //       return;
    //     }
    //   }
    // }

    this.get_errorremark(item.errorid,'');
  }else if(mode == 'remarks'){
    this.errorremark = item.errorremarks;
  }
  }

  get_errorremark(errorid,value){
    let item :any =[];
    item.push({errorid: errorid});
    this.errorremarksservice.GetbyErrorid(item[0]).subscribe(res=>{
      this.errorremarkslst = [];
      if(res.body != null && res.body != undefined && res.body != ''){
          this.errorremarkslst = res.body;
          if(value != ''){
            this.edit(value,'oncall');
          }
      }
    },error=>{
      this.toastr.error('error while getting the error remarks')
    })
  }

  async edit(item,mode) {
    debugger;
    this.in_files = [];
    this.out_files=[];
    console.log('errorlst',item);
    this.recorderrorid = item.recorderrorid;
    this._qaremarkselected = this.qaremarklst.filter(
      (x) => x.errorid == item.errorid
    );
    if(mode=='onclick'){
    await this.get_errorremark(item.errorid,item);
    }
    
    if(this.errorremarkslst != 0){
      this._errorremarkselected = this.errorremarkslst.filter((x)=>x.errorremarks == item.remarks);
      this.btnqa = true;
    }else{
      this._errorremarkselected =[];
      this.errorremark = item.remarks;
      this.btnqa = true;
    }
    // this.errorfile = item.filename;
   
    this.btn = "Update";
    
    if (
      item.filename != "" &&
      item.filename != null &&
      item.filename != undefined
    ) {
      this.file_hide = false;
      this.uploaded_filename = item.filename;
    } else {
      this.file_hide = true;
    }

    if(item.in_files != '' && item.in_files !=null && item.in_files != undefined){
     
      this.in_files = item.in_files;
    }
    if(item.out_files != '' && item.out_files !=null  && item.out_files != undefined ){
      
      this.out_files =item.out_files;
    }
 
    console.log('in',this.in_files);
    console.log('out',this.out_files);
  }
  delete(item) {
    this.dialogService
      .addDialog(CommondialogComponent, {
        title: "Please Confirm",
        message: "Are you sure you want to delete this record error ?",
        hclass: "modelsuccess",
        oktext: "Yes",
        canceltext: "No",
        okshow: true,
        cancelshow: true,
      })
      .subscribe((isConfirmed) => {
        if (isConfirmed) {
          debugger;
          const formData = new FormData();
          formData.append("recorderrorid", item.recorderrorid);
          formData.append("projectdefinitionid", item.workflowid);
          formData.append("jobtitle", this.jobid.toString());
          formData.append("lottitle", this.lotid.toString());
          formData.append("errorid", item.errorid);
          // formData.append('updatedby',this.userid);
          // formData.append('active','1');
          formData.append("mode", "delete");
          this.dashboardservice.recorderror(formData).subscribe(
            (res) => {
              debugger;
              if (
                res.body.msg != null &&
                res.body.msg != undefined &&
                res.body.msg != ""
              ) {
                if (res.body.msg == "success") {
                  this.toastr.success("Record error deleted successfully.");
                  this.reset();
                  this.getrecorderrorlst();
                  this.joblststageorder('oncall_re'); 
                }
              } else {
                console.log(res);
                this.toastr.info(res.body.message);
              }
            },
            (error) => {
              this.toastr.error("Error while deleting the record error.");
            }
          );
        }
      });
  }

  delete_file(file) {
    this.dialogService
      .addDialog(CommondialogComponent, {
        title: "Please Confirm",
        message: "Are you sure you want to delete this file ?",
        hclass: "modelsuccess",
        oktext: "Yes",
        canceltext: "No",
        okshow: true,
        cancelshow: true,
      })
      .subscribe((isConfirmed) => {
        if (isConfirmed) {
          // this.Delete(item);
          let item = this.errorlst.filter(
            (x) => x.recorderrorid == this.recorderrorid
          );
          const formData = new FormData();
          formData.append("recorderrorid", item[0].recorderrorid);
          formData.append("projectdefinitionid", item[0].workflowid);
          formData.append("jobtitle", this.jobid.toString());
          formData.append("lottitle", this.lotid.toString());
          formData.append("mode", "delete");
          formData.append("errorid", item[0].errorid);
          formData.append("updatedby", this.userid);
          formData.append("saved_filename", "file_delete");
          formData.append("bal_in_files", JSON.stringify(item[0].in_files));
          formData.append("bal_out_files", JSON.stringify(item[0].out_files));

          if(file.type == 'IN'){
            file.mode ='delete';
            let temp = [];
            temp.push(file)
            formData.append("input_filename", JSON.stringify(temp));
           
          }else if(file.type == 'OUT'){
            file.mode ='delete';
            let temp = [];
            temp.push(file)
            formData.append("output_filename", JSON.stringify(temp));
          }
          this.dashboardservice.recorderror(formData).subscribe(
            (res) => {
              debugger;
              if (
                res.body.msg != null &&
                res.body.msg != undefined &&
                res.body.msg != ""
              ) {
                if (res.body.msg == "success") {
                  this.toastr.success("File deleted successfully.");
                  this.reset();
                  this.file_hide = true;
                  this.getrecorderrorlst();
                }
              } else {
                console.log(res);
                this.toastr.info(res.body.message.toString());
              }
            },
            (error) => {
              this.toastr.error("Error while deleting files the record error.");
            }
          );
        }
      });
  }
  workarea_checkin(item,mode){
    var data =[];
    if(mode == 'checkin'){
     data =[{
      userid:Number(this.userid),
      workareastatus: 1,
      lotid:this.lotid,
      jobid:this.jobid,
      transid: this.transactionid,
      projectdefinitionid:this.projetdefid,
      stagename_alias:this.stagename,
      lottitle:item[0].title,
      jobtitle:item[0].jobtitle,
      transstatus:item[0].lotstatus,
      lotstatus:item[0].lotmaster_status,
      createdby:Number(this.userid)
    }];
    }else{
       data =[{
        userid:Number(this.userid),
        workareastatus: 0,
        lotid:0,
        jobid:0,
        transid:0,
        projectdefinitionid:0,
        stagename_alias:'',
        lottitle:'',
        jobtitle:'',
        transstatus:'',
        lotstatus:'',
        updatedby:Number(this.userid)
      }];
    }
    this.Collectionservice.workarea_checkin(data[0]).subscribe(res=>{
      //console.log('result',res);
      if(res.body != '' && res.body != null && res.body != undefined){
        
      }
    });
  console.log('workarea',item);
  }

 download_files(item) {
    debugger;
    console.log("files", item);
    let filename = item.filename;
    this.recorderrorservice
      .Recorderrorfile_Download(this.projetdefid, item.path)
      .subscribe(
        (res) => {
          if (res.file_ != null && res.file_ != "" && res.file_ != undefined) {
            var content = res.file_;
            let objectURL = "data:application/octet-stream;base64," + res.file_;
            saveAs(objectURL, filename);
          } else {
            this.toastr.error("File not Found.");
          }
        },
        (error) => {
          this.toastr.error("Error while getting data");
        }
      );
  }
  @HostListener('window:beforeunload', ['$event'])
  unloadhandler(event: Event) : void {
    this.workarea_checkin('','checkout');
  }
}
