import { DatePipe } from '@angular/common';
import { Component, OnInit,ViewChild } from '@angular/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'

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

  @ViewChild(MatTabGroup) tabGroup: MatTabGroup;

  tenderData: TenderDetailDto
  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

  showMessage: boolean = false;
  newDRWROW: boolean = false;
  newCvrROW: boolean = false;
  id: number;
  disableUploadButton: boolean;
  userID: string;
  isFileNameDuplicate: boolean;

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

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

     }

    ngOnInit(): void {
      // this.addnoticeROW= true;
      // this.addDrwROW = true;
      this.nitDocuments = [];
      this.workItemDocuments = [];
      this.drawingsDocuments = [];
      this.coverDocs = [];
      
      if(this.tenderID){

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

        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.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;
        // console.log("this.drawingsDocuments===",this.drawingsDocuments);
       }


       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;
        // console.log("this.nitDocuments===",this.nitDocuments);
       }


  
       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;
         // console.log("this.workItemDocuments===",this.workItemDocuments);

       }

      //  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; 
      
    }



    getData(){
      // this._masterService.getMasterData(apiUrl).then((res) =>{
      //   this.AllTenderData = res
      //   console.log("res",res); 
      // })

      this._masterService.getMasterData(apiUrl.TenderType).then((res) =>{
        this.tenderTypeLov = res
         
      })
      this._masterService.getMasterData(apiUrl.emdFeeType).then((res) =>{
        this.emdFeeTypeLov = res
       // console.log("emdFeeTypeLov",this.emdFeeTypeLov); 
         
      })

      
      this._masterService.getMasterData(apiUrl.documentType).then((res) =>{
        this.documentTypeLov = res
     //  console.log("res========================",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.TenderCategory).then((res) =>{
        this.TenderCategoryLov = res
        // console.log("TenderCategoryLov",res);  
      })
      this._masterService.getMasterData(apiUrl.PaymentMode).then((res) =>{
        this.PaymentModeLov = res
        // console.log("PaymentModeLov",res);  
      })

      this._masterService.getMasterData(apiUrl.formcontract).then((res) =>{
        this.formcontractLov = res
        // console.log("formcontractLov",res);  
      })
      this._masterService.getMasterData(apiUrl.productcategory).then((res) =>{
        this.productcategoryLov = res
        // console.log("productcategoryLov",res);  
      })

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

    }

    




    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);
     // console.log('===this.nitDocuments===',this.nitDocuments);
      }
    }

    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);
     // console.log('===this.drawingsDocuments===',this.drawingsDocuments);
      
      }
      
      
    }
    
    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
      //console.log(this.workItemDocuments);
      
    }


    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)=>{
      // console.log("res1===",res.fileName);
      // console.log("res2===",res.fileSizeKB);
      // console.log('======= this.tenderData.tenderDocs==========', this.tenderData.tenderDoc);


      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) {
//         console.log("this.nitDocuments[j].docName",this.nitDocuments[j].docName);
        
//         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)
   // console.log(" this.drawingsDocuments", this.drawingsDocuments);
    this._masterService.postMasterData(apiUrl.drawingUploadDoc,fd,this.id).then((res) =>{
    //  console.log("drawings===",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) {
      // console.log('size is high');
      // 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.orgChain =='' || this.tenderData.orgChain == null || this.tenderData.orgChain == undefined){
      this._ui.toastMessage(this.errorTranslateService.translate("organisationNameCantBeBlank"),2000,true);
     // console.log("errrrr"); 
    }
    else if(this.tenderData.tenderRefNo =='' || this.tenderData.tenderRefNo == null || this.tenderData.tenderRefNo == undefined){
      this._ui.toastMessage(this.errorTranslateService.translate("tenderReferenceNumberCantBeBlank"),2000,true);
    }
     else if(this.tenderData.tenderId =='' || this.tenderData.tenderId == null || this.tenderData.tenderId == undefined){
      this._ui.toastMessage(this.errorTranslateService.translate("tenderIDCantBeBlank"),2000,true);
    } 
    else if( this.tenderData.tenderType == null || this.tenderData.tenderType == undefined){
      this._ui.toastMessage(this.errorTranslateService.translate("tenderTypeCantBeBlank"),2000,true); 
    } 
    else if( this.tenderData.tenderCategory == null || this.tenderData.tenderCategory == undefined){
      this._ui.toastMessage(this.errorTranslateService.translate("tenderCategoryCantBeBlank"),2000,true); 

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

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

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

    // }
    else this.nextTab()

  }

  TenderFeeDetails(){
    if( this.tenderData.tenderFee == null || this.tenderData.tenderFee == undefined){
     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.emdAmt == null || this.tenderData.emdAmt == undefined){
     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.emdPayableTo =='' || this.tenderData.emdPayableTo == null || this.tenderData.emdPayableTo == undefined){
    //   console.log("this.tenderData.emdPayableTo",this.tenderData.emdPayableTo);
      
    //   this._ui.toastMessage(this.errorTranslateService.translate("emdPayableToCantBeBlank"),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 if( this.tenderData.emdPercentage == null || this.tenderData.emdPercentage == undefined){
    //   this._ui.toastMessage(this.errorTranslateService.translate("emdPercentageCantBeBlank"),2000,true);  
    // } 
    
    else this.nextTab()

  }

   
  WorkItemDetails(){
    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("productCategoryCantBeBlank"),2000,true);
    }
    else if(this.tenderData.subCategory =='' || this.tenderData.subCategory == null || this.tenderData.subCategory == 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(){

   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()

  }


  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
    

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

    }
    if(this.tenderDocumnetsPreCheck() ){
    // this.nextTab()
    this.tenderData.tenderDoc = this.nitDocuments.concat(this.workItemDocuments, this.drawingsDocuments)
 
    this._masterService.saveAllMasterData(apiUrl.AllTenderData,this.tenderData).then((res)=>{

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

        this.router.navigate(['/dashboard']);
        
      }
      
    }, (err) =>{
      if(err.status != 201){
        console.log("-error-");
        Swal.fire({
          icon: 'error',
          title: 'Oops...',
          text: 'Something went wrong!',
          
        })
        
      }
    });



    }
  }

  
  


  submit(){
    this.tenderData.crud = 'I' 
   // console.log('onsub---',this.tenderData);
    
    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)=>{
     // console.log('successssssssss========',res);
      this.id = res['id']
      this.tenderData = res
    //  console.log('this.id========',this.id);

      if(res){
        Swal.fire(
          'Created',
          'Tender Details created successfully',
          'success'
        )
        this.nextTab()
        
      }
      
    }, (err) =>{
      if(err.status != 201){
        console.log("-error-");
        Swal.fire({
          icon: 'error',
          title: 'Oops...',
          text: 'Something went wrong!',
          
        })
        
      }
    });

  }

  

  nextTab() {
    // console.log("dtaa=",this.tenderData);
    const selectedIndex = this.tabGroup.selectedIndex;
    const tabCount = this.tabGroup._tabs.length;

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

  prevTab() {
    // console.log("dtaa=",this.tenderData);
    
    const selectedIndex = this.tabGroup.selectedIndex;

    if (selectedIndex > 0) {
      this.tabGroup.selectedIndex = selectedIndex - 1;
    }
  }
  display(){
   // console.log('ddddaaatttaa===',this.tenderData);
    
  }

}


