import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';
import { Dsa } from '../../models/dsa';
import { AdminPersonalLoanResponse } from '../../models/loans/adminPersonalLoanResponse';
import { DsaService } from '../../shared/services/dsa.service';


@Component({
  selector: 'app-dsa-detail',
  templateUrl: './dsa-detail.component.html',
  styleUrls: ['./dsa-detail.component.scss']
})
export class DsaDetailComponent implements OnInit {
  public token!: string;
  public paramid: any;
  public dsas = new Dsa();
  public isAlert!: boolean;
  public alertType!: string;
  public alertMessage!: string;
  public subdsas: Dsa[] = new Array<Dsa>();
  public subdsa = new Dsa
  public LoanDisplayColumns = ["id", "fullName", "serviceName", "loanAmount", "loanTransactionDate", "motherName", "action"];
  public commissionDisplayColumns = ["bankName", "commissionType", "serviceName", "commission"];
  public customersDisplayColumns = ["id", "Name", "birthdate", "gender", "panCardNo", "temporaryCode", "action"];
  public employeeColumns = ['id', 'code', 'fullName', 'panCardNo', 'gender', 'city', 'companyType', 'companyName', 'createdDate', 'action']
  public groupColumns = ['id', 'code', 'fullName', 'panCardNo', 'gender', 'city', 'companyType', 'companyName', 'createdDate', 'role', 'action'];
  public walletColumns = ['coin', 'rewardType', 'isWithdrawal', 'createdDate'];
  public partnerCommission = ['id', 'type', 'createdDate', 'commission'];
  public leadDisplayColumn = ['id', 'name', 'contactNo', 'panCardNo', 'leadStatus', 'service', 'createdDate', 'loanAmount', 'assignpartner'];
  public OrderDisplayColumns = ['id', 'productName', 'quantity', 'unitCoin', 'totalcoin', 'orderstatus', 'transactiondate'];
  public service!: string;
  public personalLoans: AdminPersonalLoanResponse[] = new Array<AdminPersonalLoanResponse>();
  public services: any;
  public selectedLoan!: any
  public selectedServiceName!: string;
  public currency!: any;
  public isSticky(action: string): boolean {
    return action === 'action' ? true : false;
  }

  constructor(
    private spinnerService: NgxSpinnerService,
    private actRoute: ActivatedRoute,
    private dsaService: DsaService,
    private router: Router,
    private toasterService: ToastrService,
    private translate: TranslateService,
  ) { }

  async ngOnInit() {
    this.token = sessionStorage.getItem("SessionToken")!;
    let currency = JSON.parse(sessionStorage.getItem("Credential") ?? 'null');
    this.currency = currency.currency;
    this.paramid = this.actRoute.snapshot.paramMap.get('id');
    let partnerId = this.paramid;
    this.paramid = partnerId;

    await this.getPartnerDetailByPartnerId(partnerId);
    let lang = localStorage.getItem("selectedLanguage")!;;
    this.translate.use(lang);

  }

  public async getPartnerDetailByPartnerId(partnerId: number) {
    try {
      this.spinnerService.show();
      let res = await this.dsaService.getPartnerDetailByPartnerId(partnerId, this.token);
      if (res && res.status == 200) {
        if (res.recordList && res.recordList.length > 0)
          this.dsas = res.recordList[0];
        this.dsas.basicDetail.code = this.dsas.basicDetail.permanentCode ? this.dsas.basicDetail.permanentCode : this.dsas.basicDetail.temporaryCode
        this.dsas.isDisabled = this.dsas.isDisabled ? true : false;
        if (this.dsas.basicDetail.workAddressCityId && this.dsas.basicDetail.pincode) {
          await this.getCityByPincode(this.dsas.basicDetail.pincode)
        }
      }
      this.spinnerService.hide();
    } catch (error: any) {
      this.spinnerService.hide();
      this.alertMessage = error;
      if (error?.message) {
        this.alertMessage = error.message
      }
      if (error?.error && error.error.message) {
        this.alertMessage = error.error.message
      }
      if (error?.error && error.error.error && error.error.error.functionErrorMessage) {
        this.alertMessage = error.error.error.functionErrorMessage
      }
      this.toasterService.error(error);
    }
  }

  public viewLoanDetail(ele: { serviceName: string; id: string; }) {
    let name = ele.serviceName.replace(/\s/g, '-')
    let route = 'admin/' + name.toLowerCase()+ '/' + ele.id;
    this.router.navigate([route]);
  }

  public navigateEmployeeDetail(id: number) {
    this.router.navigate(["admin/employee", id])
  }

  public navigateCustomerDetail(id: number) {
    this.router.navigate(["admin/customers", id])
  }

  public navigateGroupDetail(element: { roleName: string; id: any; }) {
    if (element.roleName == "SUBDSA")
      this.router.navigate(["admin/subdsa", element.id]);
    if (element.roleName == "CONNECTOR")
      this.router.navigate(["admin/connector", element.id]);
  }

  public async getCityByPincode(n: string) {
    try {
      this.spinnerService.show();
      let res = await this.dsaService.getCityByPincode(null, n, this.token);
      if (res && res.status == 200) {
        let cities = res.recordList;
        if (cities && cities.length > 0) {
          this.dsas.basicDetail.workAddressCity = cities.find((c: any) => c.id == this.dsas.basicDetail.workAddressCityId).name
        }

      }
      this.spinnerService.hide();
    } catch (error: any) {
      this.spinnerService.hide();
      this.alertMessage = error;
      if (error?.message) {
        this.alertMessage = error.message
      }
      if (error?.error && error.error.message) {
        this.alertMessage = error.error.message
      }
      if (error?.error && error.error.error && error.error.error.functionErrorMessage) {
        this.alertMessage = error.error.error.functionErrorMessage
      }
      this.toasterService.error(error)
    }
  }

}
