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-upload-liquidation",
  templateUrl: "./upload-liquidation.component.html",
  styleUrls: ["./upload-liquidation.component.scss"]
})
export class UploadLiquidationComponent implements OnInit {
  title: string = "Subir hoja de liquidación";
  // For daterange

  form: FormGroup;
  fileData: File = null;
  previewUrl: any = null;
  fileUploadProgress: string = null;
  uploadedFilePath: string = null;
  interval: any;
  indexDynamicComponent: number;
  investmentProposalID: string;
  investmentExists;
  codigo_inversion: string = "";
  empresa: string = "";
  estado: string = "";
  emisor: string = "";
  instrumento: string = "";

  investmentProposalForm: FormGroup;
  submitted: boolean = false;
  paymentObject: Object;

  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
      .getProposalInvestment(this.investmentProposalID)
      .subscribe(resp => {
        this.codigo_inversion = resp["result"]["codigo_inversion"];
        this.estado = resp["result"]["id_estado_inversion"]["nombre"];
        this.instrumento =
          resp["result"]["id_inversion_instrumento"]["id_tipo_instrumento"][
            "nombre"
          ];
        this.emisor = resp["result"]["id_tipo_emisor"]["nombre"];

        this.empresa = resp["result"]["id_empresa"]["nombre"];
        Swal.close();
      });

    this.investmentProposalForm = this.formBuilder.group({
      id_inversion: [this.investmentProposalID]
    });
  }

  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 (this.fileData == null) {
      return false;
    }

    const formData = new FormData();
    formData.append("id_inversion", this.investmentProposalID);
    formData.append("hoja_liquidacion", this.fileData);

    this.investmentService.sendLiquidationFile(formData).subscribe(
      success => {
        if (success) {
          Swal.fire({
            allowOutsideClick: false,
            icon: "success",
            showCancelButton: false,
            title: "Exito",
            confirmButtonText: "Se ha subido la hoja de liquidación"
          }).then(result => {
            Swal.close();
            window.location.href = "#/investment-proposals";
          });
        }
      },
      err => {
        Swal.fire({
          icon: "error",
          title: "Error en el servidor",
          text: err.message
        });
      }
    );
  }
}
