import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ApiService } from 'app/api.service';
import { Lightbox } from 'ngx-lightbox';

@Component({
  selector: 'app-customers-prescription-pending',
  templateUrl: './customers-prescription-pending.component.html',
  styleUrls: ['./customers-prescription-pending.component.scss']
})
export class CustomersPrescriptionPendingComponent implements OnInit {
  public prescriptions: any = [];
  constructor(private title: Title, 
              public apiService: ApiService,
              private _lightbox: Lightbox) {
    this.title.setTitle("Recetas por autorizar");
    this.apiService.getPendingPrescriptions().subscribe((data:any)=> {
      this.prescriptions = data.data;
    });
  }

  ngOnInit() {
  }
  renderFiles(files:string) {
    let splitFiles = files.split(',');
    let a = [];
    if (splitFiles.length > 0 && files!="") {
      for (let x = 0; x < splitFiles.length; x++) {
        a.push(splitFiles[x]);
      }
    }
    return a;
  }
  rechazar(index: number) {
    let id = this.prescriptions[index].id;
    let motivo = this.apiService.prompt("Indique motivo:");
    motivo.then((data:any)=> {
      if (data.dismiss=="cancel") { }
      else if (data.value=="") {
        this.apiService.showError("No puedes rechazar receta sin motivo");
      } else {
        this.apiService.rejectPrescription(id, data.value).subscribe((data:any)=>{
          if (data.res == "OK") {
            this.prescriptions.splice(index,1);
          } else {
            this.apiService.showError("Error",data.msg);
          }
        });
        this.prescriptions.splice(index,1);
      }
    });
  }
  aprobar(index:number) {
    let id = this.prescriptions[index].id;
    let confirm = this.apiService.confirm("Confirmar","Deseas aprobar la receta #"+this.prescriptions[index].id);
    confirm.then((data:any)=> { 
      if (data.dismiss=="cancel") { }
      else if (data.value) {
        this.apiService.authorizePrescription(id).subscribe((data:any)=>{
          if (data.res == "OK") {
            this.prescriptions.splice(index,1);
          } else {
            this.apiService.showError("Error",data.msg);
          }
        });
      }
    });
  }
  lightbox(src:string, caption: string) {
    let tmp = [];
    
    tmp.push({ src: src, caption: caption });
    this._lightbox.open(tmp, 0);
  }

}
