import { isPlatformBrowser } from '@angular/common';
import { Component, ElementRef, Inject, OnInit, PLATFORM_ID, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Meta, Title } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { Cities } from '../../entities/cities';
import { Documents } from '../../entities/document';
import { DSA } from '../../entities/dsa';
import { CommonService } from '../../shared/services/common/common.service';
import { GlobalService } from '../../shared/services/common/global.service';
import { LinkService } from '../../shared/services/link.service';
import { LeadService } from '../../shared/services/loanService/lead.service';
import { DocumentMasters } from '../../entities/documentMasters';

@Component({
  selector: 'app-dsa-signup',
  templateUrl: './dsa-signup.component.html',
  styleUrls: ['./dsa-signup.component.scss']
})
export class DsaSignupComponent implements OnInit {
  public showTab: number = 0
  public dataimage: any;
  @ViewChild('fileInput') fileInput!: ElementRef;
  // public fileAttr = 'No File Chosen';
  public companyTypes: any = [];
  public documentTypes: any = [];
  public partnerRoles: any = [];
  public professionTypes: any = [];
  public dsaSignUpForm: FormGroup;
  public cities: Cities[] = new Array<Cities>();
  public selectedCity: Cities[] = [];
  public dsa = new DSA();
  public photoUrl: string = '';
  public aadharcardUrl: string = '';
  public pancardUrl: string = '';
  //public isShow: boolean = true;
  public photoType: string = '';
  public aadharCardType: string = '';
  public panCardType: string = '';
  public city: string = '';
  public jobList: any[] = ["Full Time", "Part Time"];
  public documentMasters: DocumentMasters[] = new Array<DocumentMasters>();
  public customFieldForm!: FormGroup;

  constructor(
    private formBuilder: FormBuilder,
    private commonService: CommonService,
    private globalService: GlobalService,
    private leadService: LeadService,
    private toastrService: ToastrService,
    private route: ActivatedRoute,
    private title: Title,
    private meta: Meta,
    @Inject(PLATFORM_ID) public platformId: object,
    private spinnerService: NgxSpinnerService,
    private linkService: LinkService
  ) {
    this.linkService.createLinkForCanonicalURL();
    let city;
    if (isPlatformBrowser(this.platformId))
      city = sessionStorage.getItem("selectedCity");
    if (city)
      this.city = city;
    // else
    //   this.city = "surat";

    this.title.setTitle(this.route.snapshot.data['title']);

    this.meta.addTags([
      {
        name: 'description', content: `Easy to compare and apply for any type of loan at Credit - compare with different banks's interest rate and select the plan with the lowest emi cost , Apply for credit card by just 1 single click, Credit is the right place to sign up as DSA that best fits your needs and helps you make the most of your purchases.`
      },
      {
        name: 'author', content: `Credit`
      },
      {
        name: 'og:title', property: "og:title", content: `Become a partner`
      },
      {
        name: 'og:description', property: "og:description", content: `Sign up as dsa/connector/employee - credit.nsserver.in`
      },
      {
        name: 'og:site_name', property: "og:site_name", content: `Credit`
      },
      {
        name: 'og:type', property: "og:type", content: `Website`
      },
      {
        name: 'og:image', property: "og:image", content: `../../../assets/img/logo/logo.webp`
      },
      {
        name: 'tweeter:card', content: `Sign Up as dsa/connector`
      },
      {
        name: 'tweeter:title', content: `Sign Up as dsa/connector/employee`
      },
      {
        name: 'tweeter:description', content: `Sign up as dsa/connector/employee - https://credit.nsserver.in`
      },
      {
        name: 'tweeter:site', content: `Credit`
      },
      {
        name: 'tweeter:image', content: `../../../assets/img/logo/logo.webp`
      }
    ]);


    this.dsaSignUpForm = formBuilder.group({
      'fullName': [null, [Validators.required]],
      'contactNo': [null, [Validators.required, Validators.minLength(10)]],
      'cityId': [null, [Validators.required]],
      'commitment': [null, [Validators.required]],
      'pincode': [null, [Validators.required, Validators.maxLength(6), Validators.minLength(6)]],
      'gender': [null, [Validators.required]],
      // 'panCardNo': [null, [Validators.required, Validators.pattern('[A-Z]{5}[0-9]{4}[A-Z]{1}')]],
      // 'aadhaarCardNo': [null, [Validators.required, Validators.pattern('^[2-9]{1}[0-9]{3}[0-9]{4}[0-9]{4}$')]],
      'jobType': [null, [Validators.required]],
      'addressLine1': [null, [Validators.required]],
      'addressLine2': [null],
      'district': [null],
      'state': [null],
    })
  }

  async ngOnInit() {
    await this.getDocumentMaster();
    if (this.documentMasters && this.documentMasters.length > 0) {
      this.customFieldForm = this.formBuilder.group({})
      for (let index = 0; index < this.documentMasters.length; index++) {
        if (this.documentMasters[index].allowDocumentField) {
          this.customFieldForm.addControl(this.documentMasters[index].documentFieldName, this.formBuilder.control(''));
        }
      }
    }
    // setTimeout(() => {
    //   this.isShow = false;
    // }, 1000);
    // await this.getCompanyTypes();
    // await this.getProfessionType();
    // await this.getPartnerRole();
    // await this.documentType();
    // this.cities = await this.commonService.getCitites();
    // this.selectedCity = [...this.cities];
    // this.dsaSignUpForm.controls['aadharcardPath'].setValue("No File Chosen");
    // this.dsaSignUpForm.controls['pancardPath'].setValue("No File Chosen");
    // this.dsaSignUpForm.controls['photoPath'].setValue("No File Chosen");
    // this.dsaSignUpForm.controls['haveOffice'].setValue("true");
  }
  public async getDocumentMaster() {
    try {
      let res = await this.globalService.getDocumentMaster();
      if (res && res.status == 200) {
        this.documentMasters = res.recordList;
      }
    } catch (error: any) {
      this.toastrService.error(error)
    }
  }
  // public async getCompanyTypes() {
  //   try {
  //     let res = await this.globalService.getCompanyTypes();
  //     if (res && res.status == 200) {
  //       this.companyTypes = res.recordList;
  //     }
  //   } catch (error: any) {
  //     let err = error;
  //     if (error && error.error && error.error.message) {
  //       err = error.error.message
  //     }
  //     this.toastrService.error(err, "Error");
  //   }
  // }

  // public async getProfessionType() {
  //   try {
  //     let res = await this.globalService.getProfessionTypes();
  //     if (res && res.status == 200) {
  //       this.professionTypes = res.recordList;
  //     }
  //   } catch (error: any) {
  //     let err = error;
  //     if (error && error.error && error.error.message) {
  //       err = error.error.message
  //     }
  //     this.toastrService.error(err, "Error");
  //   }
  // }

  // public async getPartnerRole() {
  //   try {
  //     let res = await this.globalService.getPartnerRoles();
  //     if (res && res.status == 200) {
  //       this.partnerRoles = res.recordList;
  //     }
  //   } catch (error: any) {
  //     let err = error;
  //     if (error && error.error && error.error.message) {
  //       err = error.error.message
  //     }
  //     this.toastrService.error(err, "Error");
  //   }
  // }

  // public async documentType() {
  //   try {
  //     let res = await this.globalService.getDocument();
  //     if (res && res.status == 200) {
  //       this.documentTypes = res.recordList;
  //     }
  //   } catch (error: any) {
  //     let err = error;
  //     if (error && error.error && error.error.message) {
  //       err = error.error.message
  //     }
  //     this.toastrService.error(err, "Error");
  //   }
  // }

  // public nextPrev1(n: number) {
  //   let x, y, i, valid = true;
  //   x = document.getElementsByClassName("tab");
  //   y = x[this.showTab].getElementsByTagName("input");
  //   for (i = 0; i < y.length; i++) {
  //     if (y[i].value == "") {
  //       y[i].className += " invalid ffdj";
  //       valid = false;
  //     }
  //   }
  //   if (n == -1) {
  //     this.showTab -= 1;
  //   }
  //   else {
  //     if (valid) {
  //       document.getElementsByClassName("tab")[this.showTab].className += " finish";
  //       this.showTab += 1;
  //     }
  //   }
  //   if (this.showTab == (x.length - 1)) {
  //     document.getElementById("nextBtn")!.innerHTML = "Submit";
  //   } else {
  //     document.getElementById("nextBtn")!.innerHTML = "Next";
  //   }
  // }

  // public nextPrev(n: number) {
  //   if (n == -1) {
  //     this.showTab -= 1;
  //   }
  //   else {
  //     this.showTab += 1;
  //   }
  // }

  // public uploadFileEvt(imgFile: any, type: any) {
  //   if (imgFile.target.files && imgFile.target.files[0]) {
  //     // this.fileAttr = '';
  //     imgFile.target.files.forEach((ele:any) => {
  //       if (type == "photo") {
  //         this.dsaSignUpForm.controls['photoPath'].setValue(ele.name);
  //         this.photoType = ele.type
  //       }
  //       else if (type == "pancard") {
  //         this.dsaSignUpForm.controls['pancardPath'].setValue(ele.name);
  //         this.panCardType = ele.type
  //       }
  //       else {
  //         this.dsaSignUpForm.controls['aadharcardPath'].setValue(ele.name);
  //         this.aadharCardType = ele.type
  //       }
  //     })
  //     console.log(this.photoType, this.panCardType, this.aadharCardType);

  //     // Array.from(imgFile.target.files).forEach((file) => {
  //     //   this.fileAttr += file.name;
  //     // });

  //     // HTML5 FileReader API
  //     let reader = new FileReader();
  //     reader.onload = (e: any) => {
  //       let image = new Image();
  //       image.src = e.target.result;
  //       image.onload = rs => {
  //         let imgBase64Path = e.target.result;
  //         if (type == "photo")
  //           this.photoUrl = imgBase64Path;
  //         else if (type == "pancard")
  //           this.pancardUrl = imgBase64Path;
  //         else
  //           this.aadharcardUrl = imgBase64Path
  //       };
  //     };
  //     reader.readAsDataURL(imgFile.target.files[0]);

  //     // Reset if duplicate image uploaded again
  //     this.fileInput.nativeElement.value = "";
  //   } else {
  //     imgFile.target.files.forEach((ele:any) => {
  //       if (type == "photo")
  //         this.dsaSignUpForm.controls['aadharcardPath'].setValue("No File Chosen");
  //       else if (type == "pancard")
  //         this.dsaSignUpForm.controls['pancardPath'].setValue("No File Chosen");
  //       else
  //         this.dsaSignUpForm.controls['photoPath'].setValue("No File Chosen");
  //     });
  //   }
  // }

  // public onKey(value) {
  //   this.selectedCity = this.search(value);
  // }

  // public search(value: string) {
  //   let filter = this.cities.filter(item =>
  //     item.name.toLowerCase().includes(value.toLowerCase())
  //   );
  //   return [...filter];
  // }

  // public async onSubmit() {

  //   if (this.dsaSignUpForm.valid) {
  //     this.dsa = this.dsaSignUpForm.value;
  //     this.dsa.roleId = this.dsaSignUpForm.value.role.id;
  //     this.dsa.roleName = this.dsaSignUpForm.value.role.name
  //     this.dsa.documents :any = [];

  //     if (this.dsaSignUpForm.value.photoPath) {
  //       let data = {
  //         documentId: this.documentTypes.find((c:any) => c.name == "Photo").id,
  //         fileData: this.photoUrl,
  //         fileName: this.dsaSignUpForm.value.photoPath,
  //         contentType: this.photoType
  //       }
  //       this.dsa.documents.push(data);
  //     }
  //     if (this.dsaSignUpForm.value.pancardPath) {
  //       let data = {
  //         documentId: this.documentTypes.find((c:any) => c.name == "PAN Card").id,
  //         fileData: this.photoUrl,
  //         fileName: this.dsaSignUpForm.value.pancardPath,
  //         contentType: this.panCardType
  //       }
  //       this.dsa.documents.push(data);
  //     }
  //     if (this.dsaSignUpForm.value.aadharcardPath) {
  //       let data = {
  //         documentId: this.documentTypes.find((c:any) => c.name == "Aadhar Card").id,
  //         fileData: this.photoUrl,
  //         fileName: this.dsaSignUpForm.value.aadharcardPath,
  //         contentType: this.aadharCardType
  //       }
  //       this.dsa.documents.push(data);
  //     }
  //     try {
  //       //this.isShow = true;
  //       let res = await this.leadService.partnerSignUp(this.dsa);
  //       if (res && res.status == 200) {
  //         this.commonService.showSucessSignUp();
  //         this.sucessReponse();
  //         this.showTab = 0;

  //       }
  //       //this.isShow = false;
  //     } catch (error: any) {
  //       //this.isShow = false;
  //       let err = error;
  //       if (error && error.error && error.error.message) {
  //         err = error.error.message
  //       }
  //       this.toastrService.error(err, "Error");
  //     }

  //   } else {
  //     this.validateAllFormFields(this.dsaSignUpForm);
  //     // validate all form fields
  //   }
  // }

  // private validateAllFormFields(formGroup: FormGroup) {         //{1}
  //   Object.keys(formGroup.controls).forEach(field => {  //{2}
  //     const control = formGroup.get(field);             //{3}
  //     if (control instanceof FormControl) {             //{4}
  //       control.markAsTouched({ onlySelf: true });
  //     } else if (control instanceof FormGroup) {        //{5}
  //       this.validateAllFormFields(control);            //{6}
  //     }
  //   });
  // }

  public bindState() {
    this.dsaSignUpForm.value.cityId;
    this.dsaSignUpForm.controls['district'].setValue(this.dsaSignUpForm.value.cityId.districtName)
    this.dsaSignUpForm.controls['state'].setValue(this.dsaSignUpForm.value.cityId.stateName)
  }

  public async insertPartnerDetail() {
    try {
      this.spinnerService.show();
      if (this.documentMasters && this.documentMasters.length > 0) {
        for (let index = 0; index < this.documentMasters.length; index++) {
          if (this.documentMasters[index].allowDocumentField)
            this.documentMasters[index].documentData = this.customFieldForm.get(this.documentMasters[index].documentFieldName)?.value
        }

      }
      //this.isShow = true;
      let dsaObj = {
        fullName: this.dsaSignUpForm.value.fullName,
        panCardNo: this.dsaSignUpForm.value.panCardNo,
        cityId: this.dsaSignUpForm.value.cityId.id,
        district: this.dsaSignUpForm.value.district,
        state: this.dsaSignUpForm.value.state,
        addressLine1: this.dsaSignUpForm.value.addressLine1,
        addressLine2: this.dsaSignUpForm.value.addressLine2,
        gender: this.dsaSignUpForm.value.gender,
        contactNo: this.dsaSignUpForm.value.contactNo,
        aadharCardNo: this.dsaSignUpForm.value.aadhaarCardNo,
        jobType: this.dsaSignUpForm.value.jobType,
        businessCommitement: this.dsaSignUpForm.value.commitment,
        pincode: this.dsaSignUpForm.value.pincode,
        customfields: this.documentMasters
      }

      let res = await this.leadService.partnerSignUp(dsaObj);
      if (res && res.status == 200) {
        this.commonService.showSucessSignUp();
        this.sucessReponse();
        //this.showTab = 0;

      }
      //this.isShow = false;
      this.spinnerService.hide();
    } catch (error: any) {
      //this.isShow = false;
      this.spinnerService.hide();
      let err = error;
      if (error && error.error && error.error.message) {
        err = error.error.message
      }
      this.toastrService.error(err, "Error");
    }
  }

  public sucessReponse() {
    this.dsa = new DSA();
    this.dsaSignUpForm.reset();
    this.customFieldForm.reset();
    // this.dsaSignUpForm.controls['aadharcardPath'].setValue("No File Chosen");
    // this.dsaSignUpForm.controls['pancardPath'].setValue("No File Chosen");
    // this.dsaSignUpForm.controls['photoPath'].setValue("No File Chosen");
    // this.dsaSignUpForm.controls['haveOffice'].setValue("true");
  }

  public async getCityByPincode(event: KeyboardEvent) {
    this.cities = [];
    const value = (event.target as HTMLInputElement)!.value;;
    if (value && value.length == 6) {
      try {
        let res = await this.globalService.getCityByPincode(value);
        if (res && res.recordList.length > 0) {
          this.cities = res.recordList;
          this.selectedCity = [...this.cities]
        }
      } catch (error: any) {
        let err = '';
        if (error && error.error.message) {
          err = error.error.message
        }
        else if (error && error.message) {
          err = error.message
        }
        this.toastrService.error(error);
      }

    }
  }

}
