import { Component, OnInit, ComponentFactoryResolver } from "@angular/core";
import { FileUploader, FileLikeObject } from "ng2-file-upload";
import { concat } from "rxjs";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { HttpClient, HttpEventType } from "@angular/common/http";
import { FormInvestmentProposalService } from "@app/services/form-investment-proposal.service";
import { InvestmentProposalWorkflowService } from "@app/services/investment-proposal-workflow.service";
import { InstrumentsService } from "@app/services/instruments.service";
import { CatalogsService } from "@app/services/catalogs.service";
import { ActivatedRoute } from "@angular/router";
import { InvestmentsService } from "@app/services/investments.service";
import Swal from "sweetalert2";
import { IAngularMyDpOptions } from "angular-mydatepicker";

@Component({
  selector: "app-payment-requirement",
  templateUrl: "./payment-requirement.component.html",
  styleUrls: ["./payment-requirement.component.scss"]
})
export class PaymentRequirementComponent implements OnInit {
  title: string = "Formulario de requisición de pago";
  // 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: false,
    dateFormat: "dd/mm/yyyy",
    dayLabels: this.daysLabels,
    monthLabels: this.monthsLabels
  };
  myDateInit: boolean = true;

  form: FormGroup;
  fileData: File = null;
  previewUrl: any = null;
  fileUploadProgress: string = null;
  uploadedFilePath: string = null;
  interval: any;
  indexDynamicComponent: number;
  investmentProposalID: string;
  investmentExists;
  monto: string = "";
  codigo_inversion: string = "";
  codigo: string = "";
  tipo_pago: string = "";
  cuenta_bancaria: string = "";
  fecha_pago: string = "";
  fecha_vencimiento: string = "";
  investmentProposalForm: FormGroup;
  submitted: boolean = false;
  paymentObject: Object;
  userListPrevious: any;
  generated_inputs_previous: string;
  userListNext: any;
  generated_inputs_next: string;
  cuenta_bancaria_destino: any;
  emitir_nombre: any;
  formData: any;

  constructor(
    private http: HttpClient,

    private formDataService: FormInvestmentProposalService,
    private componentFactoryResolver: ComponentFactoryResolver,
    private instrumentService: InvestmentProposalWorkflowService,
    private loadInstrumentsService: InstrumentsService,
    private catalogService: CatalogsService,
    private route: ActivatedRoute,
    private investmentService: InvestmentsService,
    private formBuilder: FormBuilder,

    private investmentsService: InvestmentsService
  ) {}

  ngOnInit() {
    //this.formDataService
    //this.ads = this.loadInstrumentsService.getInstruments();
    this.route.params.subscribe(params => {
      this.investmentProposalID = params["id"];
    });
    if (this.investmentProposalID == undefined)
      this.investmentProposalID = this.route.snapshot.queryParamMap.get("id");

    this.investmentService
      .getAvailableUsers(this.investmentProposalID)
      .subscribe(res => {
        this.userListPrevious = res["usuarios_previous"];
        this.generated_inputs_previous = "";

        this.userListNext = res["usuarios_next"];
        this.generated_inputs_next = "";

        if (this.userListPrevious.length > 0) {
          for (let i = 0; i < this.userListPrevious.length; i++) {
            if (this.userListPrevious[i].default_email == true) {
              this.generated_inputs_previous += `<div class='form-check form-check-inline'><input type='checkbox' class='form-check-input' id='previous-${
                this.userListPrevious[i].name
              }' name='users' value='${
                this.userListPrevious[i].name
              }' checked='${
                this.userListPrevious[i].default_email == "true" ? true : false
              }' disabled='disabled'><label class='form-check-label' for='previous-${
                this.userListPrevious[i].name
              }'>${this.userListPrevious[i].name}</label></div>`;
            } else {
              this.generated_inputs_previous += `<div class='form-check form-check-inline'><input type='checkbox' class='form-check-input' id='previous-${this.userListPrevious[i].name}' name='users' value='${this.userListPrevious[i].name}'><label class='form-check-label' for='previous-${this.userListPrevious[i].name}'>${this.userListPrevious[i].name}</label></div>`;
            }
          }
        }
        if (this.userListNext.length > 0) {
          for (let i = 0; i < this.userListNext.length; i++) {
            if (this.userListNext[i].default_email == true) {
              this.generated_inputs_next += `<div class='form-check form-check-inline'><input type='checkbox' class='form-check-input' id='next-${
                this.userListNext[i].name
              }' name='users' value='${this.userListNext[i].name}' checked='${
                this.userListNext[i].default_email == "true" ? true : false
              }' disabled='disabled'><label class='form-check-label' for='next-${
                this.userListNext[i].name
              }'>${this.userListNext[i].name}</label></div>`;
            } else {
              this.generated_inputs_next += `<div class='form-check form-check-inline'><input type='checkbox' class='form-check-input' id='next-${this.userListNext[i].name}' name='users' value='${this.userListNext[i].name}'><label class='form-check-label' for='next-${this.userListNext[i].name}'>${this.userListNext[i].name}</label></div>`;
            }
          }
        }
      });

    this.investmentService
      .getPaymentInfoProposalInvestment(this.investmentProposalID)
      .subscribe(resp => {
        this.monto = resp["result"]["monto"];
        this.codigo_inversion =
          resp["result"]["id_inversion"]["codigo_inversion"];
        this.codigo = resp["result"]["codigo"];
        this.tipo_pago = resp["result"]["id_tipo_pago"]["nombre"];
        this.cuenta_bancaria = resp["result"]["id_cuenta_bancaria"]["nombre"];

        if (resp["result"]["id_cuenta_bancaria_destino"] != undefined) {
          this.cuenta_bancaria_destino =
            resp["result"]["id_cuenta_bancaria_destino"]["nombre"];
        }
        if (resp["result"]["emitir_nombre"] != undefined) {
          this.emitir_nombre = resp["result"]["emitir_nombre"];
        }

        this.fecha_vencimiento = resp["result"]["fecha_vencimiento"];
      });

    this.investmentProposalForm = this.formBuilder.group({
      comentario: [""],
      fecha_pago: ["", Validators.required]
    });
  }

  fileProgress(fileInput: any) {
    this.fileData = <File>fileInput.target.files[0];
    this.preview();
  }

  preview() {
    // Show preview
    var mimeType = this.fileData.type;
    if (mimeType.match(/image\/*/) == null) {
      return;
    }

    var reader = new FileReader();
    reader.readAsDataURL(this.fileData);
    reader.onload = _event => {
      this.previewUrl = reader.result;
    };
  }

  get f() {
    return this.investmentProposalForm.controls;
  }

  onSubmit(form: any) {
    this.submitted = true;
    if (!form.valid) {
      return false;
    }

    (async () => {
      Swal.fire({
        title: `<h3>Enviar información de pago</h3>`,
        icon: "info",

        html: `<div>Notificar a:</div>${this.generated_inputs_next}`,
        confirmButtonText: "Enviar requisición",
        showCancelButton: true,
        cancelButtonText: "Cancelar",
        showLoaderOnConfirm: true,

        preConfirm: () => {
          let array = [];

          for (let i = 0; i < this.userListNext.length; i++) {
            let html_input: HTMLInputElement = document.getElementById(
              "next-" + this.userListNext[i].name
            ) as HTMLInputElement;
            let html_value: string = html_input.value;
            if (html_input.checked == true) {
              array.push(html_value);
            }
          }
          this.formData = new FormData();
          this.formData.append("id_inversion", this.investmentProposalID);
          this.formData.append("evidencia", this.fileData);
          this.formData.append("step", "next");
          this.formData.append("comentario", form.value.comentario);
          this.formData.append("notificar", array.toString());

          this.paymentObject = {
            fecha_pago: form.value.fecha_pago.singleDate.formatted,
            id_inversion: this.investmentProposalID
            //comentario:
          };
        }
      }).then(result1 => {
        if (result1.dismiss) {
          return false;
        }

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

        this.investmentsService
          .updatePaymentInfoProposalInvestment(
            this.investmentProposalID,
            this.paymentObject
          )
          .subscribe(
            success => {
              this.investmentService
                .sendProposalInvestmentToNextStep(this.formData)
                .subscribe(
                  success => {
                    if (success) {
                      Swal.fire({
                        allowOutsideClick: false,
                        icon: "success",
                        showCancelButton: false,
                        title: "Exito",
                        confirmButtonText: "La propuesta ha sido liquidada"
                      }).then(result => {
                        Swal.close();
                        window.location.href = "#/investment-proposals";
                      });
                    }
                  },
                  err => {
                    Swal.fire({
                      icon: "error",
                      title: "Error en el servidor",
                      text: err.message
                    });
                  }
                );
            },
            err => {
              Swal.fire({
                icon: "error",
                title: "Error en el servidor",
                text: err.message
              });
            }
          );
      });
    })();
  }

  sendPaymentInfo(form: any) {}
}
