import { Component, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, UntypedFormControl, UntypedFormGroup } from '@angular/forms';
import { MatOption } from '@angular/material/core';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { TenderCategoryDto } from 'src/app/_dto/category.dto';
import { PcdUserDto } from 'src/app/_dto/pcduser.dto';
import { tenderSubcategoryMasterDto } from 'src/app/_dto/tenderSubcategoryMaster.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-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})


export class RegisterComponent implements OnInit {


  loading = true

  verifiedOtp: boolean = false;

  dialogRef: any;

  userDetails = new PcdUserDto()

  categories:TenderCategoryDto;


  selectedCategoryList: number[] = [];

  categoryConfigurationForm: UntypedFormGroup;


  // companyProfile ={fileName:"",filePath:""}
  @ViewChild('allSelection') private allSelection: MatOption;
  userCategoryList: any;
  cmpPrdocSize: any;
  cmpPrfilePath: any;
  prCmpltCertFilePath: any;
  prCmpltCertdocSize: any;
 
  selected: boolean;
  selectedCategory: any[];
  selectedCategoryId: any;
  selectedCategoryIndex: any;
  subCatLength: any;
  spinnerLoading:boolean = false;

  categoryList: TenderCategoryDto[];

  subCategoryList: tenderSubcategoryMasterDto[];
  

  constructor(
    private dialog: MatDialog,
    private _masterService: MasterService,
    private _uiService: UiService,
    private errorTranslateService: ErrorTranslateService,
    private router: Router,
    private _fb: UntypedFormBuilder,


  ) { }

  ngOnInit(): void {
    this.loading = false;
    this.categoryConfigurationForm = this._fb.group({
      selection: new UntypedFormControl(''),
      count: new UntypedFormControl(''),
    });
    this.getCategoryData();
     
    
    this.userDetails.Category = []
  }

  sendOTP(template) {
    
    if (this.userDetails.email && this._uiService.emailValidation(this.userDetails.email)) {
      let body = { email: this.userDetails.email };
      this._masterService.saveAllMasterData(apiUrl.registerOtp, body).then(res => {
      this._uiService.toastMessage(this.errorTranslateService.translate("otpSendSuccessfully"));

        this.openDialogbox(template)
      },err=>{
        this._uiService.toastMessage((err.error.message) ? err.error.message : this.errorTranslateService.translate('errorInApi'));

      })
    }
    else {
      this._uiService.toastMessage(this.errorTranslateService.translate("enterAValidEmailID"));
    }

    
     this.getCategoryData()
  }

  // getCategoryData(){
  //   this._masterService.getMasterData(apiUrl.category).then(res =>{
  //     this.categories =res;
  //     this.categoryList = res;
  //   })
  // }

 

  openDialogbox(templateRef) {
    this.dialogRef = this.dialog.open(templateRef, {
      width: '400px',
      disableClose: false
    });
    // this.verifiedOtp = true
  }

 

//   onCategoryChange(selectedValues: number[]): void {
   
//     const concatenatedValues: string = selectedValues.map(value => value.toString()).join(',');

    
 
//     this.userDetails.category = concatenatedValues;
// }


toggleCategorySelection(categoryId: number): void {
    const index = this.selectedCategoryList.indexOf(categoryId);
    if (index !== -1) {
        this.selectedCategoryList.splice(index, 1);
    } else {
        this.selectedCategoryList.push(categoryId);
    }
}
// toggleAllSelection(event) {
//   // if (this.selectedCategoryList.length === this.categoryList.length) {
//   //   // If all categories are already selected, clear the selection
//   //   this.selectedCategoryList = [];
//   // } else {
//   //   // Otherwise, select all categories
//   //   this.selectedCategoryList = this.categoryList.map(category => category.id);
//   // }

//   if(event){
//     for(let element of this.categoryList){
//       this.selectedCategoryList.push(element.id);

//     }
    
//   }
// }




toggleAllSelection(field) {
  if (field == "select") {
    if (this.allSelection.selected) {
      this.categoryConfigurationForm.controls.selection
        .patchValue([...this.categoryList.map(item => item.id), 0]);

    } else {
      this.categoryConfigurationForm.controls.selection.patchValue([]);
    }
  }


}

tosslePerOne(field) {

  if (field == "select") {
    if (this.allSelection.selected) {
      this.allSelection.deselect();
      return false;
    }
    if (this.categoryConfigurationForm.controls.selection.value.length == this.categoryList.length) {
      this.allSelection.select();
    }

  }

}

  validation() {

    if (this.userDetails.otp) {
      let body = {
        email: this.userDetails.email,
        otp: this.userDetails.otp
      }
      this._masterService.saveAllMasterData(apiUrl.validateRegisterOtp, body).then(res => {
        if (res['data'] == 'success') {
          Swal.fire(
            'Verified',
            'OTP Verified Successfully',
            'success'
          )
          this.dialogRef.close()
          this._uiService.toastMessage(this.errorTranslateService.translate("otpVerifiedSuccess"));
          this.verifiedOtp = true
        }
        else {
          this.dialogRef.close();
          this._uiService.toastMessage(this.errorTranslateService.translate("otpMismatching"));
        }
      },err=>{

        this._uiService.toastMessage((err.error.message) ? err.error.message : this.errorTranslateService.translate('errorInApi'));

      })
    }
    else {
      this._uiService.toastMessage(this.errorTranslateService.translate("enterOTP"));
    }

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

  removeCmpPrFile(){
    this._masterService.deleteMasterData(apiUrl.cmpPrFileUpload,this.userDetails.companyProfile ).then(res=>{
      this.userDetails.companyProfile  = null
      this.cmpPrfilePath = null
      })  
  }
  uploadCmpPrFiles(event){
    let file: File | undefined = event.target.files[0];
    if (!file) {
      return;
    }

    const fd = new FormData();
  fd.append('file', file );
     
  this._masterService.saveMasterData(apiUrl.cmpPrFileUpload,fd).then(res=>{
    this.userDetails.companyProfile = res.fileName;
   this.cmpPrfilePath = res.filePath;
   this.cmpPrdocSize = res.fileSizeKB;
  
  })
} 

 

removeprCmpltCertFile(){
  this._masterService.deleteMasterData(apiUrl.projectCompleteCertFile,this.userDetails.projectCompletedCert ).then(res=>{
    this.userDetails.projectCompletedCert  = null
    this.prCmpltCertFilePath = null
    }) 
}

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

  const fd = new FormData();
fd.append('file', file );
   
this._masterService.saveMasterData(apiUrl.projectCompleteCertFile,fd).then(res=>{
  this.userDetails.projectCompletedCert = res.fileName;
 this.prCmpltCertFilePath = res.filePath;
 this.prCmpltCertdocSize = res.fileSizeKB;

})
}


openNotificationDialog(templateRef) {
  this.dialogRef = this.dialog.open(templateRef, {
    width: '800px',
    disableClose: false,
    maxHeight:'80vh'
  });
  this.categoryList=[]
  // this.getMarqueeData();
  this.getCategoryData();
  // this.getUserCategories()
}

closeDialog() {
  this.dialogRef.close();
}

saveCategory() {
  // this.spinnerLoading = true;
  let tempArray = []
  this.categoryList.forEach(cat => {

    for (let subCat of cat.tenderSubCategory) {
      if (subCat.selected && subCat.name != 'all') {
        let body = { Category: null, subCategory: null }
        body.Category = cat.id;
        body.subCategory = subCat.id
        // tempArray.push(body)
        this.userDetails.Category.push(body)
      }
    }
    
  });

  // this._masterService.saveMasterData(apiUrl.categoryEdit, tempArray).then(res => {
  //   this._uiService.toastMessage(this.errorTranslateService.translate('updateSuccess'));
  // this.spinnerLoading = false;
  //   this.closeDialog();
   

  // })
 
  this.closeDialog()

}

getCategoryData() {


  this._masterService.getMasterData(apiUrl.category).then(res => {
    this.categoryList = res;
    if (res && res.length > 0) {
      this.selectedCategoryId = res[0].id
      this.selectedCategoryIndex = 0;
      this.categoryList[0].selected = true
    }
    // this.categoryList.forEach(element => {
    //   let body = {
    //     all: false,
    //     tenderSubCategory: `All ${element.tenderCategory} Category`,
    //     name: 'all',
    //     selected:false
    //   }
    //   element.tenderSubCategory.unshift(body)


    // });

   

  })
}

getSubcategory(id, i) {
  this.selectedCategoryId = id
  this.selectedCategoryIndex = i
  this.categoryList[i].selected = true

  //whether all sub categories are selected or not
  // let temp = 0;
  // this.categoryList[i].tenderSubCategory.forEach(element => {
  //   if (element.selected && element.name != 'all') {
  //     temp =temp + 1 ;
  //   } 
  // });

  // if(temp == (this.categoryList[i].tenderSubCategory.length -1)  ){
  //   this.categoryList[i].tenderSubCategory[0].selected =true;
  //    }
  //    else{
  //   this.categoryList[i].tenderSubCategory[0].selected =false;
  
  //    }
  
}



categoryChecked(event, subcategory, i) {

  if (subcategory.name && subcategory.name == 'all') {
    if (subcategory.selected) {
      for (let subCat of this.categoryList[i].tenderSubCategory) {
        subCat.selected = true;
      }
    }
    else {
      for (let subCat of this.categoryList[i].tenderSubCategory) {
        subCat.selected = false;
      }
    }


  }
  else {

    let temp = 0;

    this.categoryList[i].tenderSubCategory.forEach(subCat => {
     
      if (subCat.selected && subCat.name != 'all') {
        temp =temp + 1 ;
         
      } 
      })
     
      // if(temp == (this.categoryList[i].tenderSubCategory.length -1)  ){
      // this.categoryList[i].tenderSubCategory[0].selected =true;
   
    
      //  }
      //  else{
      // this.categoryList[i].tenderSubCategory[0].selected =false;
    
      //  }

}
}



getUserCategories() {
  this._masterService.getMasterData(apiUrl.userCategory).then(res => {
    this.userCategoryList = res;
    let temp =0
    
     this.userCategoryList.forEach(element => {

       this.categoryList.forEach(cat => {

       for (let subCat of cat.tenderSubCategory) {

          if (element.subCategory == subCat.id) {
            subCat.selected = true;
            // temp =temp+1;
            temp++
          }
        }
        
        if(temp == ( cat.tenderSubCategory.length - 1 ) && cat.tenderSubCategory[0].name =='all'){
       
          cat.tenderSubCategory[0].selected = true
        }
      });
    });


  })


}





  preSave(tempRef) {
    
    if (!this.userDetails.userName || this.userDetails.userName == null || this.userDetails.userName == "" ||this.userDetails.userName == undefined) {
      this._uiService.toastMessage(this.errorTranslateService.translate('userNameCantbeBlank'), 3000);
      return false;
    }
    if (!this.userDetails.mobileNumber || this.userDetails.mobileNumber == null || this.userDetails.mobileNumber == "" ||this.userDetails.mobileNumber == undefined) {
      this._uiService.toastMessage(this.errorTranslateService.translate('phonecantBeBlank'), 3000);
      return false;
    }
    if (!this._uiService.phoneNoValidation(this.userDetails.mobileNumber) ) {
      this._uiService.toastMessage(this.errorTranslateService.translate('enterAValidPhoneNumber'), 3000);
      return false;
    }
    if (!this.userDetails.pass || this.userDetails.pass == null || this.userDetails.pass == "" ||this.userDetails.pass == undefined) {
      this._uiService.toastMessage(this.errorTranslateService.translate('passwordCantbeBlank'), 3000);
      return false;
    }
    if (this.userDetails.pass.length < 6) {
      this._uiService.toastMessage(this.errorTranslateService.translate('minimumPasswordLenght'), 3000);
      return false;
    }
    if (!this.userDetails.confPass || this.userDetails.confPass == null || this.userDetails.confPass == "" ||this.userDetails.confPass == undefined) {
      this._uiService.toastMessage(this.errorTranslateService.translate('confirmPasswordCantbeBlank'), 3000);
      return false;
    }
    if (this.userDetails.pass != this.userDetails.confPass) {
      this._uiService.toastMessage(this.errorTranslateService.translate('passwordMismatch'), 3000);
      return false;
    } if (!this.userDetails.Category || this.userDetails.Category == null || this.userDetails.Category.length == 0 || this.userDetails.Category.length < 0) {

      this.openNotificationDialog(tempRef)

      this._uiService.toastMessage(this.errorTranslateService.translate('categorycantBeBlank'), 3000);

      return false;
    }
  //  if (!this.categoryConfigurationForm.controls.selection.value || this.categoryConfigurationForm.controls.selection.value == null || this.categoryConfigurationForm.controls.selection.value == undefined) {
  //   this._uiService.toastMessage(this.errorTranslateService.translate('categorycantBeBlank'), 3000);
  //   return false;
  // }
  // this.userDetails.category=[]
  // this.categoryConfigurationForm.value.selection.forEach(element => {
  //   if(element != 0)
  //   this.userDetails.category.push(element)
  // })
    if (!this.userDetails.maxAmount || this.userDetails.maxAmount == null || this.userDetails.maxAmount == undefined) {
      this._uiService.toastMessage(this.errorTranslateService.translate('maxAmountCantbeBlank'), 3000);
      return false;
    }
    return true;
  }

  saveData(tempRef){
    this.userDetails.active = false;
    this.userDetails.status = 'R'
    if (!this.preSave(tempRef))
      return;

      delete this.userDetails.confPass
      this.loading = true;
      this._masterService.saveMasterData(apiUrl.signup,this.userDetails).then(res=>{
        this.loading = false
      this._uiService.toastMessage(this.errorTranslateService.translate('saveSuccess'), 3000);
      this.verifiedOtp = false
        this.userDetails = new PcdUserDto();
        this.navigateTo('/auth/login')
      },err=>{
        this.loading = false;
        this._uiService.toastMessage((err.error.message) ? err.error.message : this.errorTranslateService.translate('errorInApi'));
        this.verifiedOtp = false
      })

  }



/////////////////////////////////////////////////////////////////////////////
  // tosslePerOne(field) {
    
  //   if (field == "select") {
  //     if (this.allSelection.selected) {
  //       this.allSelection.deselect();
  //       return false;
  //     }
  //     if (this.categoryConfigurationForm.controls.selection.value.length == this.categoryList.length) {
  //       this.allSelection.select();
  //     }

  //   }

  // }
  toggleOptGroupSelection(categoryGroup) {
    const selectedSubCategoryIds = categoryGroup.tenderSubCategory.map(sub => sub.id);
  
    if (this.isOptGroupSelected(categoryGroup)) {
      // Deselect all options if the optgroup is already selected
      this.categoryConfigurationForm.controls.selection.patchValue(
        this.categoryConfigurationForm.controls.selection.value.filter(id => !selectedSubCategoryIds.includes(id))
      );
    } else {
      // Toggle the selection of the optgroup and its options
      const selectedOptions = [...this.categoryConfigurationForm.controls.selection.value, ...selectedSubCategoryIds];
      this.categoryConfigurationForm.controls.selection.patchValue(selectedOptions);
      
    }
  }
  
  isOptGroupSelected(categoryGroup) {
    const selectedOptions = this.categoryConfigurationForm.controls.selection.value;
    return selectedOptions.includes(categoryGroup.id) &&
      selectedOptions.some(id => selectedOptions.includes(id) && categoryGroup.tenderSubCategory.map(sub => sub.id).includes(id));
  }
  


  
  
//   toggleAllSelection() { 6/2/2024
  
//       if (this.allSelection.selected) {
        
//         this.categoryConfigurationForm.controls.selection.patchValue(
//           [].concat.apply([], this.categoryList.map(item => item.tenderSubCategory.map(subItem => subItem.id))).concat([0])
//         );

//       } else {
//         this.categoryConfigurationForm.controls.selection.patchValue([]);
//       }
// }

  
  getAllSubCategoryIds() {
    return this.categoryList.reduce((acc, category) => [
      ...acc,
      ...category.tenderSubCategory.map(sub => sub.id)
    ], []);
  }
  
}
   