import { Component, ViewChild, OnInit } from "@angular/core";
import { MatPaginator } from "@angular/material/paginator";
import { MatSort } from "@angular/material/sort";
import { MatTableDataSource } from "@angular/material/table";
import Swal from "sweetalert2";
import { CatalogsService } from "src/app/services/catalogs.service";
import { IncomesService } from "@app/services/incomes.service";

import { AuthService } from "@app/services/auth2.service";
import { JwtHelperService } from "@auth0/angular-jwt";
import { IncomeList } from "@app/models/income-list";
import { from } from "rxjs";
import { FormInvestmentProposalService } from "@app/services/form-investment-proposal.service";
import { Router } from "@angular/router";
import { IAngularMyDpOptions, IMyDateModel } from "angular-mydatepicker";

@Component({
  selector: "app-income-proposals",
  templateUrl: "./incomes.component.html",
  styleUrls: ["./incomes.component.scss"]
})
export class IncomesComponent implements OnInit {
  helper = new JwtHelperService();

  title: string = "Ingresos";

  // For daterange
  daysLabels: any = {
    su: "Dom",
    mo: "Lun",
    tu: "Mar",
    we: "Mie",
    th: "Jue",
    fr: "Vie",
    sa: "Sab"
  };
  monthsLabels: any = {
    1: "Ene",
    2: "Feb",
    3: "Mar",
    4: "Abr",
    5: "May",
    6: "Jun",
    7: "Jul",
    8: "Ago",
    9: "Sep",
    10: "Oct",
    11: "Nov",
    12: "Dic"
  };
  myDpOptions: IAngularMyDpOptions = {
    dateRange: true,
    dateFormat: "dd/mm/yyyy",
    dayLabels: this.daysLabels,
    monthLabels: this.monthsLabels
  };
  myDateInit: boolean = true;
  model: IMyDateModel = null;

  displayedColumns: string[] = [
    "codigo_inversion",
    "nombre_inversion",
    "fecha_proyeccion_pago",
    "tipo_instrumento",
    "empresa",
    "estado",
    "id_inversion",
    "proyeccion_ingreso"
  ];
  //displayedColumns: string[] = ['state'];

  listProposals: IncomeList[];
  dataSource = new MatTableDataSource(this.listProposals);

  resultsLength = 0;
  isLoadingResults = true;
  isRateLimitReached = false;
  userRole: any;

  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: true }) sort: MatSort;
  role_number: any;
  instrumentTypes: any;

  constructor(
    private catalogService: CatalogsService,
    private incomesService: IncomesService,
    private authService: AuthService,
    private formInvestmentProposal: FormInvestmentProposalService,
    private router: Router
  ) {
    const decodedToken = this.helper.decodeToken(
      this.authService.getJwtToken()
    );
    this.userRole = decodedToken.groups;

    Swal.fire({
      allowOutsideClick: false,
      icon: "info",
      text: "Espere por favor..."
    });
    Swal.showLoading();
  }

  ngOnInit() {
    this.catalogService.getInstrumentTypes().subscribe(res => {
      this.instrumentTypes = res;
    });

    this.incomesService.getProjectionsIncomeList().subscribe(
      ans => {
        this.listProposals = ans.result;
        this.dataSource.data = this.listProposals;
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      },
      err => {
        Swal.fire({
          icon: "error",
          title: "Error en el servidor",
          text: err.message
        });
      }
    );

    setTimeout(() => {
      Swal.close();
    }, 1200);
  }

  filter_by_instrument(event: any) {
    const filterInstrument = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterInstrument;
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
    this.dataSource.sort = this.sort;
  }

  filter_by_date(event: any) {
    let dateFormat = event.dateRange.formatted.split(" - ", 2);

    let date0 = dateFormat[0].split("/");
    let date1 = dateFormat[1].split("/");

    let dateStart = Number(date0[2] + date0[1] + date0[0]);
    let dateFinish = Number(date1[2] + date1[1] + date1[0]);

    this.dataSource.filterPredicate = (data, filter) => {
      if (dateFormat[0] && dateFormat[1]) {
        let date2 = data["fecha_proyeccion_pago"].split("/");
        let payment_date = Number(date2[2] + date2[1] + date2[0]);
        return payment_date >= dateStart && payment_date <= dateFinish;
      }
      return true;
    };
    this.dataSource.filter = "" + Math.random();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
    this.dataSource.sort = this.sort;
  }

  filter_by_state(event: any) {
    const filterInstrument = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterInstrument;
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
    this.dataSource.sort = this.sort;
  }

  filter_by_income_status(event: any) {
    Swal.fire({
      allowOutsideClick: false,
      icon: "info",
      text: "Espere por favor..."
    });
    Swal.showLoading();

    let active = event.target.value;

    let active_income = active == 1 || active == 2 ? "1" : "0";
    let current_date = active == 1 ? "1" : "0";

    this.incomesService
      .getProjectionsIncomeList(active_income, current_date)
      .subscribe(
        ans => {
          this.listProposals = ans["result"];
          this.dataSource.data = this.listProposals;
          this.dataSource.paginator = this.paginator;
          this.dataSource.sort = this.sort;
          Swal.close();
        },
        err => {
          Swal.fire({
            icon: "error",
            title: "Error en el servidor",
            text: err.message
          });
        }
      );
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLSelectElement).value;
    this.dataSource.filter = filterValue;

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  view_investment_proposal(id: string) {
    this.formInvestmentProposal.resetFormData();
    Swal.fire({
      allowOutsideClick: false,
      icon: "info",
      text: "Espere por favor..."
    });
    Swal.showLoading();
    setTimeout(() => {
      this.router.navigate([`/investment-proposal/${id}`]);
    }, 1000);
  }

  instrument_has_costs(id: string) {
    return true;
  }

  go_to_instrument_url(
    id: string,
    id_proyeccion_instrumento: string,
    fecha: string,
    id_proyeccion?: string
  ) {
    Swal.fire({
      allowOutsideClick: false,
      icon: "info",
      text: "Espere por favor..."
    });
    Swal.showLoading();

    setTimeout(() => {
      this.router.navigate([`/investment-income`], {
        queryParams: {
          id_inversion: id,
          id_proyeccion_ingreso_instrumento: id_proyeccion_instrumento,
          fecha_proyeccion_pago: fecha,
          id_proyeccion_ingreso: id_proyeccion
        }
      });
    }, 1000);
  }
}
