import { DatePipe } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { UntypedFormControl, UntypedFormGroup } from '@angular/forms';
import { MatOption } from '@angular/material/core';
import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar';
import { MatTabGroup } from '@angular/material/tabs';
import { ActivatedRoute, Router } from '@angular/router';
import { TenderCoversDto } from 'src/app/_dto/tender-covers.dto';
import { TenderDetailDto } from 'src/app/_dto/tender-detail.dto';
import { TenderDocumentDto } from 'src/app/_dto/tender-documents.dto';
import { apiUrl } from 'src/app/_providers/_resources/api-url.properties';
import { ErrorTranslateService } from 'src/app/_providers/_services/error-translate.service';
import { MasterService } from 'src/app/_providers/_services/master.service';
import { UiService } from 'src/app/_providers/_services/ui.service';
import Swal from 'sweetalert2';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { tenderSubcategoryMasterDto } from 'src/app/_dto/tenderSubcategoryMaster.dto';
import { closedTenderUsersDto } from 'src/app/_dto/closedTenderUsers.dto';
import { log } from 'console';

@Component({
  selector: 'app-add-tenders',
  templateUrl: './add-tenders.component.html',
  styleUrls: ['./add-tenders.component.scss']
})
export class AddTendersComponent implements OnInit {

  @ViewChild(MatTabGroup) tabGroup: MatTabGroup;

  @ViewChild('allSelection') private allSelection: MatOption;

  @ViewChild('allUser') private allUser: MatOption;


  tenderData: TenderDetailDto
  subCategoryData: tenderSubcategoryMasterDto[];
  tenderTypeLov: any;
  TenderCategoryLov: any;
  PaymentModeLov: any[];
  formcontractLov: any;
  productcategoryLov: any;
  AllTenderData: TenderDetailDto;
  emdFeeTypeLov: any;
  seculevel: any;
  documentTypeLov: any;
  isNITDocUploaded: boolean = false;
  isWIDocUploaded: boolean = false;
  toggleValue: boolean = true;

  nitDocuments: TenderDocumentDto[];
  workItemDocuments: TenderDocumentDto[];
  drawingsDocuments: TenderDocumentDto[];
  coverDocs: TenderCoversDto[];
  selectedFiles: any;
  tenderID: number;
  filteredDocumentTypeLov: any;
  filteredDocumentDrawingTypeLov: any;
  filteredDocumentNITTypeLov: any;
  coverslov: any;
  fileformatlov: any;
  addnoticeROW: boolean = true
  addDrwROW: boolean = true
  allCheck: boolean = false;
  showMessage: boolean = false;
  newDRWROW: boolean = false;
  newCvrROW: boolean = false;
  id: number;
  disableUploadButton: boolean;
  userID: string;
  isFileNameDuplicate: boolean;
  value: any;
  subcategoryLov: any;
  subcategoryform: UntypedFormGroup;
  userform: UntypedFormGroup;
  userLov: any;
  closedtenderData: closedTenderUsersDto;
  selectedUsers: any[];
  selectAllChecked: boolean = false;

  selectUserTabView: boolean = false;
  categoryEdit: boolean = false;
  data: any;
  noData: boolean = true;
  searchTerm: string = '';
  filter: string;
  pageLength: number;
  userDataCopy: any;
  savedSubcategories: any[];
  currentDate: Date;
  date: Date;
  emdDisable: boolean;
  paymentModeOnline: boolean = false;

  constructor(private router: Router,
    private _masterService: MasterService,
    private _ui: UiService,
    private route: ActivatedRoute,
    private errorTranslateService: ErrorTranslateService,
    private datePipe: DatePipe,
    private fb: FormBuilder,
    private snackBar: MatSnackBar) {

    this.seculevel = localStorage.getItem('seculevel')
    this.userID = localStorage.getItem('userId')
    this.tenderData = new TenderDetailDto();
    this.closedtenderData = new closedTenderUsersDto();
    this.tenderID = +this.route.snapshot.paramMap.get('id');
    this.getData()

  }

  ngOnInit(): void {
    // this.addnoticeROW= true;


    this.subcategoryform = this.fb.group({
      subCategory: new UntypedFormControl(''),

    });

    this.userform = this.fb.group({
      users: new UntypedFormControl(''),
    });
    // this.addDrwROW = true;
    this.nitDocuments = [];
    this.workItemDocuments = [];
    this.drawingsDocuments = [];
    this.coverDocs = [];
    this.subCategoryData = [];
    this.selectedUsers = [];

    //       if(this.tenderID){

    //       this._masterService.getMasterDatabyId(apiUrl.AllTenderData,this.tenderID).then((res) =>{
    //         this.tenderData = res 
    //         if(this.tenderData.productCategory)        {
    //           this._masterService.getMasterData(`${apiUrl.subcategory}?where[tenderCategory]=${this.tenderData.productCategory}`).then((res) =>{
    //             this.subcategoryLov = res
    //            })

    //            if(this.tenderData.tenderType==7 ){

    //             this.selectUserTabView=true

    //           }else{
    //             this.selectUserTabView=false;

    //           }

    //           // let newDate =new Date(); 

    //           // if(this.tenderData.publishDate < newDate){
    //           //   this.categoryEdit=true;

    //           // }else{
    //           //   this.categoryEdit=false;


    //           // }

    //           if(!this.tenderData.id){
    //             this.categoryEdit=false;

    //           }else{
    //             this.categoryEdit=true;

    //           }
    //         }

    //         this.tenderData.publishDate =   this.convertDateFormat(res.publishDate) ;
    //         this.tenderData.saleStartDate =   this.convertDateFormat(res.saleStartDate);
    //         this.tenderData.clarificationStartDate =   this.convertDateFormat(res.clarificationStartDate);
    //         this.tenderData.saleEndDate =   this.convertDateFormat(res.saleEndDate);
    //         this.tenderData.clarificationEndDate =   this.convertDateFormat(res.clarificationEndDate);
    //         this.tenderData.bidSubStartDate =   this.convertDateFormat(res.bidSubStartDate);
    //         this.tenderData.bidSubEndDate =   this.convertDateFormat(res.bidSubEndDate);
    //         this.tenderData.bidOpenDate =   this.convertDateFormat(res.bidOpenDate);
    //         this.tenderData.preBidDate = this.convertDateFormat(res.preBidDate);
    //         // this.subcategoryform.controls.subCategory.patchValue([res.subCategoryMaster.subCategoryId, 0]);


    //         if(this.selectUserTabView && this.tenderData.closedTenderUsers && this.tenderData.closedTenderUsers.length>0)
    //         for(let users of  this.tenderData.closedTenderUsers){
    //           this.userLov.forEach(element => {
    //             if(users.userId == element.userId){
    //               element.selected = true;
    //               let temp = {}
    //               temp = {tenderId:this.tenderID,userId:element.userId}
    //               this.selectedUsers.push(temp);
    //             } 
    //           }); 
    //         }
    // const subCategoryIds = res.subCategoryMaster.map(item => item.id);
    // this.subcategoryform.controls.subCategory.patchValue([...subCategoryIds, 0]);



    //         this.coverDocs = JSON.parse(JSON.stringify(this.tenderData.covers));
    //       this.newCvrROW =true
    //       this.newDRWROW =true

    //       this.drawingsDocuments =  this.tenderData.tenderDoc.filter(element=> element.documentCategory == 'D');
    //       for(let i=0;i<this.drawingsDocuments.length;i++){
    //          this.drawingsDocuments[i].file = this.drawingsDocuments[i].docName; 
    //        }


    //        this.nitDocuments =  this.tenderData.tenderDoc.filter(element=> element.documentCategory == 'NIT');
    //        for(let i=0;i<this.nitDocuments.length;i++){
    //          this.nitDocuments[i].file = this.nitDocuments[i].docName;

    //        }



    //        this.workItemDocuments = this.tenderData.tenderDoc.filter(element=>  element.documentCategory == 'WID');
    //        for(let i=0;i<this.workItemDocuments.length;i++){  
    //          this.workItemDocuments[i].file = this.workItemDocuments[i].docName;
    //      

    //        }

    //       //  if(res.fileName.length > 0){
    //       //   this.disableUploadButton = false
    //       //  }else{
    //       //   this.disableUploadButton = true
    //       //  }
    //       })

    //     }



  }
  convertDateFormat(dateString: string): string {
    const date = new Date(dateString);
    return this.datePipe.transform(date, 'yyyy-MM-ddTHH:mm');
  }


  addNoticeToggle(event) {
    this.addnoticeROW = !event.checked;

  }

  addDrawingToggle(event) {
    this.addDrwROW = !event.checked;

  }


  tenderTypeChange() {

    if (this.tenderData.tenderType == 7) {
      this.selectUserTabView = true;

    } else {
      this.selectUserTabView = false;

    }


  }

  getData() {

    this._masterService.getMasterData(apiUrl.TenderType).then((res) => {
      this.tenderTypeLov = res;

      if (this.tenderData.tenderType == 7) {

        this.selectUserTabView = true

      } else {
        this.selectUserTabView = false;

      }

    })
    this._masterService.getMasterData(apiUrl.emdFeeType).then((res) => {
      this.emdFeeTypeLov = res


    })


    this._masterService.getMasterData(apiUrl.documentType).then((res) => {
      this.documentTypeLov = res

      this.filteredDocumentDrawingTypeLov = this.documentTypeLov.filter(docType => docType.docCategory === 'D');
      this.filteredDocumentNITTypeLov = this.documentTypeLov.filter(docType => docType.docCategory === 'N');

      this.filteredDocumentTypeLov = this.documentTypeLov.filter(docType => docType.docCategory == 'WID');

    })

    this._masterService.getMasterData(apiUrl.basicCategory).then((res) => {
      this.TenderCategoryLov = res

    })
    this._masterService.getMasterData(apiUrl.PaymentMode).then((res) => {
      this.PaymentModeLov = res

    })

    this._masterService.getMasterData(apiUrl.formcontract).then((res) => {
      this.formcontractLov = res

    })
    this._masterService.getMasterData(apiUrl.category).then((res) => {
      this.productcategoryLov = res

    })

    this._masterService.getMasterData(apiUrl.coverslov).then((res) => {
      this.coverslov = res

    })
    this._masterService.getMasterData(apiUrl.fileformatlov).then((res) => {
      this.fileformatlov = res

    })


  }

  paymentModeChange(paymentModeId) {
    let paymentMode;

    this.PaymentModeLov.forEach(element => {
      if (element.id == paymentModeId) {
        paymentMode = element.paymentMode;
      }
    });


    if (paymentMode == 'Online') {
      this.paymentModeOnline = true;
    }
    else {
      this.paymentModeOnline = false;

    }
  }


  emdFeeApplicableChange(emdfeeeApplicable) {

    if (emdfeeeApplicable) {

      this.emdDisable = false;
    }
    else if (emdfeeeApplicable == false) {
      this.emdDisable = true;
      this.tenderData.emdAmt = null;
      this.tenderData.emdFeeType = null;
      this.tenderData.emdPayableTo = null;
      this.tenderData.allowEmdBgOrSt = null;

    }

  }



  productCategoryChange(value) {

    this._masterService.getMasterData(`${apiUrl.subcategory}?where[tenderCategory]=${value}`).then((res) => {
      this.subcategoryLov = res

    })

    // this._masterService.getMasterDatabyId(apiUrl.users, value).then((res) => {
    //   this.userLov = res;
    //   this.userDataCopy = res;

    //   this.userLov.forEach(element => {
    //     element.selected = false;
    //   });


    // })
  }




  addNewNitDocRow() {
    if (this.addnoticeROW) {
      this._ui.toastMessage(this.errorTranslateService.translate("pleaseEnableNoticeDocuments"), 2000, false);

    } else {
      const lastRow = new TenderDocumentDto();
      let newRow = Object.assign({}, lastRow);
      newRow.documentCategory = 'NIT'
      newRow.crud = 'I'
      newRow.userId = this.userID
      this.nitDocuments.push(newRow);
    }
  }

  addNewDrawingRow() {
    if (this.addDrwROW) {
      this._ui.toastMessage(this.errorTranslateService.translate("pleaseEnableDrawingDocuments"), 2000, false);

    } else {
      const lastRow = new TenderDocumentDto();
      let newRow = Object.assign({}, lastRow);
      newRow.documentCategory = 'D'
      newRow.crud = 'I'
      newRow.userId = this.userID
      this.drawingsDocuments.push(newRow);

    }


  }

  addNewWorkItemDocRow() {

    // const lastRow = this.tenderData.tenderDocs[this.tenderData.tenderDocs.length - 1];
    const lastRow = new TenderDocumentDto();
    const newRow = Object.assign({}, lastRow);
    newRow.documentCategory = 'WID'
    newRow.crud = 'I'
    newRow.userId = this.userID
    this.workItemDocuments.push(newRow);
    this.newDRWROW = true

  }


  addNewcoverDocRow() {

    const lastRow = new TenderCoversDto();
    const newRow = Object.assign({}, lastRow);
    // newRow.documentCategory = 'C'
    newRow.crud = 'I'
    this.coverDocs.push(newRow);
    this.newCvrROW = true
  }




  UploadFiles(event, i, type) {

    if (this.workItemDocuments[i].file) {
      this._ui.toastMessage(this.errorTranslateService.translate("Pleasedeletetheexistingfile"), 4000, false);


    } else {

      this.selectedFiles = event.target.files;
      let file = event.target.files[0]
      const fd = new FormData();
      fd.append('file', file);


      if (file && this.id)
        this._masterService.postMasterData(apiUrl.docUpload, fd, this.id).then((res) => {



          if (type == 'WID') {
            //   this.nitDocuments[i].docName = res.fileName
            //   this.nitDocuments[i].file = res.fileName
            //   this.nitDocuments[i].documentSize =res.fileSizeKB;
            // }
            // else{

            this.workItemDocuments[i].docName = res.fileName
            this.workItemDocuments[i].file = res.fileName
            this.workItemDocuments[i].documentSize = res.fileSizeKB;
          }
        })
    }


  }
  //  UploadNoticeFiles(event,i,type){

  //   if(this.nitDocuments[i].file){
  //         this._ui.toastMessage(this.errorTranslateService.translate("Pleasedeletetheexistingfile"),4000,false);     
  //     }else{

  //      for (let j = 0; j < this.nitDocuments.length; j++) {

  //       this.selectedFiles = event.target.files;
  //       let file = event.target.files[0]
  //       const fd = new FormData();
  //       fd.append('file', file);

  //       if (this.nitDocuments[j].docName === file.name) { 

  //         this._ui.toastMessage(this.errorTranslateService.translate("documentnamecantbesame"),4000,false);
  //         file.name = "";
  //       }
  //      if(file && this.id){
  //       this._masterService.postMasterData(apiUrl.nitUploadDoc,fd,this.id).then((res)=>{


  //        if(type == 'NIT'){
  //          this.nitDocuments[i].docName = res.fileName
  //          this.nitDocuments[i].file = res.fileName
  //          this.nitDocuments[i].documentSize =res.fileSizeKB;
  //        }
  //       })}

  //   }
  //  }      
  // }

  UploadNoticeFiles(event: any, i: number, type: string) {
    if (this.nitDocuments[i].file) {
      this._ui.toastMessage(this.errorTranslateService.translate("Pleasedeletetheexistingfile"), 4000, false);
      return;
    }

    let file: File | undefined = event.target.files[0];
    if (!file) {
      return;
    }

    const isFileNameDuplicate = this.nitDocuments.some((doc) => doc.docName === file!.name);
    if (isFileNameDuplicate) {
      this._ui.toastMessage(this.errorTranslateService.translate("documentnamecantbesame"), 4000, false);
      return;
    }

    const fd = new FormData();
    fd.append('file', file, file.name);
    if (file && this.id) {
      this._masterService.postMasterData(apiUrl.nitUploadDoc, fd, this.id)
        .then((res) => {
          if (type == 'NIT') {
            this.nitDocuments[i].docName = res.fileName
            this.nitDocuments[i].file = res.fileName
            this.nitDocuments[i].documentSize = res.fileSizeKB;
          }

        })
        .catch((error) => {

        });
    }
  }


  UploadDrawingFiles(event, i) {

    if (this.drawingsDocuments[i].file) {
      this._ui.toastMessage(this.errorTranslateService.translate("Pleasedeletetheexistingfile"), 4000, false);


    } else {


      this.selectedFiles = event.target.files;
      let file = event.target.files[0]
      const fd = new FormData();
      fd.append('file', file);
      if (file && this.id)
        this._masterService.postMasterData(apiUrl.drawingUploadDoc, fd, this.id).then((res) => {

          this.drawingsDocuments[i].docName = res.fileName
          this.drawingsDocuments[i].file = res.fileName;
          this.drawingsDocuments[i].documentSize = res.fileSizeKB;

        })
    }

  }


  deleteDrawingsRow(id, index: number) {

    this._masterService.deleteMasterData(apiUrl.drawingsDelete, `${this.id}/${this.drawingsDocuments[index].docName}`)

    let removeRow = Object.assign({}, (this.drawingsDocuments).splice(index, 1)[0]);
    // this.nitDocuments.push(removeRow);

  }
  deleteNITRow(id, index: number) {
    this._masterService.deleteMasterData(apiUrl.noticeDelete, `${this.id}/${this.nitDocuments[index].docName}`)
    let removeRow = Object.assign({}, (this.nitDocuments).splice(index, 1)[0]);
    // this.workItemDocuments.push(removeRow);

  }
  deleteWIDRow(id, index: number) {
    this._masterService.deleteMasterData(apiUrl.widDelete, `${this.id}/${this.workItemDocuments[index].docName}`)
    let removeRow = Object.assign({}, (this.workItemDocuments).splice(index, 1)[0]);
    // this.workItemDocuments.push(removeRow);

  }

  deleteCoverRow(id, index: number) {

    let removeRow = Object.assign({}, (this.coverDocs).splice(index, 1)[0]);
    // removeRow.crud = 'D';
    this.tenderData.covers[index].crud = 'D';


  }

  // UploadCoverFiles(event,i){
  //   this.selectedFiles = event.target.files;
  //   let file = event.target.files[0]
  //  const fd = new FormData();
  // fd.append('file', file);
  // if(file && this.tenderData.tenderId){
  // coverDocs
  // }

  // }


  readUrl(event: any) {

    // if (event.target.files && event.target.files[0]) {

    //   if (event.target.files[0].type === 'image/jpeg' ||
    //     event.target.files[0].type === 'image/png' ||
    //     event.target.files[0].type === 'image/jpg') {
    //     if (event.target.files[0].size < 200 * 200) {/* Checking height * width*/ }
    //     if (event.target.files[0].size < 1000000) {


    //     }
    //   }
    // }
  }


  navigateTo(destination: any) {
    this.router.navigate([destination])
  }

  goToHome() {
    window.location.href = 'https://www.thrickodithanamscb.in/index.html#hero';
  }
  goToContactUs() {
    window.location.href = 'https://www.thrickodithanamscb.in/index.html#contact';
  }


  BasicDetails() {

    if (this.tenderData.tenderCategory == null || this.tenderData.tenderCategory == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("tenderCategoryCantBeBlank"), 2000, true);
    }
    // if (this.tenderData.tenderType == null || this.tenderData.tenderType == undefined) {
    //   this._ui.toastMessage(this.errorTranslateService.translate("tenderTypeCantBeBlank"), 2000, true);
    // }
    else this.nextTab()

  }

  TenderFeeDetails() {
    if (this.paymentModeOnline) {
      if (this.tenderData.tenderFee == null || this.tenderData.tenderFee == undefined || this.tenderData.tenderFee < 1) {
        this._ui.toastMessage(this.errorTranslateService.translate("tenderFeeInCantBeBlank"), 2000, true);
      }
      //  else if(this.tenderData.feePayableTo =='' || this.tenderData.feePayableTo == null || this.tenderData.feePayableTo == undefined){
      //  this._ui.toastMessage(this.errorTranslateService.translate("feePayableToCantBeBlank"),2000,true); 
      // }
      else if (this.tenderData.tenderFeeExemption == null || this.tenderData.tenderFeeExemption == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("tenderFeeExemptionAllowedCantBeBlank"), 2000, true);
      }
      // else if(this.tenderData.feePayableAt =='' || this.tenderData.feePayableAt == null || this.tenderData.feePayableAt == undefined){
      //  this._ui.toastMessage(this.errorTranslateService.translate("feePayableAtCantBeBlank"),2000,true); 
      // } 
      else this.nextTab()
    }
  }


  EMDFeeDetails() {

    if (this.tenderData.emdFeeApplied == null || this.tenderData.emdFeeApplied == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("emdApplicableCantBeBlank"), 2000, true);
    }

    else if (this.tenderData.emdFeeApplied) {

      if (this.tenderData.emdAmt == null || this.tenderData.emdAmt == undefined || this.tenderData.emdAmt < 1) {
        this._ui.toastMessage(this.errorTranslateService.translate("emdAmountCantBeBlank"), 2000, true);
      }
      else if (this.tenderData.emdFeeType == '' || this.tenderData.emdFeeType == null || this.tenderData.emdFeeType == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("emdFeeTypeCantBeBlank"), 2000, true);
      }

      else if (this.tenderData.allowEmdBgOrSt == '' || this.tenderData.allowEmdBgOrSt == null || this.tenderData.allowEmdBgOrSt == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("selectEmdThrough"), 2000, true);
      }
      else this.nextTab()

    }

    else this.nextTab()

  }


  WorkItemDetails() {

    if (!this.tenderID && this.subcategoryform.controls.subCategory.value != '' || this.subcategoryform.controls.subCategory.value != null || this.subcategoryform.controls.subCategory.value != undefined) {

      let value = this.subcategoryform.controls.subCategory.value;


      let body = value.map(num => num.toString()).join(',');


      this._masterService.getMasterData(`${apiUrl.users}?where[subCategory]=${body}`).then((res) => {
        this.userLov = res;
        this.userDataCopy = res;

        this.userLov.forEach(element => {
          element.selected = false;
        });


      })

    }

    if (this.tenderData.title == '' || this.tenderData.title == null || this.tenderData.title == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("titleCantBeBlank"), 2000, true);
    }
    else if (this.tenderData.workDesc == '' || this.tenderData.workDesc == null || this.tenderData.workDesc == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("workDescriptionCantBeBlank"), 2000, true);
    }

    // else if( this.tenderData.tenderValue == null || this.tenderData.tenderValue == undefined){
    //   this._ui.toastMessage(this.errorTranslateService.translate("tenderValueCantBeBlank"),2000,true); 
    // }
    else if (this.tenderData.productCategory == null || this.tenderData.productCategory == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("categorycantBeBlank"), 2000, true);
    }
    else if (!this.tenderID && this.subcategoryform.controls.subCategory.value == '' || this.subcategoryform.controls.subCategory.value == null || this.subcategoryform.controls.subCategory.value == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("subCategoryCantBeBlank"), 2000, true);
    }
    else if (this.tenderData.ndaPreQualification == '' || this.tenderData.ndaPreQualification == null || this.tenderData.ndaPreQualification == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("preQualificationCantBeBlank"), 2000, true);
    }
    else if (this.tenderData.bidValidity == null || this.tenderData.bidValidity == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("bidValidityCantBeBlank"), 2000, true);
    }

    else if (this.tenderData.periodOfWork == null || this.tenderData.periodOfWork == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("periodOfWorkCantBeBlank"), 2000, true);
    }
    else if (this.tenderData.location == '' || this.tenderData.location == null || this.tenderData.location == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("locationCantBeBlank"), 2000, true);
    }
    // else if( this.tenderData.pincode == null || this.tenderData.pincode == undefined){
    //   this._ui.toastMessage(this.errorTranslateService.translate("pincodeCantBeBlank"),2000,true); 
    // } 
    // else if(this.tenderData.bidOpeningPlace =='' || this.tenderData.bidOpeningPlace == null || this.tenderData.bidOpeningPlace == undefined){
    //   this._ui.toastMessage(this.errorTranslateService.translate("bidOpeningPlaceCantBeBlank"),2000,true);
    // } 
    // else if(this.tenderData.bidOpenAddress =='' || this.tenderData.bidOpenAddress == null || this.tenderData.bidOpenAddress == undefined){
    //     this._ui.toastMessage(this.errorTranslateService.translate("bidOpenAddressCantBeBlank"),2000,true); 
    //   }

    // else if(this.tenderData.contractType =='' || this.tenderData.contractType == null || this.tenderData.contractType == undefined){
    //   this._ui.toastMessage(this.errorTranslateService.translate("contractTypeCantBeBlank"),2000,true); 
    // }

    // else if( this.tenderData.preBidMeetAdd == '' || this.tenderData.preBidMeetAdd == null || this.tenderData.preBidMeetAdd == undefined){
    //   this._ui.toastMessage(this.errorTranslateService.translate("preBidMeetingAddressCantBeBlank"),2000,true); 
    // }  


    // else if( this.tenderData.preBidDate == null || this.tenderData.preBidDate == undefined){
    //   this._ui.toastMessage(this.errorTranslateService.translate("preBidMeetingDateCantBeBlank"),2000,true); 
    // }

    // else if(this.tenderData.preBidMeetPlace == '' || this.tenderData.preBidMeetPlace == null || this.tenderData.preBidMeetPlace == undefined){
    //   this._ui.toastMessage(this.errorTranslateService.translate("preBidMeetingPlaceCantBeBlank"),2000,true); 
    // }


    else this.nextTab()

  }

  CriticalDates() {
    this.date = new Date();
    const year = this.date.getFullYear();
    const month = String(this.date.getMonth() + 1).padStart(2, '0');
    const day = String(this.date.getDate()).padStart(2, '0');
    const hour = String(this.date.getHours()).padStart(2, '0');
    const minute = String(this.date.getMinutes()).padStart(2, '0');


    const currentDate = `${year}-${month}-${day}T${hour}:${minute}`;


    //publishdate validations

    if (this.tenderData.publishDate < currentDate) {
      this._ui.toastMessage(this.errorTranslateService.translate("publishDateCantBePreviousDate"), 2500, true);

    }

    // document download/ sale start date  validations

    else if (this.tenderData.saleStartDate < this.tenderData.publishDate) {
      this._ui.toastMessage(this.errorTranslateService.translate("ddStartGreterThanPublishD"), 2500, true);
    }
    else if (this.tenderData.saleStartDate < this.tenderData.publishDate || this.tenderData.saleStartDate > this.tenderData.saleEndDate) {
      this._ui.toastMessage(this.errorTranslateService.translate("ddStartGreterThanPublishDLessThanddSakeEndD"), 2500, true);
    }

    //document download / sale end date validations

    else if (this.tenderData.saleEndDate < this.tenderData.publishDate) {
      this._ui.toastMessage(this.errorTranslateService.translate("DDEndGreterThanPublishD"), 2500, true);
    }
    else if (this.tenderData.saleEndDate < this.tenderData.publishDate || this.tenderData.saleStartDate > this.tenderData.bidSubEndDate) {
      this._ui.toastMessage(this.errorTranslateService.translate("DDEndGreterThanPublishDLessThanBidSubEndD"), 2500, true);
    }

    // bid submission start date validations

    else if (this.tenderData.bidSubStartDate < this.tenderData.publishDate) {
      this._ui.toastMessage(this.errorTranslateService.translate("bidSubStartDmustBeGreaterThanPublishDate"), 2500, true);
    }

    else if (this.tenderData.bidSubStartDate < this.tenderData.saleStartDate) {
      this._ui.toastMessage(this.errorTranslateService.translate("bidSubStartDmustBeGreaterThanDocumentDwnldStartD"), 2500, true);
    }

    //bid submission end date validations

    else if (this.tenderData.bidSubEndDate < this.tenderData.publishDate) {
      this._ui.toastMessage(this.errorTranslateService.translate("bidSubEndDmustBeGreaterThanPublishD"), 2500, true);
    }
    else if (this.tenderData.bidSubEndDate < this.tenderData.publishDate || this.tenderData.bidSubEndDate < this.tenderData.bidSubStartDate || this.tenderData.bidSubEndDate < this.tenderData.saleEndDate) {
      this._ui.toastMessage(this.errorTranslateService.translate("bidSubEndDmustBeGreaterThanDocDwnldEndDandbidSubStartD"), 2500, true);
    }

    // bid open date validations

    else if (this.tenderData.bidOpenDate < this.tenderData.publishDate || this.tenderData.bidOpenDate < this.tenderData.saleStartDate ||
      this.tenderData.bidOpenDate < this.tenderData.saleEndDate || this.tenderData.bidOpenDate < this.tenderData.bidSubStartDate ||
      this.tenderData.bidOpenDate < this.tenderData.bidSubEndDate) {
      this._ui.toastMessage(this.errorTranslateService.translate("bidopenDmustBeGreaterThanAllD"), 2000, true);

    }

    // publish date validations 

    else if (this.tenderData.publishDate > this.tenderData.bidOpenDate || this.tenderData.publishDate > this.tenderData.saleStartDate ||
      this.tenderData.publishDate > this.tenderData.saleEndDate || this.tenderData.publishDate > this.tenderData.bidSubStartDate ||
      this.tenderData.publishDate > this.tenderData.bidSubEndDate
    ) {
      this._ui.toastMessage(this.errorTranslateService.translate("publishDmustBeLesserThanAllD"), 2000, true);

    }

    else if (this.tenderData.publishDate == '' || this.tenderData.publishDate == null || this.tenderData.publishDate == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("publishedDateCantBeBlank"), 2000, true);
    }
    else if (this.tenderData.saleStartDate == '' || this.tenderData.saleStartDate == null || this.tenderData.saleStartDate == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("documentDownloadSaleStartCantBeBlank"), 2000, true);
    }
    // else if(  this.tenderData.clarificationStartDate == null || this.tenderData.clarificationStartDate == undefined){
    //   this._ui.toastMessage(this.errorTranslateService.translate("clarificationStartDateCantBeBlank"),2000,true);
    // } 
    else if (this.tenderData.saleEndDate == '' || this.tenderData.saleEndDate == null || this.tenderData.saleEndDate == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("documentDownloadSaleEndCantBeBlank"), 2000, true);
    }
    // else if( this.tenderData.clarificationEndDate == null || this.tenderData.clarificationEndDate == undefined){
    //   this._ui.toastMessage(this.errorTranslateService.translate("clarificationEndDateCantBeBlank"),2000,true);
    // } 
    else if (this.tenderData.bidSubStartDate == '' || this.tenderData.bidSubStartDate == null || this.tenderData.bidSubStartDate == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("bidSubmissionStartDateCantBeBlank"), 2000, true);
    }

    else if (this.tenderData.bidSubEndDate == '' || this.tenderData.bidSubEndDate == null || this.tenderData.bidSubEndDate == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("bidSubmissionEndDateCantBeBlank"), 2000, true);
    }
    else if (this.tenderData.bidSubEndDate && this.tenderData.bidOpenDate && this.tenderData.bidSubEndDate > this.tenderData.bidOpenDate) {
      this._ui.toastMessage(this.errorTranslateService.translate("bidSubmissionEndDateCantBeGreaterThanbidOpeningDate"), 2000, true);
    }

    else if (this.tenderData.bidOpenDate == null || this.tenderData.bidOpenDate == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("bidOpeningDateCantBeBlank"), 2000, true);
    }


    else this.nextTab()

  }

  selectUserNext() {

    if (this.selectedUsers.length <= 0) {
      this._ui.toastMessage(this.errorTranslateService.translate("selectUserCantBeBlank"), 2000, true);
    }
    else this.nextTab()

  }


  tenderDocumnetsPreCheck() {

    for (let i = 0; i < this.drawingsDocuments.length; i++) {
      if (this.drawingsDocuments[i].file == null || this.drawingsDocuments[i].file == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("UploaddocumentCantBeBlank"), 2000, true);
        return false;
      }
      else if (this.drawingsDocuments[i].docType == '' || this.drawingsDocuments[i].docType == null || this.drawingsDocuments[i].docType == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("documentTypeCantBeBlank"), 2000, true);
        return false;
      }
      else if (this.drawingsDocuments[i].description == '' || this.drawingsDocuments[i].description == null || this.drawingsDocuments[i].description == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("descriptionCantBeBlank"), 2000, true);
        return false;
      }
    }

    for (let i = 0; i < this.nitDocuments.length; i++) {
      if (this.nitDocuments[i].file == null || this.nitDocuments[i].file == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("UploaddocumentCantBeBlank"), 2000, true);
        return false;
      }
      else if (this.nitDocuments[i].docType == '' || this.nitDocuments[i].docType == null || this.nitDocuments[i].docType == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("documentTypeCantBeBlank"), 2000, true);
        return false;
      }
      else if (this.nitDocuments[i].description == '' || this.nitDocuments[i].description == null || this.nitDocuments[i].description == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("descriptionCantBeBlank"), 2000, true);
        return false;
      }
    }

    for (let i = 0; i < this.workItemDocuments.length; i++) {
      if (this.workItemDocuments[i].file == null || this.workItemDocuments[i].file == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("UploaddocumentCantBeBlank"), 2000, true);
        return false;
      }
      else if (this.workItemDocuments[i].docType == '' || this.workItemDocuments[i].docType == null || this.workItemDocuments[i].docType == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("documentTypeCantBeBlank"), 2000, true);
        return false;
      }
      else if (this.workItemDocuments[i].description == '' || this.workItemDocuments[i].description == null || this.workItemDocuments[i].description == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("descriptionCantBeBlank"), 2000, true);
        return false;
      }
    }
    return true
  }


  RequiredDocumentsPreCheck() {

    for (let i = 0; i < this.coverDocs.length; i++) {
      if (this.coverDocs[i].coverType == null || this.coverDocs[i].coverType == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("documentTypeCantBeBlank"), 2000, true);
        return false;
      }
      else if (this.coverDocs[i].Description == '' || this.coverDocs[i].Description == null || this.coverDocs[i].Description == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("descriptionCantBeBlank"), 2000, true);
        return false;
      }
      else if (this.coverDocs[i].fileFormat == '' || this.coverDocs[i].fileFormat == null || this.coverDocs[i].fileFormat == undefined) {
        this._ui.toastMessage(this.errorTranslateService.translate("documentFormatCantBeBlank"), 2000, true);
        return false;
      }
    }
    return true

  }



  RequiredDocuments() {
    if (this.RequiredDocumentsPreCheck())
      if (!this.newCvrROW) {
        this._ui.toastMessage(this.errorTranslateService.translate("requiresDocs"), 2000, true);
        return false;

      }
    if (this.RequiredDocumentsPreCheck()) {
      // this.tenderData.covers = this.coverDocs
      this.nextTab()
    }
  }





  TendersDocuments() {
    this.tenderData.id = this.id
    this.tenderData.crud = 'I'
    this.tenderData.covers = this.coverDocs

    this.savedSubcategories = []
    for (let element of this.subcategoryform.controls.subCategory.value) {
      if (element != 0) {
        this.savedSubcategories.push(element)
      }
    }


    for (let i = 0; i < this.savedSubcategories.length; i++) {

      this.subCategoryData[i] = new tenderSubcategoryMasterDto()
      this.subCategoryData[i].tenderId = this.id;

      this.subCategoryData[i].subCategoryId = this.savedSubcategories[i];

    }


    this.tenderData.subCategoryMaster = this.subCategoryData;




    if (this.tenderDocumnetsPreCheck())
      if (!this.newDRWROW) {
        this._ui.toastMessage(this.errorTranslateService.translate("addDocs"), 2000, true);
        return false;

      }
    if (this.tenderDocumnetsPreCheck()) {

      // if(!this.tenderID || this.tenderID !=0){ 
      // this.tenderData.activeYn='S';

      // }
      // this.nextTab()
      this.tenderData.tenderDoc = this.nitDocuments.concat(this.workItemDocuments, this.drawingsDocuments)

      this._masterService.saveAllMasterData(apiUrl.AllTenderData, this.tenderData).then((res) => {



        if (res['tenderTypeD'].id == 7)


          this._masterService.saveMasterData(apiUrl.closedTenderUsers, this.selectedUsers).then(res => {


          })
        if (res) {
          Swal.fire(
            'Created',
            'Tender created successfully',
            'success'
          )

          this.router.navigate(['analyst/dashboard']);

        }

      }, (err) => {

        this._ui.toastMessage(err.error.message);

        if (err.status != 201) {
          Swal.fire({
            icon: 'error',
            title: 'Oops...',
            text: 'Something went wrong!',

          })
          this.tenderData.tenderDoc = [];

        }
      });



    }
  }





  submit() {
    this.tenderData.activeYn = 'S';
    this.tenderData.crud = 'I'
    if (this.tenderData.tenderInvName == '' || this.tenderData.tenderInvName == null || this.tenderData.tenderInvName == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("nameCantBeBlank"), 2000, true);
      return
    }
    if (this.tenderData.tenderInvAddess == '' || this.tenderData.tenderInvAddess == null || this.tenderData.tenderInvAddess == undefined) {
      this._ui.toastMessage(this.errorTranslateService.translate("addressCantBeBlank"), 2000, true);
      return
    }

    this._masterService.saveMasterData(apiUrl.AllTenderData, this.tenderData).then((res) => {

      this.id = res['id']
      this.tenderData = res;

      if (this.selectUserTabView && this.id)
        this.selectedUsers.forEach(element => {
          // let temp = {}
          // temp = {tenderId:this.id,userId:element.userId}
          // this.selectedUsers.push(temp);
          element.tenderId = this.id
        });
      this.savedSubcategories = []

      for (let i = 0; i < res.subCategoryMaster.length; i++) {
        this.savedSubcategories.push(res.subCategoryMaster[i].subCategoryId);
      }



      if (res) {
        Swal.fire(
          'Created',
          'Tender Details created successfully',
          'success'
        )
        this.nextTab()

      }

    }, (err) => {

      this._ui.toastMessage(err.error.message);

      if (err.status != 201) {
        Swal.fire({
          icon: 'error',
          title: 'Oops...',
          text: 'Something went wrong!',

        })

      }
    });

  }



  nextTab() {
    const selectedIndex = this.tabGroup.selectedIndex;
    const tabCount = this.tabGroup._tabs.length;

    if (selectedIndex < tabCount - 1) {
      this.tabGroup.selectedIndex = selectedIndex + 1;
    }
  }

  prevTab() {

    const selectedIndex = this.tabGroup.selectedIndex;

    if (selectedIndex > 0) {
      this.tabGroup.selectedIndex = selectedIndex - 1;
    }
  }
  display() {

  }
  tosslePerOne(field) {

    if (field == 'select') {
      if (this.allSelection.selected) {
        this.allSelection.deselect();
        return false;
      }
      if (this.subcategoryform.controls.subCategory.value.length == this.subcategoryLov.length) {
        this.allSelection.select();
      }
    }
    if (field == 'user') {
      if (this.allUser.selected) {
        this.allUser.deselect();
        return false;
      }
      if (this.userform.controls.users.value.length == this.userLov.length) {
        this.allUser.select();
      }
    }

  }

  toggleAllSelection(field) {
    if (field == 'select') {
      if (this.allSelection.selected) {
        this.subcategoryform.controls.subCategory.patchValue([...this.subcategoryLov.map(item => item.id), 0]);
      } else {
        this.subcategoryform.controls.subCategory.patchValue([]);
      }
    }
    if (field == 'users') {
      if (this.allUser.selected) {

        this.userform.controls.users.patchValue([...this.userLov.map(item => item.userId), 0]);
      } else {

        this.userform.controls.users.patchValue([]);
      }
    }

  }

  //   selectUser(event,userId){

  // if(event.checked=true){
  // this.selectedUsers.tenderId=this.tenderID;
  // this.selectedUsers.userId=userId; 

  // }

  //   }

  //   selectAllUser(event){
  //     if(event.checked=true){

  //     }
  //   }



  selectAllUser(event) {
    if (event.checked) {
      this.selectedUsers = [];

      this.userLov.forEach(user => {
        let temp = {}
        temp = { tenderId: null, userId: user.userId }
        this.selectedUsers.push(temp)
      });
      this.userLov.forEach(element => {
        element.selected = true
      });
      this.allCheck = true;
    } else {
      this.userLov.forEach(element => {
        element.selected = false
      });
      this.selectedUsers = [];
      this.allCheck = false;
    }

    this.selectAllChecked = event.checked;  // Update the state of the "Select All" checkbox

  }


  selectUser(event, userId, index) {
    if (event.checked) {
      let temp = {}
      temp = { tenderId: null, userId: userId }
      this.selectedUsers.push(temp);

      if (this.selectedUsers.length > 0 && this.selectedUsers.length == this.userLov.length) {
        this.allCheck = true;
      }
    } else {
      this.allCheck = false;

      for (let i = 0; i < this.selectedUsers.length; i++) {
        if (this.selectedUsers[i].userId == userId) {
          this.selectedUsers.splice(i, 1);
        }

      }
    }



  }

  search() {
    this.userLov = [...this.userDataCopy]
    this.data = [...this.userLov];
    if (!this.searchTerm || this.searchTerm == null || this.searchTerm == undefined || this.searchTerm == "") {
      this._ui.toastMessage(this.errorTranslateService.translate('enterSearchTerm'), 3000);
      this.getData();
      return;
    }

    this.userLov = this.data.filter(res => {
      let includedInUser = (res.userName) ? res.userName.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
      let includedInUserId = (res.userId) ? res.userId.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
      let includedInUserEmail = (res.email) ? res.email.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;
      let includedInUserPhno = (res.mobileNumber) ? res.mobileNumber.toLowerCase().includes(this.searchTerm.toLowerCase()) : false;

      if (includedInUser || includedInUserId || includedInUserEmail || includedInUserPhno) {

        return true;
      }

      else
        return false;
    });
    // this.noData = (this.data && this.data.length == 0) ? true : false;
    // this.pageLength = this.data.length;
    // this.dataSource = new MatTableDataSource(this.data);
  }
}