import { Component, OnInit,TemplateRef,ViewChild,HostListener} from '@angular/core';
import { FormGroup, Validators, FormBuilder, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import { Ccjoburlmaster ,BidNumberMaster} from './collectionprocess';
import { JobmasterService } from 'src/app/jobconfiguration/jobmaster/jobmaster.service';
import { JobdefinitionService } from 'src/app/jobconfiguration/jobdefinition/jobdefinition.service';
import { ToastrService } from 'ngx-toastr';
import { CollectionprocessService } from '../collectionprocess/collectionprocess.service';
import {  BsModalService, BsModalRef, ModalOptions } from 'ngx-bootstrap/modal';
import { ActivatedRoute ,Router, NavigationExtras} from '@angular/router';
import { DialogService } from 'ng2-bootstrap-modal';
import { CommondialogComponent } from '../../Shared/commondialog/commondialog.component';
import {DashboardService } from '../../dashboard/dashboard.service';			
import { JobmetaService } from '../../masters/jobmeta/jobmeta.service';	
import { LotMaster} from 'src/app/jobconfiguration/jobmaster/jobmaster';
import { NgxSpinnerService } from 'ngx-spinner';						  
import { error, timeStamp } from 'console';
import { DatePipe } from '@angular/common';
import { environment } from 'src/environments/environment';
import { exists } from 'fs';
@Component({
  selector: "app-collectionprocess",
  templateUrl: "./collectionprocess.component.html",
  styleUrls: ["./collectionprocess.component.css"],
})
export class CollectionprocessComponent implements OnInit {
  @ViewChild("worlAreaPopUpTemplate", { static: true })
  worlAreaPopUpTemplate: TemplateRef<any>;
  selectedlotitem = {} as LotMaster;
  showcomplete = true;
  joburlForm: FormGroup;
  submitted = false;
  postresult: boolean;
  jobs: any = [];
  lots: any = [];
  _joblist: any = [];
  search: any;
  joblist = false;
  key = "jobname";
  userid: any;
  //userid: string = localStorage.getItem('userid');
  jobid: number;
  entity: any;
  comments_header: any;
  buttonType: any;
  comments: any;
  calltype: any;
  assign_area: boolean = false;
  selected_categorygroup: number = 0;
  cflag: any;
  workAreaPopUpModalRef: BsModalRef;
  dragHandle: any;
  textboxcss: any;
  text_width: number;
  config: ModalOptions = {
    backdrop: "static",
    keyboard: false,
    animated: true,
    class: "modal-dialog-centered",
    ignoreBackdropClick: true,
  };
  lotlist_output = [];
  lotlist = [];
  lotlist_filter = [];
  lotlistTmp = [];
  alllotdetails: any = [];
  uniqueStageTitles = [];
  lot_comments = [];
  mergedlot: number;
  transactionid: number;
  lotid = 0;
  selback = "";
  jobworkflowid: string;
  nextstagejobworkflowid: string;
  ddlLotListTypeSettings: {};
  _ddlProjecttypeSettings: {};
  _producttypeselected: any = [];
  textBoxTocuhed: boolean;
  jobProductTypeList: any[];
  jobsall: any = [];
  procomment: any;
  selectedlot: any[] = [];
  optiontoaddnewlot: string;
  isaddlot = false;
  metadataselectinputoptionflag = false;
  selectoptionlist = [];
  editselectoptionlist = false;
  editselectoption;
  metadata_checked: any = [];
  _ddlMetaSettings: any = [];
  updated_mailid: string;
  updated_parentid: string;
  addrecnotshoe = false;
  showbidnumber = false;
  ckeConfig = {
    allowedContent: false,
    forcePasteAsPlainText: true,
    font_names: "Arial;Times New Roman;Verdana",
    toolbarGroups: [
      { name: "document", groups: ["mode", "document", "doctools"] },
      { name: "clipboard", groups: ["clipboard", "undo"] },
      {
        name: "editing",
        groups: ["find", "selection", "spellchecker", "editing"],
      },
      { name: "forms", groups: ["forms"] },
      "/",
      { name: "basicstyles", groups: ["basicstyles", "cleanup"] },
      {
        name: "paragraph",
        groups: ["list", "indent", "blocks", "align", "bidi", "paragraph"],
      },
      { name: "links", groups: ["links"] },
      { name: "insert", groups: ["insert"] },
      "/",
      { name: "styles", groups: ["styles"] },
      { name: "colors", groups: ["colors"] },
      { name: "tools", groups: ["tools"] },
      { name: "others", groups: ["others"] },
      { name: "about", groups: ["about"] },
    ],
    removeButtons:
      "Source,Save,NewPage,Preview,Print,Templates,Cut,Copy,Paste,PasteText,PasteFromWord,Undo,Redo,Find,Replace,SelectAll,Scayt,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Strike,Subscript,Superscript,CopyFormatting,RemoveFormat,Outdent,Indent,CreateDiv,Blockquote,BidiLtr,BidiRtl,Language,Unlink,Anchor,Image,Flash,Table,HorizontalRule,Smiley,SpecialChar,PageBreak,Iframe,Maximize,ShowBlocks,About",
  };
  transactionid_pass: any;
  lotid_pass: any;
  projectdefinitionid_pass: any;
  userid_pass: any;
  jobid_pass: any;
  jobworkflowid_pass: any;
  frommyjob = false;
  lottitle: string;
  jobtitle: string;
  command = false;
  fromorder: number;
  toorder: number;
  orgpjid: string;
  orgurl: string;
  orgbit: string;
  assignedlotlist: any = [];
  assignedlotlistorg: any = [];
  loadnextlot = false;
  joblotexcel: any = [];
  showlotgrid = false;
  editlot = false;
  editable_joburl = "";
  editable_projid = "";
  jobMetaDataModalRef: BsModalRef;
  metadtalist1 = [];
  jobMetadata: any = [];
  categorylist: any = [];
  selectedfieldid: any;
  fieldvalue: any;
  selectedfieldname: any;
  job_lotlist: any;
  stagename: string;
  lotmastermetafields: any;
  jobmetalst: any = [];
  add_jobmetalst: any = [];
  jobMetadataorg: any = [];
  meta_pass = false;
  lotmeta: any = [];
  tojobwkflwid = 0;
  stageorder_pass: any;
  Addmetapopup: BsModalRef;
  lotMetadatapopup: BsModalRef;
  addmetaFrom: FormGroup;
  mail_url: string;
  mailid: string;
  companyname:string ='';
  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;
  projectid_iteration:number = environment.projectid_iteration;
  parentid: string;
  selectedcategoryid = 0;
  mailbody: string;
  subject: string;
  from_user: string;
  rec_date: string;
  stagelist_length: number = 0;
  newly_craeted_lot: number = 0;
  bidNumberPopUpModalRef: BsModalRef;
  p = 1;
  public searchText: string;
  itemsPerPage = 10;
  showall = true;
  showallstatus = false;
  solicitation: string;
  Project_name_search: string;
  bidlst: any = [];
  search_bidlst: any = [];
  bid_pass: boolean = true;
  bid_data = {} as BidNumberMaster;

  olua_area: boolean = false;
  selected_lots: any = [];
  insert_all: number = 0;
  update_meta_list = [];
  list_meta_vaild = [];
  projectdefinitionid: any;
  olua_lotmeta: any=[];
  mode: number = 0; //1=FROM MY JOB //2 NEWLY CREATED LOT LOAD
  collapse_excelmd : boolean =true;
  collapse_mandemd : boolean =true;
  collapse_nonmd : boolean =true;
  typemetaselectedItem:string='';
  constructor(
    private toastr: ToastrService,
    private formBuilder: FormBuilder,
    private collectionprocessservice: CollectionprocessService,
    private modalService: BsModalService,
    private jobdefinitionservice: JobdefinitionService,
    private jobmasterservice: JobmasterService,
    private route: ActivatedRoute,
    private router: Router,
    private dialogService: DialogService,
    private dashboardservice: DashboardService,
    private jobMetaService: JobmetaService,
    private SpinnerService: NgxSpinnerService,
    private datepipe: DatePipe
  ) {
    const navigation = this.router.getCurrentNavigation();
    const state = navigation.extras.state as {
      id: any;
      parentid: any;
      subject: any;
      from: any;
      body: any;
      recdate: any;
    };
    if (state !== null && state !== undefined) {
      debugger;
      this.mailid = state.id;
      this.parentid = state.parentid;
    }
  }
  ngOnInit(): void {
    this.textboxcss = {
      width: "82px",
      "margin-left": "-53px",
    };
    this.frommyjob = false;
    this.joburlForm = this.formBuilder.group({
      joburlid: [""],
      projectid: ["", [Validators.required]],
      job_url: ["", [Validators.required]],
      bitnumber: [""],
    });
    this.addmetaFrom = this.formBuilder.group({
      jobmeta: [""],
      projectdefinitionid: [""],
      inputtype: [""],
      isexcelmeta: [""],
      isrequired: [""],
      selectoption: [""],
    });
    this.userid = +localStorage.getItem("userid");
    this.ddlLotListTypeSettings = {
      singleSelection: true,
      idField: "lotid",
      textField: "title",
      allowSearchFilter: true,
    };
    this._ddlMetaSettings = {
      singleSelection: false,
      idField: "jobmetaid",
      textField: "jobmeta",
      itemsShowLimit: 7,
      allowSearchFilter: true,
    };
    //this.getAll(); //job title take
    //this.loadProductType();
    this.transactionid_pass = +this.route.snapshot.queryParamMap.get("tranid");
    this.lotid_pass = +this.route.snapshot.queryParamMap.get("lotid");
    this.projectdefinitionid_pass =
      +this.route.snapshot.queryParamMap.get("pdid");
    this.userid_pass = +this.route.snapshot.queryParamMap.get("userid");
    this.jobid_pass = +this.route.snapshot.queryParamMap.get("jobid");
    this.jobworkflowid_pass = +this.route.snapshot.queryParamMap.get("jwfid");
    this.stageorder_pass = +this.route.snapshot.queryParamMap.get("stageorder");
    this.mode = +this.route.snapshot.queryParamMap.get("m");

    if (this.jobid_pass != 0 && this.jobid_pass != undefined) {
      this.frommyjob = true;
      this.fn_LoadJoblistDetails(this.projectdefinitionid_pass); //job title
      this.olua_area =
        this.projectdefinitionid_pass == this.projectid_not_unique
          ? true
          : false;
      this.jobid = this.jobid_pass;
      this.transactionid = this.transactionid_pass;
      this.jobworkflowid = this.jobworkflowid_pass;
      this.projectdefinitionid = this.projectdefinitionid_pass;
      this.lotid = this.lotid_pass;
      if (this.lotid != 0 && this.lotid != null) {
        this.getlotmastermetavalue(this.lotid); //meta data taken from lotmaster
        this.loadJobDetails(this.lotid); //stage details
      }
      this.userid = this.userid_pass;
      if (this.olua_area == false) {
        this.getlotdeatils(); //alllotDetails,lottile,lot select
      }
      this.getassignedlot("load"); //assignedlotlist
      if (this.projectdefinitionid_pass == this.automailprojectid) {
        this.loadcategory();
        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.getmaildetailsbyid();
          this.mail_url =
            this.mail_parenturl_start + this.mailid + this.mail_parenturl_end;
          this.showmail();
        }
      } else {
        this.selectedcategoryid = -1;
      }
    }
    this.selectedfieldid = 0;
  }
  ngOnDestroy(): void {
    this.workarea_checkin("", "exit");
  }
  refresh(): void {
    this.router.navigate(["/ccstageprocess/collectionprocess"]).then(() => {
      window.location.reload();
    });
  }
  toggle_meta(s){
    if(s==1){
      this.collapse_excelmd=!this.collapse_excelmd;
    }else if(s==2){
      this.collapse_mandemd=!this.collapse_mandemd;
    }else if(s==3){
      this.collapse_nonmd=!this.collapse_nonmd;
    }

  }
  onCheckboxChange(value,name) {
    console.log(value)
    console.log(name)


    this.jobmetalst.forEach(element => {
      if(element.FieldName==name){
        element.FieldValue=value;
      }  
    });
    console.log(this.jobmetalst)
  }
  loadcategory() {
    this.collectionprocessservice.getCategory().subscribe(
      (res) => {
        debugger;
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.categorylist = JSON.parse(res.body[0]);
            }
          }
        }
      },
      (error) => {
        this.toastr.error("Error while getting category list");
        this.categorylist = [];
      }
    );
  }
  getassignedlot(type) {
    debugger;
    const input = [];
    input.push({
      p_userid: +this.userid,
      p_projectdefinitionid: this.projectdefinitionid_pass,
      p_jobid : this.assignedlotlist[0].jobid
    });
    this.dashboardservice.getProjectJobDetails(input[0]).subscribe((res) => {
      if (
        res.body[1] !== undefined &&
        res.body[1] !== null &&
        JSON.parse(res.body[1][0]) !== null
      ) {
        this.assignedlotlistorg = JSON.parse(res.body[1][0]);
        console.log("assignedlotlistorg", this.assignedlotlistorg);
        let item = [];
        if (this.olua_area == true && type != "addlot") {
          this.selected_lots = [];
          this.assignedlotlist = this.assignedlotlistorg.filter(
            (x) =>
              (x.lotstatus == "R" || x.lotstatus == "P") &&
              (x.userid == this.userid ||
                x.userid == null ||
                x.userid == undefined) &&
              x.stageorder == 1
          );

          if (type == "lot_compeleted" || type == "load") {
            debugger;

            this.jobid = this.assignedlotlist[0].jobid;
            this.jobworkflowid = this.assignedlotlist[0].jobworkflowid;
            this.transactionid = this.assignedlotlist[0].transactionid;
            this.projectdefinitionid =
              this.assignedlotlist[0].projectdefinitionid;
            this.userid = this.assignedlotlist[0].userid;
            this.stagename = this.assignedlotlist[0].stagename_alias;

            this.loadJobDetails(this.assignedlotlist[0].lotid);
            this.workarea_checkin("", "checkin");
            this.getlotdeatils();
          }
        } else {
          this.workarea_checkin("", "checkin");
          this.assignedlotlist = this.assignedlotlistorg.filter(
            (x) =>
              x.lotstatus == "R" &&
              x.userid == this.userid &&
              x.jobid == this.jobid &&
              x.stageorder == 1
          );

          //this.stagename=this.assignedlotlist[0].stagename_alias;
        }

        if (this.isaddlot && this.mode!=2) {
          console.log("assignedlotlist before", this.assignedlotlist);
          //decending sort
         /*  this.assignedlotlist.sort((a, b) => {
            return b.lotid - a.lotid;
          }); */
          //ascending sort
          this.assignedlotlist.sort((a, b) => {
            return a.lotid - b.lotid;
          });
          console.log("assignedlotlist after", this.assignedlotlist);
        } else if(this.mode==2){
          debugger;
          console.log("assignedlotlist before", this.assignedlotlist);
          console.log(this.isaddlot)
          console.log( "this.mode",this.mode)
          //sort newly created lot
          if(this.newly_craeted_lot!=0){
            var sort_assignedlotlist =  this.assignedlotlist.filter(x => x.lotid !== this.newly_craeted_lot).sort((a, b) => b.lotid - a.lotid);
            sort_assignedlotlist.unshift(this.assignedlotlist.find(x => x.lotid === this.newly_craeted_lot));
         this.assignedlotlist=[];
            this.assignedlotlist=sort_assignedlotlist;
          }else{
            this.assignedlotlist.sort((a, b) => {
              return b.lotid - a.lotid;
            });
          }
          console.log("assignedlotlist after", this.assignedlotlist);
        }else {
          console.log("assignedlotlist before", this.assignedlotlist);
          console.log("type",type);
          console.log(this.isaddlot)
          //ascending sort
          this.assignedlotlist.sort((a, b) => {
            return a.lotid - b.lotid;
          });
          console.log("assignedlotlist after", this.assignedlotlist);
        }
      }
      if (type == "complete") {
        if (this.assignedlotlist.length > 0) {
          let newlotData = new FormData();
          newlotData.append(
            "tranid",
            this.assignedlotlist[0].transactionid.toString()
          );
          newlotData.append("userid", this.userid.toString());
          newlotData.append("lotstatus", "P");
          newlotData.append("p_option", "checkin");
          newlotData.append(
            "jobworkflowid",
            this.assignedlotlist[0].jobworkflowid.toString()
          );
          this.dashboardservice.getCheckincur(newlotData).subscribe(
            (res) => {
              const queryParams = {
                tranid: this.assignedlotlist[0].transactionid,
                lotid: this.assignedlotlist[0].lotid,
                pdid: this.assignedlotlist[0].projectdefinitionid,
                userid: this.userid,
                jobid: this.assignedlotlist[0].jobid,
                jwfid: this.assignedlotlist[0].jobworkflowid,
                m:this.mode
              };
              const navigationExtras: NavigationExtras = {
                queryParams,
                state: {
                  id: this.assignedlotlist[0].uniquemailid,
                  parentid: this.assignedlotlist[0].parentmailid,
                  subject: this.assignedlotlist[0].subject,
                  from: this.assignedlotlist[0].from_user,
                  body: this.assignedlotlist[0].body,
                  recdate: this.assignedlotlist[0].mailrecievedtime,
                },
              };
              this.router
                .navigate(
                  ["/ccstageprocess/collectionprocess"],
                  navigationExtras
                )
                .then(() => {
                  window.location.reload();
                });

              // this.router.navigate(['/ccstageprocess/collectionprocess'], {
              //   queryParams:
              //     { tranid : this.assignedlotlist[0].transactionid, lotid :this.assignedlotlist[0].lotid, pdid:this.assignedlotlist[0].projectdefinitionid,userid:this.userid,jobid:this.assignedlotlist[0].jobid,jwfid:this.assignedlotlist[0].jobworkflowid,id:this.assignedlotlist[0].uniquemailid}
              //  }).then(() => {
              //   window.location.reload();
              // });
            },
            (error) => {
              this.toastr.error("Error in updating lot transaction");
            }
          );
        } else {
          this.workarea_checkin("", "exit");
          this.router.navigate(["/dashboard"]);
        }
      } else if (
        type == "addlot" &&
        this.optiontoaddnewlot == "updateandisertlot" &&
        !this.olua_area
      ) {
        if (this.assignedlotlist.length > 0) {
          let newlotData = new FormData();

          newlotData.append(
            "tranid",
            this.assignedlotlist[0].transactionid.toString()
          );
          newlotData.append(
            "jobworkflowid",
            this.assignedlotlist[0].jobworkflowid.toString()
          );
          newlotData.append("userid", this.userid.toString());
          newlotData.append("lotstatus", "P");
          newlotData.append("p_option", "checkin");

          this.dashboardservice.getCheckincur(newlotData).subscribe(
            (res) => {
              const queryParams = {
                tranid: this.assignedlotlist[0].transactionid,
                lotid: this.assignedlotlist[0].lotid,
                pdid: this.assignedlotlist[0].projectdefinitionid,
                userid: this.userid,
                jobid: this.assignedlotlist[0].jobid,
                jwfid: this.assignedlotlist[0].jobworkflowid,
                m:this.mode
              };
              const navigationExtras: NavigationExtras = {
                queryParams,
                state: {
                  id: this.assignedlotlist[0].uniquemailid,
                  parentid: this.assignedlotlist[0].parentmailid,
                  subject: this.assignedlotlist[0].subject,
                  from: this.assignedlotlist[0].from_user,
                  body: this.assignedlotlist[0].body,
                  recdate: this.assignedlotlist[0].mailrecievedtime,
                },
              };
              this.router
                .navigate(
                  ["/ccstageprocess/collectionprocess"],
                  navigationExtras
                )
                .then(() => {
                  window.location.reload();
                });

              // this.router.navigate(['/ccstageprocess/collectionprocess'], {
              //   queryParams:
              //     { tranid : this.assignedlotlist[0].transactionid, lotid :this.assignedlotlist[0].lotid, pdid:this.assignedlotlist[0].projectdefinitionid,userid:this.userid,jobid:this.assignedlotlist[0].jobid,jwfid:this.assignedlotlist[0].jobworkflowid,id:this.assignedlotlist[0].uniquemailid}
              //  }).then(() => {
              //   window.location.reload();
              // });
            },
            (error) => {
              this.toastr.error("Error in updating lot transaction");
            }
          );
        }
      } else if (
        type == "addlot" &&
        this.optiontoaddnewlot == "updateandisertlot" &&
        this.olua_area
      ) {
        this.getassignedlot("lot_compeleted");
      }
    });
  }
  getjob() {
    this.collectionprocessservice.GetJobByUserId(this.userid, 349).subscribe(
      (res) => {
        if (res.body[0] != null && res.body[0] !== undefined) {
          this.jobs = JSON.parse(res.body[0]);
          this.jobid = this.jobs.jobid;
          this.getlotdeatils();
        } else {
          this.joblist = true;
        }
      },
      (error) => {
        this.toastr.error("Error while getting data");
      }
    );
  }
  get_checkin(job,mode){
    let fileData = new FormData();
    fileData.append('tranid',job.transactionid.toString());
    fileData.append('userid',this.userid.toString());
    fileData.append('lotstatus', 'P');
    fileData.append('p_option', mode);
    fileData.append('jobworkflowid', job.jobworkflowid.toString());
    this.dashboardservice.getCheckincur(fileData).subscribe(res => {
     let up_lotstatus =res.body[0].json_build_object.lotstatus;
     let up_tranid =res.body[0].json_build_object.transactionid;
     console.log('before_updated',this.assignedlotlist)
     this.assignedlotlist.forEach((element) => {
      if(element.transactionid == up_tranid){
        console.log('update',up_lotstatus,up_tranid)
        element.lotstatus=up_lotstatus;
        console.log('updated',this.assignedlotlist)
      }
    });
     
    }, error => { this.toastr.error('Error in updating lot transaction'); });
  }
  //  async checkmandatorymetafilled(): Promise<any> {
  //   debugger;
  //     return Promise.resolve((async () => {
  //         this.meta_pass =true;
  //         var biddatecheck=true;
  //         var projectidexist = true; var projectid='';var projectidval = true;
  // 		 let biddate = "";
  //         let meta_biddate = "";
  //         let companyname = "";
  //         let meta_companyname = "";
  //         let projectname = "";
  //         let meta_projectname = "";
  //         let meta_url = "";
  //         let meta_solicitation = "";
  //         let bidnumcheck = false;
  //         this.bid_pass = false;
  //         console.log(JSON.stringify(this.jobmetalst));
  //         this.jobmetalst.forEach(element => {
  //           if(element.isexcelmeta === false && element.isrequired === true){
  //             if(element.FieldValue ===''){
  //               this.meta_pass =false;
  //             }
  //           }
  // 		   if (element.FieldName === "Company Name") {
  //             if (element.FieldValue != "") {
  //               meta_companyname = element.FieldValue;
  //             }
  //           }
  //           if (element.FieldName === "Project Name") {
  //             if (element.FieldValue != "") {
  //               meta_projectname = element.FieldValue;
  //             }
  //           }
  //           if (element.FieldName === "URL") {
  //             if (element.FieldValue != "") {
  //               meta_url = element.FieldValue;
  //             }
  //           }
  //          if(element.FieldName === "Bid Date")
  //           {
  //             if(element.FieldValue !=''){
  //               var date = new Date();
  // 			   meta_biddate = element.FieldValue;
  //               if(date > new Date(element.FieldValue) && this.datepipe.transform(date, 'dd-MMM-yyyy') != this.datepipe.transform(element.FieldValue, 'dd-MMM-yyyy')){
  //                 this.meta_pass =false;
  //                 biddatecheck=false;
  //                 }
  //             }
  //           }
  //           if(element.isexcelmeta === false && element.isrequired === true){
  //             if(element.FieldName==="Project ID")
  //             {
  //               if(element.FieldValue !=''){
  //                 projectid=element.FieldValue;
  //                 //const pattern = /^\d{6}[a-zA-Z0-9][a-zA-Z0-9]$/;
  //                 const pattern = /^\d{6}[a-zA-Z0-9]{1,2}$/;

  //                 if (!pattern.test(element.FieldValue)) {
  //                   projectidval=false;
  //                   this.meta_pass =false;
  //                 }
  //               }
  //             }
  //           }
  // 		     if (element.FieldName == "Bid Number") {
  //         debugger;
  //             if (
  //               element.FieldValue != "" &&
  //               element.FieldValue != undefined &&
  //               element.FieldValue != null
  //             ) {
  //               meta_solicitation = element.FieldValue;
  //             }
  //           }
  //         });
  //         debugger;
  //         if(!biddatecheck){
  //           this.toastr.error('Kindly choose the bid date as current or future date only.');
  //           return;
  //         }
  //         if(!projectidval){
  //           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;
  //         }
  //         if(!this.meta_pass){
  //           this.toastr.error('Kindly fill the mandatory field and then proceed.');
  //           return;
  //         }
  //         if(meta_solicitation != "" &&
  //         meta_solicitation != undefined &&
  //         meta_solicitation != null){
  //           if(this.bidlst.length>0){
  //             this.bidlst.forEach((i) => {
  //               biddate = i.biddate;
  //               companyname = i.companyname;
  //               projectname = i.projectname;
  //               let bid_number = "";

  //               if(i.solicitation != null && i.solicitation != undefined ){

  //               if (i.solicitation.length > 1) {
  //                 bid_number = i.solicitation.join(",");
  //               } else {
  //                 bid_number = i.solicitation[0];
  //               }
  //               if (
  //                 bid_number.toLocaleLowerCase().trim() ==
  //                 meta_solicitation.toLocaleLowerCase().trim()
  //               ) {
  //                 if (
  //                   biddate ==
  //                    meta_biddate.toString() &&
  //                   companyname.toLocaleLowerCase().trim() ==
  //                     meta_companyname.toLocaleLowerCase().trim()
  //                     && meta_projectname == projectname
  //                 ) {
  //                   /* if (meta_projectname != "") {
  //                     if (meta_projectname == projectname) {
  //                       this.bid_pass = true;
  //                     }
  //                   } else { */
  //                     this.bid_pass = true;
  //                   //}
  //                 }
  //               }
  //             }
  //             });
  //           }else if(!this.showbidnumber){
  //             //new record
  //             this.bid_pass = true;
  //           }else{
  //             this.bid_pass = false;
  //           }
  //         }else if(!this.showbidnumber){
  //           //new record
  //           this.bid_pass = true;
  //         }
  //      if (!this.bid_pass) {
  //           var date_1 = new Date();
  //           this.bid_data.companyname = meta_companyname;
  // if(meta_projectname)this.bid_data.projectname = meta_projectname;
  //           this.bid_data.solicitation = meta_solicitation;
  //           this.bid_data.biddate = this.datepipe
  //             .transform(meta_biddate, "yyyy-MM-dd")
  //             .toString();
  //           this.bid_data.createdby = this.userid;
  //           this.bid_data.url = meta_url;
  //           this.bid_data.creationdate = this.datepipe
  //             .transform(date_1, "yyyy-MM-dd")
  //             .toString();
  //           this.bid_data.prodefid = this.projectdefinitionid_pass;
  //           //this.bid_data.projectname = meta_projectname;
  //         }

  //         if(this.projectid_not_unique != this.projectdefinitionid_pass && projectid != ''&& projectid != null && projectid != undefined){
  //         const job_ = new Object({
  //           projectid:projectid,
  //           lotid:this.lotid_pass
  //         });

  //         //projectid Unique Check
  //           return await  this.collectionprocessservice.getBylotProjectId(job_).toPromise().then(lotdetails => {
  //           var result=JSON.parse(lotdetails.body[0]);
  //           if(result!=undefined && result!='' && result!=null){
  //             if(result.length>=1){
  //               projectidexist =false;
  //               this.meta_pass =false;
  //             }
  //           }
  //           if(!projectidexist){
  //             this.toastr.error('Project ID already exist.');
  //              return;
  //           }else{
  //           this.metadtalist1=[];
  //           debugger;
  //             this.jobmetalst.forEach(element => {
  //                 this.metadtalist1.push(element);
  //               });
  //               debugger;
  //               return 'from first';
  //             }
  //             }, error => {
  //               this.toastr.error('Error in getting Chapter Master Records');
  //             });
  //           }else{
  //             this.metadtalist1=[];
  //           debugger;
  //             this.jobmetalst.forEach(element => {
  //                 this.metadtalist1.push(element);
  //               });
  //               return 'from first';
  //           }
  //        /* const job_ = new Object({
  //           jobid: this.jobid
  //         });
  //         //need to change check projectid duplicate
  //           return await  this.jobmasterservice.getLotByJobId(job_).toPromise().then(lotres => {
  //           this.job_lotlist = JSON.parse(lotres.body[0]);
  //           var lotres = this.job_lotlist.filter(a => a.lotmastermetafields);
  //            this.job_lotlist.forEach(val => {
  //             if(val.lotmastermetafields != null && val.lotmastermetafields.length >0 && val.lotid !=this.lotid_pass){
  //               val.lotmastermetafields.forEach(vals =>{
  //                 this.jobmetalst.forEach(element => {
  //                   if(element.isexcelmeta === false && element.isrequired === true){
  //                 if(element.FieldName==="Project ID" && vals.FieldName==="Project ID" )
  //                 {
  //                   if(vals.FieldValue ===element.FieldValue)
  //                   {
  //                     this.toastr.error(element.FieldName+' already exist.');
  //                     this.meta_pass =false;
  //                      return;
  //                   }
  //                 }
  //               }
  //               });
  //             });
  //             }
  //           });
  //           if(!this.meta_pass){
  //             return;
  //           }
  //          else{
  //           this.metadtalist1=[];
  //           this.jobmetalst.forEach(element => {
  //               this.metadtalist1.push(element);
  //             });
  //             return 'from first';
  //          }

  //         }, error => {
  //           this.toastr.error('Error in getting Chapter Master Records');
  //         }); */
  //     })());
  // }

  async checkmandatorymetafilled(): Promise<any> {
    debugger;
    return Promise.resolve(
      (async () => {
        this.meta_pass = true;
        var biddatecheck = true;
        var projectidexist = true;
        var projectid = "";
        var projectidval = true;
        let biddate = "";
        let meta_biddate = "";
        let companyname = "";
        let meta_companyname = "";
        let projectname = "";
        let meta_projectname = "";
        let meta_url = "";
        let meta_solicitation = "";
        let bidnumcheck = false;
        this.bid_pass = false;
        var contains_alpha =false;
        this.jobmetalst.forEach((element) => {
          if (element.isexcelmeta === false && element.isrequired === true && !element.Isdisplay ) {
            if (element.FieldValue === "") {
              this.meta_pass = false;
            }
          }
          if (element.FieldName === "Company Name") {
            if (element.FieldValue != "") {
              meta_companyname = element.FieldValue;
            }
          }
          if (element.FieldName === "Project Name") {
            if (element.FieldValue != "") {
              meta_projectname = element.FieldValue;
            }
          }
          if (element.FieldName === "URL") {
            if (element.FieldValue != "") {
              meta_url = element.FieldValue;
            }
          }
          if (element.FieldName === "Bid Date") {
            if (element.FieldValue != "") {
              var date = new Date();
              meta_biddate = element.FieldValue;
              if (
                date > new Date(element.FieldValue) &&
                this.datepipe.transform(date, "dd-MMM-yyyy") !=
                  this.datepipe.transform(element.FieldValue, "dd-MMM-yyyy")
              ) {
                this.meta_pass = false;
                biddatecheck = false;
              }
            }
          }
          if (element.isexcelmeta === false && element.isrequired === true) {
            if (element.FieldName === "Project ID") {
              if (element.FieldValue != "") {
                projectid = element.FieldValue.includes("-")?element.FieldValue.split("-")[0]:element.FieldValue;
                //const pattern = /^\d{6}[a-zA-Z0-9][a-zA-Z0-9]$/;
                const pattern = /^\d{6}[a-zA-Z0-9]{1,2}$/;

                if (!pattern.test(projectid)) {
                  projectidval = false;
                  this.meta_pass = false;
                }
              }
            }
          }
          if (element.FieldName == "Bid Number") {
            debugger;
            bidnumcheck = true;
            if (
              element.FieldValue != "" &&
              element.FieldValue != undefined &&
              element.FieldValue != null
            ) {
              meta_solicitation = element.FieldValue;
            }
          } 
        });
        //debugger;
        if (!biddatecheck) {
          if (this.olua_area == false) {
            this.toastr.error(
              "Kindly choose the bid date as current or future date only."
            );
            return;
          } else {
            this.list_meta_vaild.push({
              biddatecheck: false,
            });
          }
        } else {
          this.list_meta_vaild.push({
            biddatecheck: true,
          });
        }
        if (!projectidval) {
          if (this.olua_area == false) {
            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)."
            );
          } else {
            this.list_meta_vaild.push({
              projectidval: false,
            });
          }
          return;
        } else {
          this.list_meta_vaild.push({
            projectidval: true,
          });
        }
        if (!this.meta_pass) {
          if (this.olua_area == false) {
            this.toastr.error(
              "Kindly fill the mandatory field and then proceed."
            );
            return;
          } else {
            this.list_meta_vaild.push({
              meta_pass: false,
            });
          }
        } else {
          this.list_meta_vaild.push({
            meta_pass: true,
          });
        }

        if (
          meta_solicitation != "" &&
          meta_solicitation != undefined &&
          meta_solicitation != null
        ) {
          if (this.bidlst.length > 0) {
            this.bidlst.forEach((i) => {
              biddate = i.biddate;
              companyname = i.companyname;
              projectname = i.projectname;
              let bid_number = "";

              if (i.solicitation != null && i.solicitation != undefined) {
                if (i.solicitation.length > 1) {
                  bid_number = i.solicitation.join(",");
                } else {
                  bid_number = i.solicitation[0];
                }
                if (
                  bid_number.toLocaleLowerCase().trim() ==
                  meta_solicitation.toLocaleLowerCase().trim()
                ) {
                  debugger;
                  if (
                    biddate == meta_biddate.toString() &&
                    companyname.toLocaleLowerCase().trim() ==
                      meta_companyname.toLocaleLowerCase().trim()
                  ) {
                    console.log(biddate,meta_biddate.toString(),companyname.toLocaleLowerCase().trim(), meta_companyname.toLocaleLowerCase().trim(),meta_projectname,meta_projectname)
                    if (meta_projectname != "") {
                      if (meta_projectname == projectname) {
                        console.log(meta_projectname,meta_projectname)
                        this.bid_pass = true;
                      }
                    } else {
                      this.bid_pass = true;
                    }
                  }
                }
              }
            });
          } else if (!this.showbidnumber) {
            //new record
            this.bid_pass = true;
          } else {
            this.bid_pass = false;
          }
        } else if (!this.showbidnumber) {
          //new record
          this.bid_pass = true;
        }
        if (!this.bid_pass && bidnumcheck) {
          var date_1 = new Date();
          this.bid_data.companyname = meta_companyname;
          if (meta_projectname) this.bid_data.projectname = meta_projectname;
          this.bid_data.solicitation = meta_solicitation;
          this.bid_data.biddate = this.datepipe
            .transform(meta_biddate, "yyyy-MM-dd")
            .toString();
          this.bid_data.createdby = this.userid;
          this.bid_data.url = meta_url;
          this.bid_data.creationdate = this.datepipe
            .transform(date_1, "yyyy-MM-dd")
            .toString();
          this.bid_data.prodefid = this.projectdefinitionid_pass;
          this.bid_data.projectid=projectid;
          //this.bid_data.projectname = meta_projectname;
        }
        if (
          this.projectid_not_unique != this.projectdefinitionid_pass &&
          projectid != "" &&
          projectid != null &&
          projectid != undefined
        ) {
          const job_ = new Object({
            projectid: projectid,
            lotid: this.lotid_pass,
          });

          if (this.olua_area == false) {
            var result;
            //projectid Unique Check
            return await this.collectionprocessservice
              .getBylotProjectId(job_)
              .toPromise()
              .then(
                (lotdetails) => {
                   result = JSON.parse(lotdetails.body[0]);
                     contains_alpha = /[a-zA-Z]/.test(projectid);
                 if(contains_alpha && this.projectid_iteration == this.projectdefinitionid_pass){
                   if(result != undefined && result != "" && result != null){

                    var exist_pid_count=result.length+1;
                    if(exist_pid_count>0){
                     var occuran=(exist_pid_count).toString().padStart(2,0);
                     var iteration_pid=projectid+"-"+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=projectid+"-"+occuran;
                       }   
                     }); 
                   }                   
                   }else{
                    iteration_pid=projectid+"-"+"01";
                   }
                   projectid=iteration_pid;
                    this.metadtalist1 = [];
                    //debugger;
                    this.jobmetalst.forEach((element) => {
                      if (element.FieldName === "Project ID") {
                        element.FieldValue=projectid;
                      }
                      if(element.FieldValue != ''){
                        this.metadtalist1.push(element);
                      }
                     

                    });
                    console.log(JSON.stringify(this.metadtalist1))
                    //debugger;
                    return "from first";
                   
                 }else{
                  if (result != undefined && result != "" && result != null) {
                    if (result.length >= 1) {
                      projectidexist = false;
                      this.meta_pass = false;
                    }
                  }
                  if (!projectidexist) {
                    this.toastr.error("Project ID already exist.");
                    return;
                  } else {
                    this.metadtalist1 = [];
                    //debugger;
                    this.jobmetalst.forEach((element) => {
                      if(element.FieldValue != ''){
                      this.metadtalist1.push(element);
                      }
                    });
                    //debugger;
                    return "from first";
                  }
                }
                },
                (error) => {
                  this.toastr.error("Error in getting Chapter Master Records");
                }
              );
          }
        } else {
          this.metadtalist1 = [];
          //debugger;
          this.jobmetalst.forEach((element) => {
            this.metadtalist1.push(element);
          });
          return "from first";
        }
        /* const job_ = new Object({
          jobid: this.jobid
        });
        //need to change check projectid duplicate
          return await  this.jobmasterservice.getLotByJobId(job_).toPromise().then(lotres => {
          this.job_lotlist = JSON.parse(lotres.body[0]);
          var lotres = this.job_lotlist.filter(a => a.lotmastermetafields);
           this.job_lotlist.forEach(val => {
            if(val.lotmastermetafields != null && val.lotmastermetafields.length >0 && val.lotid !=this.lotid_pass){
              val.lotmastermetafields.forEach(vals =>{             
                this.jobmetalst.forEach(element => {
                  if(element.isexcelmeta === false && element.isrequired === true){
                if(element.FieldName==="Project ID" && vals.FieldName==="Project ID" )
                {
                  if(vals.FieldValue ===element.FieldValue)
                  {
                    this.toastr.error(element.FieldName+' already exist.');
                    this.meta_pass =false;
                     return;
                  }
                }
              }
              });
            });
            }
          });
          if(!this.meta_pass){
            return;
          }
         else{
          this.metadtalist1=[];
          this.jobmetalst.forEach(element => {    
              this.metadtalist1.push(element);
            });
            return 'from first';
         } 
           
        }, error => {
          this.toastr.error('Error in getting Chapter Master Records');
        }); */
      })()
    );
  }
  datevalidation(meta, item) {
    debugger;
    if (meta.FieldName === "Bid Date") {
      if (meta.FieldValue != "") {
        var date = new Date();
        if (
          date > new Date(meta.FieldValue) &&
          this.datepipe.transform(date, "dd-MMM-yyyy") !=
            this.datepipe.transform(meta.FieldValue, "dd-MMM-yyyy")
        ) {
          this.toastr.error(
            "Kindly choose the bid date as current or future date only."
          );
          if (this.olua_area == true) {
            let ind = this.assignedlotlist.findIndex(
              (x) => x.transactionid == item.transactionid
            );
            this.assignedlotlist[ind].lotmeta.forEach((meta) => {
              if (meta.FieldName == "Bid Date") {
                meta.FieldValue = "";
              }
            });
            if (this.selected_lots.length != 0) {
              ind = this.selected_lots.findIndex(
                (x) => x.transactionid == item.transactionid
              );
              this.selected_lots[ind].lotmeta.forEach((meta) => {
                if (meta.FieldName == "Bid Date") {
                  meta.FieldValue = "";
                }
              });
            }
            return;
          } else {
            this.jobmetalst.forEach((element) => {
              if (element.FieldName === "Bid Date") element.FieldValue = "";
            });
            return;
          }
        }
      }
    }
  }
  /* datevalidation(meta){
  console.log(meta)
  if(meta.FieldName==="Bid Date")
  {
    if(meta.FieldValue !=''){
      var date = new Date(); 
      if(date > new Date(meta.FieldValue) && this.datepipe.transform(date, 'dd-MMM-yyyy') != this.datepipe.transform(meta.FieldValue, 'dd-MMM-yyyy')){
        this.toastr.error('Kindly choose the bid date as current or future date only.');
       
        this.jobmetalst.forEach(element => {
          if(element.FieldName==="Bid Date") element.FieldValue='';
        });

        return;
        }
    }
  }
} */
  /*async checkmandatorymetafilled(){
    debugger;
    this.meta_pass =true;
          this.jobmetalst.forEach(element => {
            if(element.isexcelmeta === false && element.isrequired === true){
              if(element.FieldValue ===''){
                //this.toastr.error('Please enter the '+element.FieldName+' value');
                this.meta_pass =false;
              }
            }
          });
          if(!this.meta_pass){
            this.toastr.error('Kindly fill the mandatory field and then proceed.');
            return;
          }
          const job_ = new Object({
            jobid: this.jobid
          });
         return await  this.jobmasterservice.getLotByJobId(job_).subscribe(lotres => {
            this.job_lotlist = JSON.parse(lotres.body[0]);
            var lotres = this.job_lotlist.filter(a => a.lotmastermetafields);
            console.log(lotres);
             this.job_lotlist.forEach(val => {
              if(val.lotmastermetafields != null && val.lotmastermetafields.length >0 && val.lotid !=this.lotid){
                val.lotmastermetafields.forEach(vals =>{             
                  this.jobmetalst.forEach(element => {
                    if(element.isexcelmeta === false && element.isrequired === true){
                  //if(vals.FieldName ===element.FieldName)
                  if(element.FieldName==="Project ID")
                  {
                    if(vals.FieldValue ===element.FieldValue)
                    {
                      this.toastr.error(element.FieldName+' already exist.');
                      this.meta_pass =false;
                       return;
                    }
                  }
                }
                });
              });
              }
            });
            if(!this.meta_pass){
              return;
            }
           else{
            this.metadtalist1=[];
            this.jobmetalst.forEach(element => {    
                this.metadtalist1.push(element);
              });
           } 
             
          }, error => {
            this.toastr.error('Error in getting Chapter Master Records');
          }); 
  }*/
  async updatemetaandcompletelot() {
    debugger;

    if (this.olua_area == true) {
      this.list_meta_vaild = [];
      if (this.selected_lots.length == 0) {
        this.toastr.error("Atleast select one lot to completed.");
        return;
      } else {
        let len = 0;
        if (this.showbidnumber) {
          this.collectionprocessservice.Getbidlist().subscribe(async (res) => {
            if (res.body != null && res.body != "" && res.body != undefined) {
              this.bidlst = JSON.parse(res.body);
            }
            this.selected_lots.forEach(async (element) => {
              len = len + 1;
              this.jobmetalst = element.lotmeta;
              if (this.addrecnotshoe == false) {
                await this.checkmandatorymetafilled().then((data1) => {
                  if (!this.meta_pass) {
                    return;
                  }
                });
              } else {
                this.completeStage(
                  "A",
                  this.worlAreaPopUpTemplate,
                  0,
                  0,
                  0,
                  "comp"
                );
              }
            });
            let err_meta = this.list_meta_vaild.findIndex(
              (x) => x.meta_pass == false
            );
            let err_bid = this.list_meta_vaild.findIndex(
              (x) => x.biddatecheck == false
            );
            let err_projectid = this.list_meta_vaild.findIndex(
              (x) => x.projectidval == false
            );
            if (err_meta != -1 || err_bid != -1 || err_projectid != -1) {
              this.meta_pass = false;
            }
            if (!this.meta_pass) {
              if (err_meta != -1) {
                this.toastr.error(
                  "Kindly fill the mandatory field and then proceed."
                );
              }
              if (err_bid != -1) {
                this.toastr.error(
                  "Kindly choose the bid date as current or future date only."
                );
              }
              if (err_projectid != -1) {
                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)."
                );
              }
              this.list_meta_vaild = [];
              return;
            }
            if (len == this.selected_lots.length) {
              if (err_meta == -1 && err_bid == -1 && err_projectid == -1) {
                this.updatelotmetafields();
              } else {
                return;
              }
            } else {
              return;
            }
          });
        }else{
          this.selected_lots.forEach(async (element) => {
            len = len + 1;
            this.jobmetalst = element.lotmeta;
            if (this.addrecnotshoe == false) {
              await this.checkmandatorymetafilled().then((data1) => {
                if (!this.meta_pass) {
                  return;
                }
              });
            } else {
              this.completeStage(
                "A",
                this.worlAreaPopUpTemplate,
                0,
                0,
                0,
                "comp"
              );
            }
          });
          let err_meta = this.list_meta_vaild.findIndex(
            (x) => x.meta_pass == false
          );
          let err_bid = this.list_meta_vaild.findIndex(
            (x) => x.biddatecheck == false
          );
          let err_projectid = this.list_meta_vaild.findIndex(
            (x) => x.projectidval == false
          );
          if (err_meta != -1 || err_bid != -1 || err_projectid != -1) {
            this.meta_pass = false;
          }
          if (!this.meta_pass) {
            if (err_meta != -1) {
              this.toastr.error(
                "Kindly fill the mandatory field and then proceed."
              );
            }
            if (err_bid != -1) {
              this.toastr.error(
                "Kindly choose the bid date as current or future date only."
              );
            }
            if (err_projectid != -1) {
              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)."
              );
            }
            this.list_meta_vaild = [];
            return;
          }
          if (len == this.selected_lots.length) {
            if (err_meta == -1 && err_bid == -1 && err_projectid == -1) {
              this.updatelotmetafields();
            } else {
              return;
            }
          } else {
            return;
          }
        }
       
      }
    } else {
      if (this.showbidnumber) {
        this.collectionprocessservice.Getbidlist().subscribe(async (res) => {
          debugger;
          if (res.body != null && res.body != "" && res.body != undefined) {
            this.bidlst = JSON.parse(res.body);
          }
          if (this.addrecnotshoe == false) {
            await this.checkmandatorymetafilled().then((data1) => {
              if (!this.meta_pass) {
                return;
              }
              this.updatelotmetafields();
            });
          } else {
            this.completeStage(
              "A",
              this.worlAreaPopUpTemplate,
              0,
              0,
              0,
              "comp"
            );
          }
        });
      } else {
        if (this.addrecnotshoe == false) {
          await this.checkmandatorymetafilled().then((data1) => {
            if (!this.meta_pass) {
              return;
            }
            this.updatelotmetafields();
          });
        } else {
          this.completeStage("A", this.worlAreaPopUpTemplate, 0, 0, 0, "comp");
        }
      }
    }
  }
  async openconfrimpop(ccjoburlmaster: Ccjoburlmaster) {

    if (this.olua_area == true) {
      if (this.selected_lots.length == 0) {
        this.toastr.error("Atleast select one lot to completed.");
        return;
      }

      let len = 0;
      this.list_meta_vaild = [];
      if (this.showbidnumber) {
        this.collectionprocessservice.Getbidlist().subscribe(async (res) => {
          if (res.body != null && res.body != "" && res.body != undefined) {
            this.bidlst = JSON.parse(res.body);
          }
  this.selected_lots.forEach(async (element) => {
    len = len + 1;
    this.jobmetalst = element.lotmeta;
    await this.checkmandatorymetafilled().then((data1) => {
      if (!this.meta_pass) {
        return;
      }
    });
  });
  let err_meta = this.list_meta_vaild.findIndex(
    (x) => x.meta_pass == false
  );
  let err_bid = this.list_meta_vaild.findIndex(
    (x) => x.biddatecheck == false
  );
  let err_projectid = this.list_meta_vaild.findIndex(
    (x) => x.projectidval == false
  );
  if (err_meta != -1 || err_bid != -1 || err_projectid != -1) {
    this.meta_pass = false;
  }
  if (!this.meta_pass) {
    if (err_meta != -1) {
      this.toastr.error(
        "Kindly fill the mandatory field and then proceed."
      );
    }
    if (err_bid != -1) {
      this.toastr.error(
        "Kindly choose the bid date as current or future date only."
      );
    }
    if (err_projectid != -1) {
      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)."
      );
    }
    this.list_meta_vaild = [];
    return;
  }
  if (len == this.selected_lots.length) {
    if (this.frommyjob && this.meta_pass) {
      this.dialogService
        .addDialog(CommondialogComponent, {
          title: "Please Confirm",
          message: "Do you want add Multiple Projects (Records) ?",
          hclass: "modelsuccess",
          oktext: "Add Record ",
          canceltext: "Add & Open Record",
          okshow: true,
          cancelshow: true,
        })
        .subscribe((isConfirmed) => {
          debugger;
          if (this.meta_pass) {
            if (isConfirmed) {
              this.isaddlot = true;
              this.optiontoaddnewlot = "updateandisertlot";
              this.mode=1;
              this.updatelotmetafields();
            } else {
             /*  this.optiontoaddnewlot = "updatelot";
              this.isaddlot = false;
              this.updatelotmetafields(); */
              this.isaddlot = true;
              this.mode=2;
              this.optiontoaddnewlot = "updateandisertlot";
              this.updatelotmetafields();

            }
          } else {
            return;
          }
        });
    }
  } else {
    return;
  }
});
}else{
  this.selected_lots.forEach(async (element) => {
    len = len + 1;
    this.jobmetalst = element.lotmeta;
    await this.checkmandatorymetafilled().then((data1) => {
      if (!this.meta_pass) {
        return;
      }
    });
  });
  let err_meta = this.list_meta_vaild.findIndex(
    (x) => x.meta_pass == false
  );
  let err_bid = this.list_meta_vaild.findIndex(
    (x) => x.biddatecheck == false
  );
  let err_projectid = this.list_meta_vaild.findIndex(
    (x) => x.projectidval == false
  );
  if (err_meta != -1 || err_bid != -1 || err_projectid != -1) {
    this.meta_pass = false;
  }
  if (!this.meta_pass) {
    if (err_meta != -1) {
      this.toastr.error(
        "Kindly fill the mandatory field and then proceed."
      );
    }
    if (err_bid != -1) {
      this.toastr.error(
        "Kindly choose the bid date as current or future date only."
      );
    }
    if (err_projectid != -1) {
      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)."
      );
    }
    this.list_meta_vaild = [];
    return;
  }
  if (len == this.selected_lots.length) {
    if (this.frommyjob && this.meta_pass) {
      this.dialogService
        .addDialog(CommondialogComponent, {
          title: "Please Confirm",
          message: "Do you want add Multiple Projects (Records) ?",
          hclass: "modelsuccess",
          oktext: "Add Record ",
          canceltext: "Add & Open Record",
          okshow: true,
          cancelshow: true,
        })
        .subscribe((isConfirmed) => {
          debugger;
          if (this.meta_pass) {
            if (isConfirmed) {
              this.isaddlot = true;
              this.optiontoaddnewlot = "updateandisertlot";
              this.mode=1;
              this.updatelotmetafields();
            } else {
             /*  this.optiontoaddnewlot = "updatelot";
              this.isaddlot = false;
              this.updatelotmetafields(); */
              this.isaddlot = true;
              this.mode=2;
              this.optiontoaddnewlot = "updateandisertlot";
              this.updatelotmetafields();

            }
          } else {
            return;
          }
        });
    }
  } else {
    return;
  }
}

   
    } else {
      if (this.showbidnumber) {
        this.collectionprocessservice.Getbidlist().subscribe(async (res) => {
          if (res.body != null && res.body != "" && res.body != undefined) {
            this.bidlst = JSON.parse(res.body);
          }
          await this.checkmandatorymetafilled().then((data1) => {
            if (!this.meta_pass) {
              return;
            }
            if (this.frommyjob && this.meta_pass) {
              this.dialogService
                .addDialog(CommondialogComponent, {
                  title: "Please Confirm",
                  message: "Do you want add Multiple Projects (Records) ?",
                  hclass: "modelsuccess",
                  oktext: "Add Record",
                  canceltext: "Add & Open Record",
                  okshow: true,
                  cancelshow: true,
                })
                .subscribe((isConfirmed) => {
                  debugger;
                  if (this.meta_pass) {
                    if (isConfirmed) {
                      this.isaddlot = true;
                      this.optiontoaddnewlot = "updateandisertlot";
                      this.mode=1;
                      this.updatelotmetafields();
                    } else {
                      
                      this.isaddlot = true;
                      this.mode=2;
                      this.optiontoaddnewlot = "updateandisertlot";
                      this.updatelotmetafields();
                    }
                  } else {
                    return;
                  }
                });
            }
          });
        });
      }else{
        await this.checkmandatorymetafilled().then((data1) => {
          if (!this.meta_pass) {
            return;
          }
          if (this.frommyjob && this.meta_pass) {
            this.dialogService
              .addDialog(CommondialogComponent, {
                title: "Please Confirm",
                message: "Do you want add Multiple Projects (Records) ?",
                hclass: "modelsuccess",
                oktext: "Add Record",
                canceltext: "Add & Open Record",
                okshow: true,
                cancelshow: true,
              })
              .subscribe((isConfirmed) => {
                debugger;
                if (this.meta_pass) {
                  if (isConfirmed) {
                    this.isaddlot = true;
                    this.optiontoaddnewlot = "updateandisertlot";
                    this.mode=1;
                    this.updatelotmetafields();
                  } else {
                    
                    this.isaddlot = true;
                    this.mode=2;
                    this.optiontoaddnewlot = "updateandisertlot";
                    this.updatelotmetafields();
                  }
                } else {
                  return;
                }
              });
          }
        });
      }
      
    }
  }
  addtbljoblotexcel(lotid) {
    let filterlot = this.joblotexcel.filter((x) => x.lotid == lotid);
    let input = [];
    if (filterlot.length > 0) {
      input = [
        {
          projectid: this.editable_projid,
          job_url: this.editable_joburl,
          lotid: lotid,
          jobid: this.jobid,
          updatedby: this.userid,
        },
      ];
      this.collectionprocessservice.updatejoblotexcel(input[0]).subscribe(
        (res) => {
          if (res.body[0] != null && res.body[0] !== undefined) {
            //this.joblotexcel = JSON.parse(res.body[0]);
            if (res.body[0] != 1) {
              this.gettbljoblotexcel();
              this.showcomplete = false;
              this.toastr.success("Lot updated successfully");
              this.getlotdeatils();
              if (this.isaddlot) {
                this.completeStage(
                  "A",
                  this.worlAreaPopUpTemplate,
                  0,
                  0,
                  0,
                  "comp"
                );
              }
            } else {
              this.showlotgrid = false;
              this.toastr.error("Projectid already exist!!!");
            }
          }
        },
        (error) => {
          this.toastr.error("Error while updating lot data");
        }
      );
    } else {
      //insert
      let existlot = this.joblotexcel.filter((x) => x.lotid == this.lotid_pass);
      if (existlot.length > 0) {
        input = [
          {
            projectid: null,
            job_url: null,
            frequencyid:
              existlot[0].frequencyid == null ? 0 : existlot[0].frequencyid,
            statecodeid:
              existlot[0].statecodeid == null ? 0 : existlot[0].statecodeid,
            companyname: existlot[0].companyname,
            type: existlot[0].type,
            city: existlot[0].city,
            joblotinfoexcelpath: existlot[0].joblotinfoexcelpath,
            lotid: lotid,
            jobid: this.jobid,
            createdby: this.userid,
          },
        ];
      } else {
        input = [
          {
            projectid: this.editable_projid,
            job_url: this.editable_joburl,
            frequencyid: 0,
            statecodeid: 0,
            companyname: null,
            type: null,
            city: null,
            joblotinfoexcelpath: null,
            lotid: lotid,
            jobid: this.jobid,
            createdby: this.userid,
          },
        ];
      }
      this.collectionprocessservice.addjoblotexcel(input[0]).subscribe(
        (res) => {
          if (res.body[0] != null && res.body[0] !== undefined) {
            this.gettbljoblotexcel();
          }
        },
        (error) => {
          this.toastr.error("Error while adding lot data");
          this.showlotgrid = false;
        }
      );
    }
  }
  gettbljoblotexcel() {
    const input = [];
    this.collectionprocessservice.getjoblotexcel(input).subscribe(
      (res) => {
        if (res.body[0] != null && res.body[0] !== undefined) {
          this.joblotexcel = JSON.parse(res.body[0]);
        }
      },
      (error) => {
        this.toastr.error("Error while getting data");
      }
    );
  }
  getlotdeatils() {
    var data = [];
    if (this.olua_area == true) {
      data = [
        {
          jobid: 0,
          prodefid: this.projectdefinitionid_pass,
          userid: this.userid_pass,
          mode: "olua_lots",
        },
      ];
    } else {
      data = [
        {
          jobid: this.jobid,
          prodefid: 0,
          userid: this.userid_pass,
          mode: "single_lot",
        },
      ];
    }
    this.collectionprocessservice.getalllotDetails(data[0]).subscribe(
      async (res) => {
        debugger;
        if (res.body != null && res.body !== undefined) {
          this.alllotdetails = res.body;
          if (this.olua_area == true) {
            await this.getJobMetaFields();
          } else {
            this.alllotdetails.forEach((val) => {
              const alllotdetails_ = JSON.parse(val);
              if (alllotdetails_.lotid == this.lotid_pass) {
                if (
                  this.userid != 0 &&
                  alllotdetails_.pickedby == this.userid
                ) {
                  this.lottitle = alllotdetails_.title;
                  this.metadtalist1 = alllotdetails_.lotmastermetafields;
                  debugger;
                  if(this.metadtalist1 != null ){
                    this.metadtalist1.forEach((x)=>{
                      debugger;
                      if(x.FieldName === "Company Name")
                    {
                      this.companyname=x.FieldValue;
                      console.log("company",this.companyname)
                    } 
                });
                  }

                  this.getJobMetaFields();
                  this.stagename = alllotdetails_.stagename_alias;
                  if (this.lottitle != undefined) {
                    this.text_width = 82 + 4 * Number(this.lottitle.length);
                    this.textboxcss = {
                      width: this.text_width + "px",
                      "margin-left": "-53px",
                    };
                  }
                  this.onlotSelect(this.selectedlot, "ts");
                }
                if (
                  this.mailid == undefined ||
                  this.mailid == "" ||
                  this.mailid == null
                ) {
                  if (
                    alllotdetails_.uniquemailid &&
                    alllotdetails_.parentmailid
                  ) {
                    if (
                      this.projectdefinitionid_pass == this.automailprojectid
                    ) {
                      this.mailid = alllotdetails_.uniquemailid;
                      this.parentid = alllotdetails_.parentmailid;
                      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.loadcategory();
                        this.getmaildetailsbyid();
                        this.mail_url =
                          this.mail_parenturl_start +
                          this.mailid +
                          this.mail_parenturl_end;
                        this.showmail();
                      }
                    }
                  }
                }
              }
            });
          }
        } else {
          this.alllotdetails = [];
        }
      },
      (err) => {
        this.toastr.error("Error in loading all lot details");
      }
    );
  }

  getJobMetaFields() {
    debugger;
    console.log("metadata");
    this.jobmetalst = [];
    let metadtalist2;
    this.jobMetaService.GetActive().subscribe(
      (res) => {
        debugger;
        if (res.length > 0) {
          this.jobMetadataorg = JSON.parse(res[0]);
          this.jobMetadata = this.jobMetadataorg.filter(
            (i) => i.projectdefinitionid === +this.projectdefinitionid_pass
          );
          this.add_jobmetalst = this.jobMetadataorg.filter(
            (i) =>
              i.projectdefinitionid === +this.projectdefinitionid_pass &&
              i.isexcelmeta === false &&
              i.isrequired === true
          ); //&& i.isexcelmeta === false && i.isrequired === true
          this.lotmeta = this.jobMetadata.filter(
            (m) => m.isexcelmeta === false && m.isrequired === false
          );
          this.olua_lotmeta = [];
          this.olua_lotmeta = this.lotmeta
          let item = {};
          let index = 0;
          if (this.olua_area == true) {
            this.alllotdetails.forEach((val) => {
              const alllotdetails_ = JSON.parse(val);
              var ind = this.assignedlotlist.findIndex(
                (x) => x.lotid == alllotdetails_.lotid
              );
              this.stagename = alllotdetails_.stagename_alias;
              if (ind != -1) {
                index = index + 1;
                this.metadtalist1 = alllotdetails_.lotmastermetafields;
                if (
                  this.metadtalist1 != null &&
                  this.metadtalist1 != undefined &&
                  this.metadtalist1.length != 0
                ) {
                  metadtalist2 = this.metadtalist1.filter(
                    (m) => m.isexcelmeta === false && m.isrequired === false
                  );
                  this.metadtalist1.forEach((lmd) => {
                    this.jobMetadata.forEach((md) => {
                      if (
                        lmd.FieldName === md.jobmeta &&
                        lmd.isexcelmeta === true &&
                        lmd.FieldValue != null &&
                        lmd.FieldValue != undefined &&
                        lmd.FieldValue != ""
                      ) {
                        var index = this.jobmetalst.findIndex(
                          (p) => p.FieldName == lmd.FieldName
                        );
                        if (index === -1) {
                          if (md.inputtype === "dropdown" || md.inputtype === "checkbox") {
                            item = {
                              FieldName: lmd.FieldName,
                              FieldValue: lmd.FieldValue,
                              isexcelmeta: lmd.isexcelmeta,
                              isrequired: md.isrequired,
                              inputtype: md.inputtype,
                              Fieldselectoption: md.inputvalueoption,
                            };
                          } else {
                            item = {
                              FieldName: lmd.FieldName,
                              FieldValue: lmd.FieldValue,
                              isexcelmeta: lmd.isexcelmeta,
                              isrequired: md.isrequired,
                              inputtype: md.inputtype,
                              Fieldselectoption: md.inputvalueoption,
                            };
                            if (lmd.FieldName == "Bid Number") {
                              this.showbidnumber = true;
                            }
                          }
                          this.jobmetalst.push(item);
                        }
                      } else if (
                        lmd.FieldName === md.jobmeta &&
                        lmd.isexcelmeta === false &&
                        lmd.isrequired === true
                      ) {
                        var index = this.jobmetalst.findIndex(
                          (p) => p.FieldName == lmd.FieldName
                        );
                        if (index === -1) {
                          if (lmd.FieldValue != "") {
                            if (md.inputtype === "dropdown" || md.inputtype === "checkbox") {
                              item = {
                                FieldName: lmd.FieldName,
                                FieldValue: lmd.FieldValue,
                                isexcelmeta: lmd.isexcelmeta,
                                isrequired: md.isrequired,
                                inputtype: md.inputtype,
                                Fieldselectoption: md.inputvalueoption,
                              };
                            } else {
                              item = {
                                FieldName: lmd.FieldName,
                                FieldValue: lmd.FieldValue,
                                isexcelmeta: lmd.isexcelmeta,
                                isrequired: md.isrequired,
                                inputtype: md.inputtype,
                                Fieldselectoption: md.inputvalueoption,
                              };
                              if (lmd.FieldName == "Bid Number") {
                                this.showbidnumber = true;
                              }
                            }
                            this.jobmetalst.push(item);
                          } else {
                            if (md.inputtype === "dropdown" || md.inputtype === "checkbox") {
                              item = {
                                FieldName: lmd.FieldName,
                                FieldValue: "",
                                isexcelmeta: md.isexcelmeta,
                                isrequired: md.isrequired,
                                inputtype: md.inputtype,
                                Fieldselectoption: md.inputvalueoption,
                              };
                            } else {
                              item = {
                                FieldName: lmd.FieldName,
                                FieldValue: "",
                                isexcelmeta: md.isexcelmeta,
                                isrequired: md.isrequired,
                                inputtype: md.inputtype,
                                Fieldselectoption: md.inputvalueoption,
                              };
                              if (lmd.FieldName == "Bid Number") {
                                this.showbidnumber = true;
                              }
                            }
                            this.jobmetalst.push(item);
                          }
                        }
                      } else if (
                        metadtalist2 != null &&
                        metadtalist2 != undefined &&
                        metadtalist2.length != 0
                      ) {
                        if (
                          lmd.FieldName === md.jobmeta &&
                          lmd.isexcelmeta === false &&
                          lmd.isrequired === false
                        ) {
                          item = {
                            FieldName: lmd.FieldName,
                            FieldValue: lmd.FieldValue,
                            isexcelmeta: lmd.isexcelmeta,
                            isrequired: lmd.isrequired,
                            inputtype: lmd.inputtype,
                            Fieldselectoption: lmd.inputvalueoption,
                          };
                          if (lmd.FieldName == "Bid Number") {
                            this.showbidnumber = true;
                          }
                          this.jobmetalst.push(item);
                        }
                      }
                    });
                  });
                  this.add_jobmetalst.forEach((element) => {
                    this.jobmetalst.forEach((element1) => {
                      //debugger;
                      if (element.jobmeta != element1.FieldName) {
                        var index = this.jobmetalst.findIndex(
                          (p) => p.FieldName == element.jobmeta
                        );
                        if (index === -1) {
                          if (
                            metadtalist2 != null &&
                            metadtalist2 != undefined &&
                            metadtalist2.length != 0
                          ) {
                            if (element.inputtype === "dropdown" || element.inputtype === "checkbox") {
                              item = {
                                FieldName: element.jobmeta,
                                FieldValue: "",
                                isexcelmeta: element.isexcelmeta,
                                isrequired: element.isrequired,
                                inputtype: element.inputtype,
                                Fieldselectoption: element.inputvalueoption,
                              };
                            } else {
                              item = {
                                FieldName: element.jobmeta,
                                FieldValue: "",
                                isexcelmeta: element.isexcelmeta,
                                isrequired: element.isrequired,
                                inputtype: element.inputtype,
                                Fieldselectoption: element.inputvalueoption,
                              };
                              if (element.jobmeta == "Bid Number") {
                                this.showbidnumber = true;
                              }
                            }
                            this.jobmetalst.push(item);
                          } else {
                            if (element.isrequired == true) {
                              if (element.inputtype === "dropdown"  || element.inputtype === "checkbox") {
                                item = {
                                  FieldName: element.jobmeta,
                                  FieldValue: "",
                                  isexcelmeta: element.isexcelmeta,
                                  isrequired: element.isrequired,
                                  inputtype: element.inputtype,
                                  Fieldselectoption: element.inputvalueoption,
                                };
                              } else {
                                item = {
                                  FieldName: element.jobmeta,
                                  FieldValue: "",
                                  isexcelmeta: element.isexcelmeta,
                                  isrequired: element.isrequired,
                                  inputtype: element.inputtype,
                                  Fieldselectoption: element.inputvalueoption,
                                };
                                if (element.jobmeta == "Bid Number") {
                                  this.showbidnumber = true;
                                }
                              }
                            }
                            this.jobmetalst.push(item);
                          }
                        }
                      }
                    });
                  });
                } else {
                  this.jobMetadata.forEach((element) => {
                    if (
                      (element.isexcelmeta === true &&
                        element.isrequired === true &&
                        element.FieldValue != null &&
                        (element.FieldValue != undefined ||
                          this.projectid_not_unique ==
                            this.projectdefinitionid_pass) &&
                        element.FieldValue != "") ||
                      (element.isexcelmeta == false &&
                        element.isrequired === true) ||
                      (element.isexcelmeta === true &&
                        element.isrequired === false &&
                        element.FieldValue != null &&
                        (element.FieldValue != undefined ||
                          this.projectid_not_unique ==
                            this.projectdefinitionid_pass) &&
                        element.FieldValue != "")
                    ) {
                      if (element.inputtype === "dropdown"  || element.inputtype === "checkbox") {
                        item = {
                          FieldName: element.jobmeta,
                          FieldValue: "",
                          isexcelmeta: element.isexcelmeta,
                          isrequired: element.isrequired,
                          inputtype: element.inputtype,
                          Fieldselectoption: element.inputvalueoption,
                        };
                      } else {
                        item = {
                          FieldName: element.jobmeta,
                          FieldValue: "",
                          isexcelmeta: element.isexcelmeta,
                          isrequired: element.isrequired,
                          inputtype: element.inputtype,
                          Fieldselectoption: element.inputvalueoption,
                        };
                        if (element.jobmeta == "Bid Number") {
                          this.showbidnumber = true;
                        }
                      }
                      this.jobmetalst.push(item);
                    }
                  });
                }
                this.assignedlotlist[ind]["lotmeta"] = this.jobmetalst;
                this.assignedlotlist[ind]["insert_p"] = 0;
                this.jobmetalst = [];
              }
            });
          } else {
            if (
              this.metadtalist1 != null &&
              this.metadtalist1 != undefined &&
              this.metadtalist1.length != 0
            ) {
              metadtalist2 = this.metadtalist1.filter(
                (m) => m.isexcelmeta === false && m.isrequired === false
              );
               //is excel true
              this.metadtalist1.forEach((lmd) => {
                this.jobMetadata.forEach((md) => {
                  if (
                    lmd.FieldName === md.jobmeta &&
                    lmd.isexcelmeta === true &&
                    lmd.FieldValue != null &&
                    lmd.FieldValue != undefined &&
                    lmd.FieldValue != ""
                  ) {
                    var index = this.jobmetalst.findIndex(
                      (p) => p.FieldName == lmd.FieldName
                    );
                    if (index === -1) {
                      if (md.inputtype === "dropdown"  || md.inputtype === "checkbox") {
                        item = {
                          FieldName: lmd.FieldName,
                          FieldValue: lmd.FieldValue,
                          isexcelmeta: lmd.isexcelmeta,
                          isrequired: md.isrequired,
                          inputtype: md.inputtype,
                          Fieldselectoption: md.inputvalueoption,
                        };
                      } else {
                        item = {
                          FieldName: lmd.FieldName,
                          FieldValue: lmd.FieldValue,
                          isexcelmeta: lmd.isexcelmeta,
                          isrequired: md.isrequired,
                          inputtype: md.inputtype,
                          Fieldselectoption: md.inputvalueoption,
                        };
                        if (lmd.FieldName == "Bid Number") {
                          this.showbidnumber = true;
                        }
                      }
                      this.jobmetalst.push(item);
                    }
                  } else if (
                    lmd.FieldName === md.jobmeta &&
                    lmd.isexcelmeta === false &&
                    lmd.isrequired === true
                  ) {
                    var index = this.jobmetalst.findIndex(
                      (p) => p.FieldName == lmd.FieldName
                    );
                    if (index === -1) {
                      if (lmd.FieldValue != "") {
                        if (md.inputtype === "dropdown"  || md.inputtype === "checkbox") {
                          item = {
                            FieldName: lmd.FieldName,
                            FieldValue: lmd.FieldValue,
                            isexcelmeta: lmd.isexcelmeta,
                            isrequired: md.isrequired,
                            inputtype: md.inputtype,
                            Fieldselectoption: md.inputvalueoption,
                          };
                        } else {
                          item = {
                            FieldName: lmd.FieldName,
                            FieldValue: lmd.FieldValue,
                            isexcelmeta: lmd.isexcelmeta,
                            isrequired: md.isrequired,
                            inputtype: md.inputtype,
                            Fieldselectoption: md.inputvalueoption,
                          };
                          if (lmd.FieldName == "Bid Number") {
                            this.showbidnumber = true;
                          }
                        }
                        this.jobmetalst.push(item);
                      } else {
                        if (md.inputtype === "dropdown" || md.inputtype === "checkbox") {
                          item = {
                            FieldName: lmd.FieldName,
                            FieldValue: "",
                            isexcelmeta: md.isexcelmeta,
                            isrequired: md.isrequired,
                            inputtype: md.inputtype,
                            Fieldselectoption: md.inputvalueoption,
                          };
                        } else {
                          item = {
                            FieldName: lmd.FieldName,
                            FieldValue: "",
                            isexcelmeta: md.isexcelmeta,
                            isrequired: md.isrequired,
                            inputtype: md.inputtype,
                            Fieldselectoption: md.inputvalueoption,
                          };
                          if (lmd.FieldName == "Bid Number") {
                            this.showbidnumber = true;
                          }
                        }
                        this.jobmetalst.push(item);
                      }
                    }
                  } else if (
                    metadtalist2 != null &&
                    metadtalist2 != undefined &&
                    metadtalist2.length != 0
                  ) {
                    if (
                      lmd.FieldName === md.jobmeta &&
                      lmd.isexcelmeta === false &&
                      lmd.isrequired === false
                    ) {
                      item = {
                        FieldName: lmd.FieldName,
                        FieldValue: lmd.FieldValue,
                        isexcelmeta: lmd.isexcelmeta,
                        isrequired: lmd.isrequired,
                        inputtype: lmd.inputtype,
                        Fieldselectoption: lmd.Fieldselectoption,
                      };
                      if (lmd.FieldName == "Bid Number") {
                        this.showbidnumber = true;
                      }
                      this.lotmeta = this.lotmeta.filter(
                        (l) => l.jobmetaid != md.jobmetaid
                      );
                      this.jobmetalst.push(item);
                    }
                  }
                });
              });
              var key = true;
             //is required true ,is excel false
              this.add_jobmetalst.forEach((element) => {
                this.jobmetalst.forEach((element1) => {
                  debugger;
                  if (element.jobmeta != element1.FieldName) {
                    var index = this.jobmetalst.findIndex(
                      (p) => p.FieldName == element.jobmeta
                    );
                    if (index === -1) {
                      if (
                        metadtalist2 != null &&
                        metadtalist2 != undefined &&
                        metadtalist2.length != 0
                      ) {
                        if (element.inputtype === "dropdown" || element.inputtype === "checkbox") {
                          item = {
                            FieldName: element.jobmeta,
                            FieldValue: "",
                            isexcelmeta: element.isexcelmeta,
                            isrequired: element.isrequired,
                            inputtype: element.inputtype,
                            Fieldselectoption: element.inputvalueoption,
                          };
                        } else {
                          item = {
                            FieldName: element.jobmeta,
                            FieldValue: "",
                            isexcelmeta: element.isexcelmeta,
                            isrequired: element.isrequired,
                            inputtype: element.inputtype,
                            Fieldselectoption: element.inputvalueoption,
                          };
                          if (element.jobmeta == "Bid Number") {
                            this.showbidnumber = true;
                          }
                        }
                        this.jobmetalst.push(item);
                      } else {
                        if (element.isrequired == true) {
                          if (element.inputtype === "dropdown" || element.inputtype === "checkbox") {
                            item = {
                              FieldName: element.jobmeta,
                              FieldValue: "",
                              isexcelmeta: element.isexcelmeta,
                              isrequired: element.isrequired,
                              inputtype: element.inputtype,
                              Fieldselectoption: element.inputvalueoption,
                            };
                          } else {
                            item = {
                              FieldName: element.jobmeta,
                              FieldValue: "",
                              isexcelmeta: element.isexcelmeta,
                              isrequired: element.isrequired,
                              inputtype: element.inputtype,
                              Fieldselectoption: element.inputvalueoption,
                            };
                            if (element.jobmeta == "Bid Number") {
                              this.showbidnumber = true;
                            }
                          }
                        }
                        this.jobmetalst.push(item);
                      }
                    }
                  }
                });
              });

              //is required false ,is excel false
              this.lotmeta.forEach(element => {
                this.jobmetalst.forEach((element1) => {
debugger
                  if (element.jobmeta != element1.FieldName) {
                    var index = this.jobmetalst.findIndex(
                      (p) => p.FieldName == element.jobmeta
                    );
                    if (index === -1) {
                      if (element.inputtype === "dropdown" || element.inputtype === "checkbox") {
                        item = {
                          FieldName: element.jobmeta,
                          FieldValue: "",
                          isexcelmeta: element.isexcelmeta,
                          isrequired: element.isrequired,
                          inputtype: element.inputtype,
                          Fieldselectoption: element.inputvalueoption,
                        };
                      } else {
                        item = {
                          FieldName: element.jobmeta,
                          FieldValue: "",
                          isexcelmeta: element.isexcelmeta,
                          isrequired: element.isrequired,
                          inputtype: element.inputtype,
                          Fieldselectoption: element.inputvalueoption,
                        };
                        if (element.jobmeta == "Bid Number") {
                          this.showbidnumber = true;
                        }
                      }
                      this.jobmetalst.push(item);
                    }
                  }
                }); 
              });


              console.log("testing");
              console.log(this.jobmetalst);
            } else {
              this.jobMetadata.forEach((element) => {
                debugger;
                //lmd.isexcelmeta === true && lmd.FieldValue != null  && lmd.FieldValue != undefined && lmd.FieldValue != ''
                if (
                  (element.isexcelmeta === true &&
                    element.isrequired === true &&
                    element.FieldValue != null &&
                    element.FieldValue != undefined &&
                    element.FieldValue != "") ||
                  (element.isexcelmeta == false &&
                    element.isrequired === true) ||
                    (element.isexcelmeta == false &&
                      element.isrequired === false) ||
                  (element.isexcelmeta === true &&
                    element.isrequired === false &&
                    element.FieldValue != null &&
                    element.FieldValue != undefined &&
                    element.FieldValue != "")
                ) {
                  if (element.inputtype === "dropdown" || element.inputtype === "checkbox") {
                    item = {
                      FieldName: element.jobmeta,
                      FieldValue: "",
                      isexcelmeta: element.isexcelmeta,
                      isrequired: element.isrequired,
                      inputtype: element.inputtype,
                      Fieldselectoption: element.inputvalueoption,
                    };
                  } else {
                    item = {
                      FieldName: element.jobmeta,
                      FieldValue: "",
                      isexcelmeta: element.isexcelmeta,
                      isrequired: element.isrequired,
                      inputtype: element.inputtype,
                      Fieldselectoption: element.inputvalueoption,
                    };
                    if (element.jobmeta == "Bid Number") {
                      this.showbidnumber = true;
                    }

                  }
                  this.jobmetalst.push(item);
                }
              });
            }
//tas
this.jobmetalst.forEach(obj => {
  if (obj.isexcelmeta === true) {
    obj.Isdisplay = true;
  } else {
    obj.Isdisplay = false;
  }
});


          }
        }
      },
      (err) => {
        this.toastr.error("Error While geting JobMetaData");
      }
    );
  }

  Add_Lot_Meta_Data(item) {
    if (this.olua_area == true) {
      if (this.selected_lots.length != 0) {
        this.selected_lots.forEach((lot) => {
          let ind = this.assignedlotlist.findIndex((x) => x.lotid == lot.lotid);
          this.metadata_checked.forEach((element) => {
            let add_meta_check = true;
            let selectarr = this.lotmeta.filter(
              (x) => x.jobmetaid == element.jobmetaid
            );
            console.log(item);
            let item1 = {
              FieldName: selectarr[0].jobmeta,
              FieldValue: "",
              isexcelmeta: selectarr[0].isexcelmeta,
              isrequired: selectarr[0].isrequired,
              inputtype: selectarr[0].inputtype,
              Fieldselectoption: selectarr[0].inputvalueoption,
            };
            if (selectarr[0].jobmeta == "Bid Number") {
              this.showbidnumber = true;
            }
            this.assignedlotlist[ind].lotmeta.forEach((meta) => {
              if (meta.FieldName == item1.FieldName) {
                add_meta_check = false;
              }
            });

            if (add_meta_check == true) {
              this.assignedlotlist[ind].lotmeta.push(item1);
            } else {
              this.list_meta_vaild.push({
                add_meta_check: false,
              });
            }
            this.assignedlotlist[ind].insert_p = 0;
            if (this.list_meta_vaild.length != 0) {
              let ind = this.list_meta_vaild.findIndex(
                (x) => (x.add_meta_check = false)
              );
              if (ind != -1) {
                this.toastr.error("Metadata already added to the lot");
                this.list_meta_vaild = [];
              }
            }
          });
        });
      }
      this.lotMetadatapopup.hide();
      this.selected_lots = [];
      this.metadata_checked = [];
      this.insert_all == 1 ? (this.insert_all = 0) : (this.insert_all = 0);
    } else {
      this.metadata_checked.forEach((element) => {
        let selectarr = this.lotmeta.filter(
          (x) => x.jobmetaid == element.jobmetaid
        );
        console.log(item);
        let item1 = {
          FieldName: selectarr[0].jobmeta,
          FieldValue: "",
          isexcelmeta: selectarr[0].isexcelmeta,
          isrequired: selectarr[0].isrequired,
          inputtype: selectarr[0].inputtype,
          Fieldselectoption: selectarr[0].inputvalueoption,
        };
        if (selectarr[0].jobmeta == "Bid Number") {
          this.showbidnumber = true;
        }
        this.jobmetalst.push(item1);
        this.lotMetadatapopup.hide();
        this.metadata_checked = [];
      });
    }
  }
  AddMetaData(item) {
    item.forEach((element) => {
      if (element.required === true) {
        if (element.fieldvalue === "") {
          this.toastr.error("Please enter the " + element.filedname + " value");
          return;
        }
      }
    });
    const job_ = new Object({
      jobid: this.jobid,
    });
    this.jobmasterservice.getLotByJobId(job_).subscribe(
      (lotres) => {
        this.job_lotlist = JSON.parse(lotres.body[0]);
        var lotres = this.job_lotlist.filter((a) => a.lotmastermetafields);
        console.log(lotres);
        this.job_lotlist.forEach((val) => {
          debugger;
          if (
            val.lotmastermetafields != null &&
            val.lotmastermetafields.length > 0
          ) {
            val.lotmastermetafields.forEach((vals) => {
              debugger;
              if (vals.FieldName === "Project ID") {
                if (vals.FieldValue === this.fieldvalue) {
                  this.toastr.error("Project ID already exist.");
                  return false;
                }
              }
            });
          }
        });
      },
      (error) => {
        this.toastr.error("Error in getting Chapter Master Records");
      }
    );

    if (
      this.selectedfieldid === undefined ||
      this.selectedfieldid === null ||
      this.selectedfieldid === 0
    ) {
      this.toastr.error("Select the field name");
      return false;
    }
    if (
      this.fieldvalue === undefined ||
      this.fieldvalue === null ||
      this.fieldvalue === ""
    ) {
      this.toastr.error("Select the field value");
      return false;
    }
    if (this.metadtalist1.length > 0) {
      var res = this.metadtalist1.filter(
        (a) => a.FieldName === this.selectedfieldid
      );
    }
    if (res && res.length > 0) {
      this.toastr.warning("Field already selected");
      return;
    } else {
      var excelmeta;
      const data = this.jobMetadata.filter(
        (i) => i.jobmetaid === +this.selectedfieldid
      );
      if (data.length > 0) {
        this.selectedfieldname = data[0].jobmeta;
        excelmeta = data[0].isexcelmeta;
      }
      this.metadtalist1.push({
        FieldName: this.selectedfieldname,
        FieldValue: this.fieldvalue,
        isexcelmeta: excelmeta,
      });
    }

    this.selectedfieldid = 0;
    this.fieldvalue = "";
  }

  updatelotmetafields() {
    this.SpinnerService.show();
    this.update_meta_list = [];
    if (this.olua_area == true) {
      for (let i = 0; i < this.selected_lots.length; i++) {
        this.selectedlotitem = {} as LotMaster;
        this.selectedlotitem.lotmastermetafields = JSON.stringify(
          this.selected_lots[i].lotmeta.map((i) => ({
            FieldName: i.FieldName,
            FieldValue: i.FieldValue,
            isexcelmeta: i.isexcelmeta,
            isrequired: i.isrequired,
            inputtype: i.inputtype,
            Fieldselectoption: i.Fieldselectoption,
          }))
        );
        this.selectedlotitem.jobid = this.selected_lots[i].jobid;
        this.selectedlotitem.lotid = this.selected_lots[i].lotid;
        this.selectedlotitem.updatedby = this.userid_pass;
        this.selected_lots[i].lotmeta.forEach((element) => {
          if (element.FieldName == "Company Name") {
            this.selectedlotitem.companyname = element.FieldValue;
          } else if (element.FieldName == "Type") {
            this.selectedlotitem.type = element.FieldValue;
          } else if (element.FieldName == "Ranking") {
            this.selectedlotitem.ranking = element.FieldValue;
          } else if (element.FieldName == "Frequency") {
            this.selectedlotitem.frequency = element.FieldValue;
          } else if (element.FieldName == "City") {
            this.selectedlotitem.city = element.FieldValue;
          } else if (element.FieldName == "State") {
            this.selectedlotitem.state = element.FieldValue;
          } else if (element.FieldName == "Follow Up Date") {
            this.selectedlotitem.followupdate = element.FieldValue;
          } else if (element.FieldName == "Bid Date") {
            this.selectedlotitem.biddate = element.FieldValue;
          } else if (element.FieldName == "Project ID") {
            //this.selectedlotitem.projectid=element.FieldValue;
            this.selectedlotitem.projectid = element.FieldValue.toUpperCase();
          } else if (element.FieldName == "URL") {
            this.selectedlotitem.url = element.FieldValue;
          } else if (element.FieldName == "Project Name") {
            this.selectedlotitem.projectname = element.FieldValue;
          } else if (element.FieldName == "Bid Number") {
            this.selectedlotitem.bidnumber = element.FieldValue;
          }
        });
        this.update_meta_list.push(this.selectedlotitem);
      }
    } else {
      this.selectedlotitem = {} as LotMaster;
      this.selectedlotitem.lotmastermetafields = JSON.stringify(
        this.metadtalist1.map((i) => ({
          FieldName: i.FieldName,
          FieldValue: i.FieldValue,
          isexcelmeta: i.isexcelmeta,
          isrequired: i.isrequired,
          inputtype: i.inputtype,
          Fieldselectoption: i.Fieldselectoption,
        }))
      );
      this.selectedlotitem.jobid = this.jobid;
      this.selectedlotitem.lotid = this.lotid_pass;
      this.selectedlotitem.updatedby = this.userid;
      this.metadtalist1.forEach((element) => {
        if (element.FieldName == "Company Name") {
          this.selectedlotitem.companyname = element.FieldValue;
        } else if (element.FieldName == "Type") {
          this.selectedlotitem.type = element.FieldValue;
        } else if (element.FieldName == "Ranking") {
          this.selectedlotitem.ranking = element.FieldValue;
        } else if (element.FieldName == "Frequency") {
          this.selectedlotitem.frequency = element.FieldValue;
        } else if (element.FieldName == "City") {
          this.selectedlotitem.city = element.FieldValue;
        } else if (element.FieldName == "State") {
          this.selectedlotitem.state = element.FieldValue;
        } else if (element.FieldName == "Follow Up Date") {
          this.selectedlotitem.followupdate = element.FieldValue;
        } else if (element.FieldName == "Bid Date") {
          this.selectedlotitem.biddate = element.FieldValue;
        } else if (element.FieldName == "Project ID") {
          this.selectedlotitem.projectid = element.FieldValue.toUpperCase();
        } else if (element.FieldName == "URL") {
          this.selectedlotitem.url = element.FieldValue;
        } else if (element.FieldName == "Project Name") {
          this.selectedlotitem.projectname = element.FieldValue;
        } else if (element.FieldName == "Bid Number") {
          this.selectedlotitem.bidnumber = element.FieldValue;
        }
      });
      console.log(JSON.stringify(this.metadtalist1));
      console.log(JSON.stringify(this.selectedlotitem));
      this.update_meta_list.push(this.selectedlotitem);
    }
    if (
      this.bid_pass == false &&
      this.bid_data.solicitation != "" &&
      this.bid_data.solicitation != null &&
      this.bid_data.solicitation != undefined &&
      this.bid_data.biddate != "" &&
      this.bid_data.biddate != null &&
      this.bid_data.biddate != undefined
    ) {
      this.collectionprocessservice.InsertBidnumber(this.bid_data).subscribe(
        (res) => {
          this.SpinnerService.hide();
          if (res.status === 200) {
            if (res !== undefined) {
              if (res.body !== 0) {
                this.bid_data = {} as BidNumberMaster;
                this.toastr.success("New Bid Number Added successfully");
              }
            }
          }
        },
        (error) => {
          this.toastr.error("Error while doing the operation");
          this.SpinnerService.hide();
        }
      );
    }

    this.collectionprocessservice
      .Putlotmetafields(this.update_meta_list)
      .subscribe(
        (res) => {
          this.SpinnerService.hide();
          if (res.status === 200) {
            if (res !== undefined) {
              if (res.body !== 0) {
                debugger;
                //18-01-2024
                this.getlotmastermetavalue(this.lotid_pass);
                this.toastr.success("Data updated successfully");
                /*if (
                  this.stagename == "FPR" &&
                  this.automailprojectid != this.projectdefinitionid_pass                  
                ) {
                  */
                  this.transactionid = this.transactionid_pass;
                  this.jobworkflowid = this.jobworkflowid_pass;
                  this.calltype = "checkout";
                  this.cflag = "A";
                  this.add();
               /* } else {
                  this.completeStage(
                    "A",
                    this.worlAreaPopUpTemplate,
                    0,
                    0,
                    0,
                    "comp"
                  );
                }*/
              }
            }
          }
        },
        (error) => {
          this.toastr.error("Error while doing the operation");
          this.SpinnerService.hide();
        }
      );
  }

  getlot() {
    this.collectionprocessservice.GetLotByJobId(this.jobs.jobid).subscribe(
      (lotres) => {
        if (lotres.body[0] != null) {
          this.lots = JSON.parse(lotres.body[0]);
        }
      },
      (error) => {
        this.toastr.error("Error in getting Chapter Master Records");
      }
    );
  }
  savelotinfo(lot, type) {
    if (type == "edit") {
      this.editlot = true;
    } else {
      this.editlot = false;
      this.editable_joburl = lot.job_url;
      this.editable_projid = lot.projectid;
      this.addtbljoblotexcel(this.lotid_pass);
    }
  }
  
  clearForm() {
    this.joburlForm.reset();
    this.joburlForm.controls["joburlid"].setValue(0);
  }
  createjob() {
    this.collectionprocessservice.PostCCJob(this.userid, 349).subscribe(
      (ress) => {
        if (ress.body[0] != null && ress.body[0] !== undefined) {
          this.jobs = JSON.parse(ress.body[0]);
          this.jobid = this.jobs.jobid;
        }
      },
      (error) => {
        this.toastr.error("Error while getting data");
      }
    );
  }

  Post(ccjoburlmaster: Ccjoburlmaster) {
    debugger;
    this.submitted = true;
    this.showcomplete = true;
    ccjoburlmaster.createdby = this.userid;
    // if ((ccjoburlmaster.bitnumber.trim() === undefined) || (ccjoburlmaster.bitnumber.trim() === '')) {
    //   this.toastr.error('Bit number or Project name should not be empty');
    //   return;
    // }
    if (this.joblist) {
      //ccjoburlmaster.projectid=this.joburlForm.value.projectid;
      ccjoburlmaster.projectid = this.joburlForm.value.projectid.toUpperCase();
      ccjoburlmaster.url = this.joburlForm.value.job_url;
      ccjoburlmaster.biddate = this.joburlForm.value.bitnumber;
      if (
        ccjoburlmaster.projectid === undefined ||
        ccjoburlmaster.projectid === ""
      ) {
        this.toastr.error("Project Code should not be empty");
        return;
      }
      if (ccjoburlmaster.url === undefined || ccjoburlmaster.url === "") {
        this.toastr.error("Job URL should not be empty");
        return;
      }
      //new job create
      this.collectionprocessservice.PostCCJob(this.userid, 349).subscribe(
        (ress) => {
          if (ress != null && ress !== undefined) {
            this.jobs = ress;
            this.jobid = this.jobs.jobid;
            ccjoburlmaster.jobid = this.jobid;
            this.collectionprocessservice
              .PostCCLotMaster(ccjoburlmaster)
              .subscribe(
                (res) => {
                  if (res.body[0] != null && res.body[0] !== undefined) {
                    this.lots = JSON.parse(res.body[0]);
                    console.log(JSON.stringify( this.lots));
                    this.toastr.success("Lot created successfully");
                    this.clearForm();
                    this.getlotdeatils();
                  }
                },
                (error) => {
                  this.toastr.error("Error while doing the operation");
                  this.postresult = false;
                }
              );
          }
        },
        (error) => {
          this.toastr.error("Error while getting data");
        }
      );
    } else {
      //existing job
      ccjoburlmaster.jobid = this.jobid;
      if (this.frommyjob) {
        ccjoburlmaster.lotid = this.lotid_pass;
        ccjoburlmaster.option = this.optiontoaddnewlot;
        if (this.optiontoaddnewlot == "updateandisertlot") {
          //update
          if (
            this.lotmastermetafields != null &&
            this.lotmastermetafields != undefined &&
            this.lotmastermetafields != "" &&
            !this.olua_area
          ) {
            let lotmetadata = this.lotmastermetafields.filter(
              (i) => i.isexcelmeta == true
            );
            ccjoburlmaster.lotmastermetafields = JSON.stringify(lotmetadata);
            lotmetadata.forEach((element) => {
              if (element.FieldName == "Company Name") {
                ccjoburlmaster.companyname = element.FieldValue;
              } else if (element.FieldName == "Type") {
                ccjoburlmaster.type = element.FieldValue;
              } else if (element.FieldName == "Ranking") {
                ccjoburlmaster.ranking = element.FieldValue;
              } else if (element.FieldName == "Frequency") {
                ccjoburlmaster.frequency = element.FieldValue;
              } else if (element.FieldName == "City") {
                ccjoburlmaster.city = element.FieldValue;
              } else if (element.FieldName == "State") {
                ccjoburlmaster.state = element.FieldValue;
              } else if (element.FieldName == "Follow Up Date") {
                ccjoburlmaster.followupdate = element.FieldValue;
              } else if (element.FieldName == "Project Name") {
                ccjoburlmaster.projectname = element.FieldValue;
              } else if (element.FieldName == "Bid Number") {
                ccjoburlmaster.bidnumber = element.FieldValue;
              }
            });
          }
          ccjoburlmaster.uniquemailid = this.updated_mailid;
          ccjoburlmaster.parentmailid = this.updated_parentid;
        }
        if (this.olua_area == true) {
          this.selected_lots.forEach((lot) => {
            this.jobid = lot.jobid;
            let lotmetadata = lot.lotmeta.filter((i) => i.isexcelmeta == true);
            ccjoburlmaster.lotmastermetafields = JSON.stringify(lotmetadata);
            lotmetadata.forEach((element) => {
              if (element.FieldName == "Company Name") {
                ccjoburlmaster.companyname = element.FieldValue;
              } else if (element.FieldName == "Type") {
                ccjoburlmaster.type = element.FieldValue;
              } else if (element.FieldName == "Ranking") {
                ccjoburlmaster.ranking = element.FieldValue;
              } else if (element.FieldName == "Frequency") {
                ccjoburlmaster.frequency = element.FieldValue;
              } else if (element.FieldName == "City") {
                ccjoburlmaster.city = element.FieldValue;
              } else if (element.FieldName == "State") {
                ccjoburlmaster.state = element.FieldValue;
              } else if (element.FieldName == "Follow Up Date") {
                ccjoburlmaster.followupdate = element.FieldValue;
              } else if (element.FieldName == "Project Name") {
                ccjoburlmaster.projectname = element.FieldValue;
              } else if (element.FieldName == "Bid Number") {
                ccjoburlmaster.bidnumber = element.FieldValue;
              }
            });
            ccjoburlmaster.createdby = lot.userid;
          });
          ccjoburlmaster.jobid = this.selected_lots[0].jobid;
          ccjoburlmaster.lotid = this.selected_lots[0].lotid;
          // ccjoburlmaster.uniquemailid=this.selected_lots[0].parentmailid;
          //  ccjoburlmaster.parentmailid=this.selected_lots[0].uniquemailid;
        }

        console.log("metadata", ccjoburlmaster);
        this.collectionprocessservice
          .PostCCLotMasterandtrans(ccjoburlmaster)
          .subscribe(
            (res) => {
              console.log("restas",res);
              if (res.body != null && res.body !== undefined) {
                this.newly_craeted_lot=res.body[0].lotid;
                //this.addtbljoblotexcel(res.body[0].lotid);
                this.showcomplete = false;
                console.log(JSON.stringify(res.body ));
                this.toastr.success("Lot updated successfully");
                if (!this.olua_area) this.getlotdeatils();
                this.getassignedlot("addlot");
              }
            },
            (error) => {
              this.toastr.error("Error while doing the operation");
              this.postresult = false;
            }
          );
      } else {
        this.collectionprocessservice.PostCCLotMaster(ccjoburlmaster).subscribe(
          (res) => {
            if (res.body[0] != null && res.body[0] !== undefined) {
              this.lots = JSON.parse(res.body[0]);
              this.toastr.success("Lot created successfully");
              this.clearForm();
              this.getlotdeatils();
            }
          },
          (error) => {
            this.toastr.error("Error while doing the operation");
            this.postresult = false;
          }
        );
      }
    }
  }
  getlotmastermetavalue(lotid) {
    let input = [];
    input.push({ lotid: lotid });
    this.collectionprocessservice.getBylotId(input[0]).subscribe(
      (res) => {
        if (
          res.body !== undefined &&
          res.body !== null &&
          res.body[0] !== undefined &&
          res.body[0] !== null &&
          JSON.parse(res.body[0]).length > 0
        ) {
          // get job workflow
          this.lotmastermetafields = JSON.parse(res.body[0]);
          this.lotmastermetafields =
            this.lotmastermetafields[0].lotmastermetafields;
        }
      },
      (err) => {
        this.toastr.error(err);
      }
    );
  }
  getFirstPart(value)
   {
    if (value && value.includes('-')) {
        return value.split('-')[0];
    }
    return value;
}
  async completeStage(
    cFlag,
    template: TemplateRef<any>,
    lotid,
    tranid,
    jbwfid,
    type
  ) {
    // debugger;
    if (this.olua_area == true) {
      if (this.selected_lots.length == 0) {
        this.toastr.error("Atleast select one lot to completed.");
        return;
      }
    }
    if (type == "norec") {
      this.isaddlot=false;
      let shownotmand = false;
      this.list_meta_vaild = [];
      //check mandatory meta should be empty
      if (this.olua_area == true) {
        this.selected_lots.forEach((lot) => {
          lot.lotmeta.forEach((element) => {
            if (element.isexcelmeta === false && element.isrequired === true) {
              if (
                element.FieldValue != "" &&
                element.FieldValue != undefined &&
                element.FieldValue != null
              ) {
                //this.meta_pass =false;
                this.list_meta_vaild.push({
                  shownotmand: true,
                });
              } else {
                this.list_meta_vaild.push({
                  shownotmand: false,
                });
              }
            }
          });
        });
        let ind = this.list_meta_vaild.findIndex((x) => x.shownotmand == true);
        shownotmand = ind != -1 ? true : false;
        if (shownotmand) {
          this.toastr.error("Mandatory Comment should be empty");
          return;
        }
        this.list_meta_vaild = [];
      } else {
        this.jobmetalst.forEach((element) => {
          if (element.isexcelmeta === false && element.isrequired === true) {
            if (
              element.FieldValue != "" &&
              element.FieldValue != undefined &&
              element.FieldValue != null
            ) {
              //this.meta_pass =false;
              shownotmand = true;
            }
          }
        });
      }
      if (shownotmand) {
        this.toastr.error("Mandatory meta data should be empty");
        return;
      }
    }
    let lot_id = lotid != 0 ? lotid : this.lotid_pass;
    this.transactionid = tranid != 0 ? tranid : this.transactionid_pass;
    this.jobworkflowid = jbwfid != 0 ? jbwfid : this.jobworkflowid_pass;
    if (this.projectdefinitionid_pass == 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(selectedcategoryname=="Already Exist" || selectedcategoryname=="Query"|| selectedcategoryname=="Invalid " || selectedcategoryname=="Broken Agent")

        if (this.selected_categorygroup == 1) {
          this.command = true;
          this.calltype = selectedcategoryname;
          this.selback = this.tojobwkflwid.toString();
          this.cflag = "F";
        } else {
          if (this.olua_area == true) {
            let len = 0;
            this.selected_lots.forEach(async (element) => {
              len = len + 1;
              this.jobmetalst = element.lotmeta;
              await this.checkmandatorymetafilled().then((data1) => {
                if (!this.meta_pass) return;
              });
            });
            let err_meta = this.list_meta_vaild.findIndex(
              (x) => x.meta_pass == false
            );
            let err_bid = this.list_meta_vaild.findIndex(
              (x) => x.biddatecheck == false
            );
            let err_projectid = this.list_meta_vaild.findIndex(
              (x) => x.projectidval == false
            );
            if (err_meta != -1 || err_bid != -1 || err_projectid != -1) {
              this.meta_pass = false;
            }
            if (!this.meta_pass) {
              if (err_meta != -1) {
                this.toastr.error(
                  "Kindly fill the mandatory field and then proceed."
                );
              }
              if (err_bid != -1) {
                this.toastr.error(
                  "Kindly choose the bid date as current or future date only."
                );
              }
              if (err_projectid != -1) {
                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)."
                );
              }
              this.list_meta_vaild = [];
              if (err_meta != -1 || err_bid != -1 || err_projectid != -1) {
                return;
              }
            }
          } else {
            await this.checkmandatorymetafilled().then((data1) => {
              if (!this.meta_pass) return;
            });
          }
          this.calltype = selectedcategoryname;
          this.cflag = "F";
        }
      }
    } else {
      if (type != "norec" && type != "dup") {
        if (this.olua_area == true) {
          let len = 0;
          this.selected_lots.forEach(async (element) => {
            len = len + 1;
            this.jobmetalst = element.lotmeta;
            await this.checkmandatorymetafilled().then((data1) => {
              if (!this.meta_pass) return;
            });
          });
          let err_meta = this.list_meta_vaild.findIndex(
            (x) => x.meta_pass == false
          );
          let err_bid = this.list_meta_vaild.findIndex(
            (x) => x.biddatecheck == false
          );
          let err_projectid = this.list_meta_vaild.findIndex(
            (x) => x.projectidval == false
          );
          if (err_meta != -1 || err_bid != -1 || err_projectid != -1) {
            this.meta_pass = false;
          }
          if (!this.meta_pass) {
            if (err_meta != -1) {
              this.toastr.error(
                "Kindly fill the mandatory field and then proceed."
              );
            }
            if (err_bid != -1) {
              this.toastr.error(
                "Kindly choose the bid date as current or future date only."
              );
            }
            if (err_projectid != -1) {
              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)."
              );
            }
            this.list_meta_vaild = [];
            if (err_meta != -1 || err_bid != -1 || err_projectid != -1) {
              return;
            }
          }
        } else {
          await this.checkmandatorymetafilled().then((data1) => {
            if (!this.meta_pass) return;
          });
        }
      }
      this.command = false;
      if (type == "dup") {
        this.command = true;
        this.calltype = "duplicate";
        this.selback = this.tojobwkflwid.toString();
      } else if (type == "norec") {
        this.command = true;
        this.calltype = "norecord";
        this.selback = this.tojobwkflwid.toString();
      } else {
        this.calltype = "checkout";
      }
      this.cflag = cFlag;
    }
    if (this.entity !== null) {
    }
    this.comments_header = "Comments";
    if (cFlag === "B") {
      this.buttonType = "Correction";
    } else {
      this.buttonType = "Complete";
    }
    this.comments = this.buttonType + " Comments";

    this.workAreaPopUpModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName("modal-content");
    aa[0].classList.remove("modal-content");
  }
  // method to load job details
  loadJobDetails(lotid) {
    debugger;
    this.lotid_pass = lotid;
    this.lotlist_output = [];
    this.lotlist = [];
    this.lotlist_filter = [];
    var inputData = [];
    inputData.push({
      jobid: this.jobid,
      lotid: this.lotid_pass.toString(),
      projectdefinitionid: this.projectdefinitionid_pass,
    });
    this.collectionprocessservice.getJobDetails(inputData[0]).subscribe(
      (res) => {
        if (
          res.body[1] !== undefined &&
          res.body[1] !== null &&
          JSON.parse(res.body[1]).length > 0
        ) {
          //debugger;

          this.jobworkflowid =
            this.jobworkflowid == undefined
              ? this.jobworkflowid_pass
              : this.jobworkflowid;
          if (this.jobworkflowid != "" && this.jobworkflowid != undefined) {
            var stagelist = JSON.parse(res.body[1]);
            this.stagelist_length = stagelist.length;
            var index = stagelist.findIndex(
              (p) => p.jobworkflowid == this.jobworkflowid
            );
            this.uniqueStageTitles = stagelist.slice(
              index + 1,
              stagelist.length
            );
            this.fromorder = stagelist[index].stageorder;
            this.toorder = stagelist[stagelist.length - 1].stageorder;
            this.tojobwkflwid = stagelist[stagelist.length - 1].jobworkflowid;
          }
        }
      },
      (err) => {
        this.toastr.error("Loading Lot detail failed.");
      }
    );
  }
  getmaildetailsbyid() {
    let field = [{ mailid: this.mailid, parentid: this.parentid }];
    let fileData = new FormData();
    fileData.append("model", JSON.stringify(field));
    this.collectionprocessservice.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");
      }
    );
  }
  onprojectidchange(evt,data){
    console.log(data)
    console.log(JSON.stringify(this.selected_lots));
    if(evt.target.value != "" && evt.target.value != undefined && evt.target.value != null){
     if(this.selected_lots.length!=0){
      let lot_ind = this.selected_lots.findIndex(
        (x) => (x.lotid == data.lotid && x.insert_p == 1)
      );
      if(lot_ind <0){
        console.log("call second lot select");
        this.lot_select('',data,'AS'); 
      }   
     }else{
      console.log("call first lot select");
      this.lot_select('',data,'AS');
     } 

    }else{
    if(this.selected_lots.length!=0){
      let lot_ind = this.selected_lots.findIndex(
        (x) => x.lotid == data.lotid && x.insert_p == 1
      );
      console.log(lot_ind);
      if(lot_ind >= 0){
        console.log("call lot UnSelect");
        this.lot_select('',data,'AUS');
        console.log(JSON.stringify(this.selected_lots));
      }
      
     }
    }

  }
  add() {
    if (
      this.command &&
      (this.procomment === null ||
        this.procomment == "" ||
        this.procomment == undefined)
    ) {
      this.toastr.error("Comment should not be empty");
      return;
    }
    let entity_temp = null;
    if (this.procomment === null || this.procomment == undefined) {
      this.procomment = "";
    }
    if (this.selback === null) {
      this.selback = "";
    }
    let fields = [];
    if (this.olua_area == true) {
      this.selected_lots.forEach((lot) => {
        fields.push({
          transid: lot.transactionid,
          jobworkflowid: lot.jobworkflowid,
          option: this.calltype,
          cflag: this.cflag,
          userid: this.userid,
          tostage: this.selback,
          jobid: lot.jobid.toString(),
          comment: this.procomment,
          batchid: "",
          lotid: lot.lotid.toString(),
          fromorder:
            this.fromorder == undefined || this.fromorder == null
              ? ""
              : this.fromorder,
          toorder:
            this.toorder == undefined || this.toorder == null
              ? ""
              : this.toorder,
          skipto: "",
          selected_categorygroup: this.selected_categorygroup,
          lotstatus_checkin: lot.lotmaster_status,
        });
      });
    } else {
      fields = [
        {
          transid: this.transactionid,
          jobworkflowid: this.jobworkflowid,
          option: this.calltype,
          cflag: this.cflag,
          userid: this.userid,
          tostage: this.selback,
          jobid: this.jobid.toString(),
          comment: this.procomment,
          batchid: "",
          lotid: this.lotid_pass.toString(),
          fromorder:
            this.fromorder == undefined || this.fromorder == null
              ? ""
              : this.fromorder,
          toorder:
            this.toorder == undefined || this.toorder == null
              ? ""
              : this.toorder,
          skipto: "",
          selected_categorygroup: this.selected_categorygroup,
        },
      ];
    }
    let fileData = new FormData();
    fileData.append("model", JSON.stringify(fields));
    this.collectionprocessservice.PostUpdateLotTransaction(fileData).subscribe(
      async (res) => {
        if (res.body !== undefined && res.body !== null) {
          console.log("response",res)
          debugger;
          if (this.olua_area == true) {
            this.selectedlot = [];
            this.clearForm();
            this.command = false;
            this.procomment = "";
            this.toastr.success("Saved successfully.");
            this.assign_area=false;
            //this.getlotdeatils();
            if (this.workAreaPopUpModalRef) {
              this.workAreaPopUpModalRef.hide();
            }

            if (
              this.selected_lots.length == this.assignedlotlist.length &&
              !this.isaddlot
            ) {
              this.workarea_checkin("", "exit");
              this.router.navigate(["/dashboard"]);
            } else {
              if (!this.isaddlot) {
                this.command = false;
                this.procomment = "";
                this.fromorder = 0;
                this.toorder = 0;
                this.selback = "";
                this.cflag = "";
                this.calltype = "";
                this.selected_lots = [];
                this.getassignedlot("lot_compeleted");
                return;
              }
            }
          } else {
            this.selectedlot = [];
            this.clearForm();
            this.getlotdeatils();
            this.toastr.success("Saved successfully.");
            if (this.workAreaPopUpModalRef) {
              this.workAreaPopUpModalRef.hide();
            }
          }
          //&& this.calltype != "Bid date too close" && this.calltype != "New Project" && this.calltype != "With Docs"
          if (this.projectdefinitionid_pass == this.automailprojectid) {
            let field = [
              {
                userid: this.userid,
                lotid: this.lotid_pass,
                mailid: this.mailid,
                option: this.calltype,
                tranid: 0,
              },
            ];
            let fileData = new FormData();
            fileData.append("model", JSON.stringify(field));
            this.collectionprocessservice.movemessage(fileData).subscribe(
              (res1) => {
                //debugger;
                if (res1.body !== undefined && res1.body !== null) {
                  if (res1.body[0] != "Mailid not exist") {
                    this.toastr.success("Successfully mail moved to folder");
                    this.updated_mailid = res1.body[0];
                    this.updated_parentid = res1.body[1];
                    // if(this.calltype == "Bid date too close" || this.calltype == "New Project" || this.calltype == "With Docs"){
                    if (this.selected_categorygroup == 2) {
                      if (this.frommyjob) {
                        if (!this.isaddlot) this.getassignedlot("complete");
                        if (this.isaddlot) {
                          this.Post(this.joburlForm.value);
                        }
                      }
                    } else {
                      this.workarea_checkin("", "exit");
                      this.router.navigate(["/dashboard"]);
                    }
                  } else {
                    this.toastr.error(res1.body[0]);
                  }
                }
              },
              (error) => {
                this.toastr.error("Error in moving mail details");
              }
            );
          } else {
            if (
              this.calltype === "checkout" ||this.calltype === "norecord"||this.calltype === "duplicate"||
              this.selected_categorygroup == 2
            ) {
              if (this.frommyjob) {
                if (!this.isaddlot) {
                  if (!this.olua_area) {
                    this.getassignedlot("complete");
                  } else {
                    this.getassignedlot("lot_compeleted");
                  }
                }
                if (this.isaddlot) {
                  this.Post(this.joburlForm.value);
                }
                //this.isaddlot = false;
              }
            } else {
              if (this.olua_area == false) {
                this.workarea_checkin("", "exit");
                this.router.navigate(["/dashboard"]);
              }
             // this.isaddlot = false;
            }
          }
        }
      },
      (err) => {
        this.toastr.error("Error in saving lot details");
      }
    );
  }
  onlotSelect(item: any, opt) {
    this.lotlist_output = [];
    if (opt == "view") {
      this.lotlist_output.push(
        this.alllotdetails.filter((u) => u.lotid === item.lotid)[0]
      );
    } else {
      //  this.lotlist_output.push((this.alllotdetails.filter(u => u.lotid === item[0].lotid))[0]);
      this.lotlist_output.push(item);
    }
    this.selectLotDetails();
  }
  onlotDeSelect(item: any) {
    let res;
    res = this.lotlist_output.findIndex((d) => d.lotid === item.lotid);
    let splic = [];
    splic = this.lotlist_output.splice(res, 1);
    this.selectLotDetails();
  }
  selectLotDetails() {
    if (this.lotlist_output.length > 0) {
      this.lotid = this.lotlist_output[0].lotid;
      this.transactionid = this.lotlist_output[0].transactionid;
      this.jobworkflowid = this.lotlist_output[0].jobworkflowid;
      this.joburlForm.get("job_url").setValue(this.lotlist_output[0].job_url);
      this.joburlForm
        .get("bitnumber")
        .setValue(this.lotlist_output[0].bitnumber);
      this.joburlForm
        .get("projectid")
        .setValue(this.lotlist_output[0].projectid);
      this.orgpjid = this.lotlist_output[0].projectid;
      this.orgurl = this.lotlist_output[0].job_url;
      this.orgbit = this.lotlist_output[0].bitnumber;
      if (
        (this.joburlForm.value.projectid != "" &&
          this.joburlForm.value.projectid != undefined &&
          this.joburlForm.value.projectid != null &&
          this.joburlForm.value.job_url != "" &&
          this.joburlForm.value.job_url != undefined &&
          this.joburlForm.value.job_url != null) ||
        (this.joburlForm.value.bitnumber != "" &&
          this.joburlForm.value.bitnumber != undefined &&
          this.joburlForm.value.bitnumber != null)
      ) {
        this.showcomplete = false;
      }
    } else {
      this.lotid = 0;
      this.transactionid = 0;
      this.jobworkflowid = "";
      this.clearForm();
    }
  }
  onSearchChange(searchValue: string): void {
    if (
      this.orgpjid != this.joburlForm.value.projectid ||
      this.orgurl != this.joburlForm.value.job_url
    ) {
      this.showcomplete = true;
    } else {
      this.showcomplete = false;
    }
  }
  fn_LoadJoblistDetails(projectdefinitionid) {
    this._joblist = [];
    const inputvalue = [];
    inputvalue.push({ projectdefinitionid: +projectdefinitionid });
    this.collectionprocessservice.getJobNo(inputvalue[0]).subscribe(
      (res) => {
        if (
          res !== undefined &&
          res !== null &&
          res.body[0] !== undefined &&
          res.body[0] !== null
        ) {
          if (JSON.parse(res.body[0]).length > 0) {
            this._joblist = JSON.parse(res.body[0]);
            if (this.jobid != 0 && this.jobid != undefined) {
              this.jobtitle = this._joblist.filter(
                (u) => u.jobid === this.jobid
              )[0].title;
            }
          }
        }
      },
      (error) => {
        this.toastr.error("Error while getting data");
      }
    );
  }

  selectstagedetails(eve, search) {
    const currentjobno = +eve ? eve : +eve.target.value;
    this.search = search ? search : eve.target.selectedOptions[0].text;
    this.jobid = currentjobno;
    this.getlotdeatils();
  }

  loadProductType() {
    this._ddlProjecttypeSettings = {
      singleSelection: false,
      idField: "projectdefinitionid",
      textField: "project_subtitle",
      selectAllText: "Select All",
      unSelectAllText: "UnSelect All",
      itemsShowLimit: 7,
      allowSearchFilter: true,
    };
    this.jobmasterservice.getJobProductType(this.userid).subscribe((res) => {
      debugger;
      if (
        res !== undefined &&
        res !== null &&
        res[0] !== undefined &&
        res[0] !== null
      ) {
        if (JSON.parse(res[0]).length > 0) {
          let list: any[];
          list = JSON.parse(res[0]);
          this.jobProductTypeList = list;
        }
      }
    });
  }
  getAll() {
    this.jobs = [];
    const user = new Object({
      userid: this.userid,
    });
    this.jobdefinitionservice.GetAllByUserId(user).subscribe(
      (res) => {
        if (res.body[0] != null && res.body[0] !== undefined) {
          this.jobs = JSON.parse(res.body[0]);
          this.jobsall = JSON.parse(res.body[0]);
          this.jobs = this.jobsall;
          if (this.jobid != 0 && this.jobid != undefined) {
            this.jobtitle = this.jobs.filter(
              (u) => u.jobid === this.jobid
            )[0].title;
          }
        }
      },
      (error) => {
        this.toastr.error("Error while getting data");
      }
    );
  }
  onItemSelect(item: any) {
    this.textBoxTocuhed = true;
    this._producttypeselected.push(item.project_subtitle);
    this.jobs = [];
    this.jobs = this.jobsall.filter((f) =>
      this._producttypeselected.includes(f.project_subtitle)
    );
  }

  onItemDeSelect(item: any) {
    this.textBoxTocuhed = true;
    let res;
    res = this._producttypeselected.findIndex(
      (d) => d === item.project_subtitle
    );
    let splic = [];
    splic = this._producttypeselected.splice(res, 1);
    if (this._producttypeselected.length > 0) {
      this.jobs = [];
      this.jobs = this.jobsall.filter((f) =>
        this._producttypeselected.includes(f.project_subtitle)
      );
    } else if (this._producttypeselected.length === 0) {
      this.jobs = [];
      this.jobs = this.jobsall;
    }
  }

  onSelectAll(item: any) {
    this._producttypeselected = [];
    item.forEach((element) => {
      this._producttypeselected.push(element.project_subtitle);
    });
    this.jobs = [];
    this.jobs = this.jobsall.filter((f) =>
      this._producttypeselected.includes(f.project_subtitle)
    );
  }

  onDeSelectAll(item: any) {
    this.jobs = [];
    this.jobs = this.jobsall;
    this._producttypeselected = [];
  }

  OpenMetaData(template: TemplateRef<any>) {
    this.jobMetaDataModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName("modal-content");
    aa[0].classList.remove("modal-content");
  }
  metaclearform() {
    this.addmetaFrom.reset();
    this.metadataselectinputoptionflag = false;
  }
  addmeta(template: TemplateRef<any>) {
    /*
  this.addmetaFrom.controls['jobmeta'].setValue('');
  this.addmetaFrom.controls['projectdefinitionid'].setValue(Number(this.projectdefinitionid_pass));
  this.addmetaFrom.controls['isexcelmeta'].setValue(0);
  this.addmetaFrom.controls['isrequired'].setValue(0);
  this.addmetaFrom.controls['inputtype'].setValue('0');
  this.addmetaFrom.controls['selectoption'].setValue('');
  this.metadataselectinputoptionflag = false;
  this.selectoptionlist=[];
this.Addmetapopup= this.modalService.show(template,this.config);
const aa = document.getElementsByClassName('modal-content');
aa[0].classList.remove('modal-content');*/
    debugger;
    this.metadata_checked = [];
    if(this.olua_area){
      let temp= [];
      if(this.selected_lots.length == 1){
        this.lotmeta = [];
        this.lotmeta = this.olua_lotmeta;
        temp = this.lotmeta.filter((el) => {
          return !this.selected_lots[0].lotmeta.find((element) => {
            return element.FieldName === el.jobmeta;
          });
        });
        this.lotmeta = temp;
      }else{
        this.lotmeta = [];
        this.lotmeta = this.olua_lotmeta
      }
      //console.log('olua meta removed',temp);
    }else{
      let res = [];
      res = this.lotmeta.filter((el) => {
        return !this.jobmetalst.find((element) => {
          return element.FieldName === el.jobmeta;
        });
      });
      this.lotmeta = res;
     // console.log("meta removed", res);
    }
  

    this.lotMetadatapopup = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName("modal-content");
    aa[0].classList.remove("modal-content");
    this.selectedfieldid = 0;
  }

  addmeta_sumbit(jobmeta) {
    //debugger;
    //console.log(jobmeta);
    if (jobmeta.jobmeta.trim() === undefined || jobmeta.jobmeta.trim() === "") {
      this.toastr.error("Jobmeta should not be empty");
      return;
    }
    if (+jobmeta.isexcelmeta === 0) {
      jobmeta.isexcelmeta = false;
    }
    if (+jobmeta.isrequired === 0) {
      jobmeta.isrequired = false;
    }
    if (+jobmeta.inputtype === 0) {
      this.toastr.error("Kindly choose input type.");
      return;
    } else {
      if (jobmeta.inputtype === "dropdown" || jobmeta.inputtype === "checkbox") {
        if (
          this.selectoptionlist === undefined ||
          this.selectoptionlist === null
        ) {
          this.toastr.error(
            "Kindly enter option list for dropdown type input."
          );
          return;
        }
      }
    }

    let msg = null;

    this.userid = +localStorage.getItem("userid");
    jobmeta.jobmeta = jobmeta.jobmeta.trim();

    jobmeta.inputvalueoption = JSON.stringify(
      this.selectoptionlist.map((i) => ({
        Fieldselectoption: i.Fieldselectoption,
      }))
    );
    jobmeta.createdby = this.userid;
    msg = "Record Added Successfully";
    jobmeta.projectdefinitionid = Number(jobmeta.projectdefinitionid);
    //console.log(jobmeta);
    this.jobMetaService.Post(jobmeta).subscribe(
      (res) => {
        debugger;
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.Addmetapopup.hide();
              this.metadataselectinputoptionflag = false;
              this.selectoptionlist = [];

              this.toastr.success("Data added successfully");
              this.metaclearform();
              this.getJobMetaFields();
            } else {
              this.toastr.warning("Record already exists.");
            }
          }
        }
      },
      (error) => {
        this.toastr.error("Error while doing the operation");
        this.postresult = false;
      }
    );
  }

  onchangeinputtype() {
    if (this.addmetaFrom.controls["inputtype"].value == "dropdown"  || this.addmetaFrom.controls["inputtype"].value  == "checkbox") {
      this.metadataselectinputoptionflag = true;
    } else {
      this.metadataselectinputoptionflag = false;
      this.addmetaFrom.controls["selectoption"].setValue(null);
      this.selectoptionlist = [];
    }
  }
  addselectoptionlist() {
    debugger;
    this.selectoptionlist.push({
      Fieldselectoption: this.addmetaFrom.controls["selectoption"].value,
    });
    this.addmetaFrom.controls["selectoption"].setValue(null);
  }
  updateselectoptionlist(item) {
    const index: number = this.selectoptionlist.indexOf(item);
    if (index !== -1) {
      this.selectoptionlist.splice(index, 1);
    }
  }
  Meta_onItemSelect(item) {
    //debugger;
   // console.log("checked item", this.metadata_checked);
  }
  Meta_onItemDeSelect(item) {
   // debugger;
   // console.log("checked item", this.metadata_checked);
  }
  showmail() {
    //this.mail_url="https://outlook.office.com/mail/inbox/id/AAQkAGNlOWI1ZWNmLThhMGUtNGE5OC05ZTE0LWE4YWU1YzU5NDYxYgAQAJO7fzWIcU4Prxkl9fhRCNg%3D";
    window.open(this.mail_url);
  }
  selectcategory(evt) {
    var categoryname = this.categorylist.filter((x) => x.categoryid == evt)[0]
      .categoryname;
    this.selected_categorygroup = this.categorylist.filter(
      (x) => x.categoryid == evt
    )[0].categorygroup;
    //&& this.calltype != "Bid date too close" && this.calltype != "New Project" && this.calltype != "With Docs"
    //if(categoryname == "Bid date too close" || categoryname == "New Project" || categoryname == "With Docs"){
    if (this.selected_categorygroup == 2) {
      this.addrecnotshoe = false;
    } else {
      this.addrecnotshoe = true;
    }
  }
  openbidnumber(template: TemplateRef<any>) {
    this.solicitation = "";
    this.search_bidlst = [];
    this.Project_name_search = "";
    this.bidNumberPopUpModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName("modal-content");
    aa[0].classList.remove("modal-content");
  }
  onKey(evt){
    debugger;
    console.log(evt);

  }
  async getBidlst(value) {
    debugger;
    console.log(this.solicitation);
    console.log(this.Project_name_search);
    let temp = "";

    if (value != "") {
      this.solicitation = value;
    }
    if (
      this.solicitation != null &&
      this.solicitation != undefined &&
      this.solicitation != ""
    ) {
      if (this.solicitation.includes(",")) {
        let value = this.solicitation.split(",");
        value.forEach((element) => {
          if (temp == "") {
            temp = "%" + element + "%";
          } else {
            temp = temp + "," + "%" + element + "%";
          }
        });
      } else {
        temp = "%" + this.solicitation + "%";
      }
    }
      const input = [
        {
          search: temp,
          companyname:this.companyname,
          projectname:this.Project_name_search
        },
      ];
      this.SpinnerService.show();
      await this.collectionprocessservice
        .Getdatabyname(input[0])
        .subscribe((res) => {
          debugger;
          this.SpinnerService.hide();
          if (res.body != null && res.body != "" && res.body != undefined) {
            this.search_bidlst = JSON.parse(res.body);
          }else{
            this.search_bidlst = [];
          }
        },
        (error) => {
          this.SpinnerService.hide();
          this.toastr.error("Error while getting bid number data");
          this.search_bidlst = [];
        });
 /*    } else {
      this.search_bidlst = [];
    } */
  }
  getbidlist() {
    this.collectionprocessservice.Getbidlist().subscribe((res) => {
      debugger;
      if (res.body != null && res.body != "" && res.body != undefined) {
        this.bidlst = JSON.parse(res.body);
        //console.log("bidlst", this.bidlst);
      }
    });
  }
  checked_metalist(item) {
    //console.log("checked:", item);

    if (this.metadata_checked.length == 0) {
      this.metadata_checked.push(item);
    } else {
      var index = this.metadata_checked.findIndex(
        (x) => x.jobmeta == item.jobmeta
      );
      if (index == -1) {
        this.metadata_checked.push(item);
      } else {
        let temp = [];
        temp = this.metadata_checked.filter((x) => x.jobmeta != item.jobmeta);
        this.metadata_checked = temp;
      }
    }
    //console.log("ngmodel", this.metadata_checked);
  }
  selectdropdown(data){
if(data.FieldName == 'Assignment Types' && this.olua_area){
  this.selected_lots.forEach(element => {
    if(element.insert_p == 1){
      element.lotmeta.forEach(meta =>{
          if(meta.FieldName == 'Assignment Types'){
            meta.FieldValue=data.FieldValue;
          }
      });
    }
  });
}else if(data.FieldName == 'Status' && !this.olua_area){
  console.log(data)
 if(data.FieldValue == "Already Exist" 
 || data.FieldValue == "Invalid" 
 || data.FieldValue == "Completed" 
 || data.FieldValue == "Bid Date too Close" 
 ){
  this.jobmetalst.forEach(obj => {
    if (obj.isexcelmeta === false && (
      obj.FieldName=="Bid Date"
      || obj.FieldName=="Project ID"
      ||  obj.FieldName=="URL"   
      )) {
      obj.Isdisplay = true;
    }
  });

 }else{
  this.jobmetalst.forEach(obj => {
    if (obj.isexcelmeta === true) {
      obj.Isdisplay = true;
    } else {
      obj.Isdisplay = false;
    }
  });
 }
 console.log(JSON.stringify(this.jobmetalst))
 /*  this.jobmetalst.forEach(obj => {
    if (obj.isexcelmeta === true) {
      obj.Isdisplay = false;
    } else {
      obj.Isdisplay = true;
    }
  }); */
}
  }
  lot_select(e, item, mode) {
    debugger;
    if (mode == "M") {
      this.insert_all == 0 ? (this.insert_all = 1) : (this.insert_all = 0);

      if (this.insert_all == 1) {
        this.assignedlotlist.forEach((element) => {
          console.log(element);
          let ind = this.selected_lots.findIndex(
            (x) => x.lotid == element.lotid
          );
          if (ind == -1) {
            element.insert_p = 1;
            this.selected_lots.push(element);
             if(element.lotstatus == 'R' ||  element.lotstatus =='YTS'){
              this.get_checkin(element,'checkin');       
            } 
          }
        });
      } else {
        this.assignedlotlist.forEach((element) => {
          element.insert_p = 0;
           if(element.lotstatus == 'P'){
            this.get_checkin(element,'checkin_reverse');       
          }
        });

        this.selected_lots = [];
      }
     // console.log("selectedc lot", this.selected_lots);
    } else if (mode == "S") {
      this.insert_all == 1 ? (this.insert_all = 0) : (this.insert_all = 0);
      if (e.currentTarget.checked) {
        console.log("check");
        let lot_ind = this.assignedlotlist.findIndex(
          (x) => x.lotid == item.lotid
        );
        this.assignedlotlist[lot_ind].insert_p = 1;
        this.selected_lots.push(item);
        console.log('item',item);
        if(item.lotstatus == 'R' ||  item.lotstatus =='YTS'){
          this.get_checkin(item,'checkin');       
        } 
        if(this.stagename.toString()=="Assignment"){
           var check_selected=[];
          check_selected =this.assignedlotlist.filter(
            (p) => p.insert_p == 1
          );
         if(check_selected.length == 0){
          this.assign_area=false; 
         }else{
          this.assign_area=true; 
         } 

          }
      } else {
        console.log("uncheck");
        let lot_ind = this.assignedlotlist.findIndex(
          (x) => x.lotid == item.lotid
        );
        this.selected_lots.forEach(element => {
          if(element.lotid ==item.lotid){
            element.lotmeta.forEach(meta =>{
                if(meta.FieldName == 'Assignment Types'){
                  meta.FieldValue="";
                }
                if(meta.FieldName == 'Project ID'){
                  meta.FieldValue="";
                }
            });
          }
        });
        this.assignedlotlist[lot_ind].insert_p = 0;
        let ind = this.selected_lots.findIndex((x) => x.lotid == item.lotid);
        if (ind != -1) {
          this.selected_lots.splice(ind, 1);
          this.get_checkin(item,'checkin_reverse'); 
        }
        if(this.stagename.toString()=="Assignment"){
          this.assign_area=false; 
          /*  var un_check_selected=[];
          un_check_selected =this.assignedlotlist.filter(
            (p) => p.insert_p == 0
          );
        if(un_check_selected.length == 0){
         this.assign_area=true; 
        }  */
        }
      }
      console.log(JSON.stringify(this.selected_lots))
    }else if (mode=="AS"){
      this.insert_all == 1 ? (this.insert_all = 0) : (this.insert_all = 0);
      let lot_ind = this.assignedlotlist.findIndex(
        (x) => x.lotid == item.lotid
      );
      this.assignedlotlist[lot_ind].insert_p = 1;
      this.selected_lots.push(item);
      if(item.lotstatus == 'R' ||  item.lotstatus =='YTS'){
        this.get_checkin(item,'checkin');       
      } 
    }else if (mode=="AUS"){
      this.insert_all == 1 ? (this.insert_all = 0) : (this.insert_all = 0);
      let lot_ind = this.assignedlotlist.findIndex(
        (x) => x.lotid == item.lotid
      );
      this.assignedlotlist[lot_ind].insert_p = 0;
      let ind = this.selected_lots.findIndex((x) => x.lotid == item.lotid);
      if (ind != -1) {
        this.selected_lots.splice(ind, 1);
        this.get_checkin(item,'checkin_reverse'); 
      }
    }
  }

  workarea_checkin(item, mode) {
    var data = [];
    if (mode == "checkin") {
      data = [
        {
          userid: this.userid,
          workareastatus: 1,
          lotid: this.lotid,
          jobid: this.jobid,
          transid: this.transactionid,
          projectdefinitionid: this.projectdefinitionid,
          stagename_alias: this.stagename,
          lottitle: "",
          jobtitle: "",
          transstatus: "",
          lotstatus: "",
          createdby: this.userid_pass,
        },
      ];
    } else {
      data = [
        {
          userid: this.userid_pass,
          workareastatus: 0,
          lotid: 0,
          jobid: 0,
          transid: 0,
          projectdefinitionid: 0,
          stagename_alias: "",
          lottitle: "",
          jobtitle: "",
          transstatus: "",
          lotstatus: "",
          updatedby: this.userid_pass,
        },
      ];
    }
    this.collectionprocessservice.workarea_checkin(data[0]).subscribe((res) => {
      //console.log('result',res);
      if (res.body != "" && res.body != null && res.body != undefined) {
      } else {
        console.log("error in workarea checkin");
      }
    });
    //console.log("workarea", item);
  }
  exit() {
    this.workarea_checkin("", "checkout");
    this.router.navigate(["/dashboard"]);
  }

  @HostListener("window:beforeunload", ["$event"])
  unloadhandler(event: Event): void {
    this.workarea_checkin("", "checkout");
  }

  lotMetadataTemplate_close() {
    this.lotMetadatapopup.hide();
    this.metadata_checked = [];
    this.insert_all == 1 ? (this.insert_all = 0) : (this.insert_all = 0);
    this.assignedlotlist.forEach(lot => {
      this.selected_lots.forEach(selected => {
        if(lot.transactionid == selected.transactionid){
          let ind = this.assignedlotlist.findIndex(x=> x.transactionid == lot.transactionid)
          if(ind != -1){
            this.assignedlotlist[ind].insert_p = 0;
          }
        }
      });
    });
    this.selected_lots=[];
  }
}