import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { PagingSortPatientResultDto } from '@proxy/dto';
import { Gender, Status } from '@proxy/global-enum';
import { PatientService } from '@proxy/patients';
import { CreateUpdatePatientRecordDto, PatientDto, PatientRecordDto } from '@proxy/patients/dto';
import { PermissionService } from '@abp/ng.core';
import { ActivatedRoute, Router } from '@angular/router';
import { environment } from 'src/environments/environment';
import { Confirmation, ConfirmationService, ToasterService } from '@abp/ng.theme.shared';

@Component({
  selector: 'app-patient-record',
  templateUrl: './patient-record.component.html',
  styleUrl: './patient-record.component.scss',
  providers: [PatientService, ConfirmationService, ToasterService, PermissionService],
})
export class PatientRecordComponent implements OnInit {
  globalFilter: string = '';
  patientrecords: PatientRecordDto[];
  totalRecords: number = 0;
  loading: boolean = false;
  patientDialog: boolean = false;
  selectedPatient: CreateUpdatePatientRecordDto;
  patientdto: PatientDto;
  isEditMode: boolean = false;
  patientDialogTitle: string = '';
  params: PagingSortPatientResultDto;
  status: any;
  gender: any;
  statuslist: any;
  selectdateOfAdmission: Date = new Date();
  selectnextFollowUp: Date = new Date();
  createpermission: boolean;
  editpermission: boolean;
  deletepermission: boolean;
  patientId: any;
  patientImageUrl: string;
  labReportUrlpath: string;
  medicationHistoryUrlpath: string;
  medicationUrlpath: string;
  guid: string = '00000000-0000-0000-0000-000000000000';
  options: Partial<Confirmation.Options> = {
    hideCancelBtn: false,
    hideYesBtn: false,
    dismissible: false,
    cancelText: 'Close',
    yesText: 'Confirm',
    messageLocalizationParams: ['Demo'],
    titleLocalizationParams: [],
    // You can customize icon
    // icon: 'fa fa-exclamation-triangle', // or
    // iconTemplate : '<img src="custom-image-path.jpg" alt=""/>'
  };

  constructor(
    private patientService: PatientService,
    private confirmation: ConfirmationService,
    private permissionChecker: PermissionService,
    private toaster: ToasterService,
    private route: ActivatedRoute,
    private router: Router
  ) {}

  ngOnInit() {
    this.patientId = this.route.snapshot.paramMap.get('id');
    console.log(this.patientId);

    this.createpermission = this.permissionChecker.getGrantedPolicy(
      'HospitalManagementSystem.Patient.Create'
    );
    this.editpermission = this.permissionChecker.getGrantedPolicy(
      'HospitalManagementSystem.Patient.Edit'
    );
    this.deletepermission = this.permissionChecker.getGrantedPolicy(
      'HospitalManagementSystem.Patient.Delete'
    );
    this.status = Status;
    this.gender = Gender;
    this.patientService.getStatusDropdown().subscribe(result => {
      this.statuslist = result;
    });

    this.resetselectpatient();
  }

  resetselectpatient() {
    this.selectedPatient = {
      patientId: this.patientId,
      dateOfAdmission: '',
      // labReportUrl: '',
      // medicationUrl: '',
      // medicationHistoryUrl: '',
      nextFollowUp: '',
      diagnosis: '',
      treatmentPlan: '',
      doctorNotes: '',
      insuranceProvider: '',
      status: Status.InTreatment,
    };
    this.labReportUrlpath = '';
    this.medicationUrlpath = '';
    this.medicationHistoryUrlpath = '';
    this.selectdateOfAdmission = new Date();
    this.selectnextFollowUp = new Date();
  }

  loadPatient(event: any, id: any) {
    this.selectedPatient.patientId = this.patientId;
    this.loading = true;
    let order = event.sortOrder == 1 ? ' asc' : ' desc';
    event.sortField = event.sortField == undefined ? 'id' : event.sortField;
    this.params = {
      skipCount: event.first,
      maxResultCount: event.rows,
      sorting: event.sortField + order,
      search: event.globalFilter == null ? '' : event.globalFilter,
    };
    this.patientService.getPatientById(this.patientId).subscribe(result => {
      this.patientdto = result;
      this.patientImageUrl = environment.apis.default.url + result.imagepath;
    });
    this.patientService.getPatientRecordList(this.params, id).subscribe(data => {
      this.patientrecords = data.items;
      // console.log(data.items);
      this.totalRecords = data.totalCount;
      this.loading = false;
    });
  }

  backtopatient() {
    this.router.navigate(['/patients/all-patients']);
  }

  exportPatient() {
    this.patientService.getExportPatientRecord().subscribe(result => {
      const binary = atob(result.fileContent);
      const len = binary.length;
      const bytes = new Uint8Array(len);

      for (let i = 0; i < len; i++) {
        bytes[i] = binary.charCodeAt(i);
      }

      const blob = new Blob([bytes], { type: 'application/xlsx' });

      const url = window.URL.createObjectURL(blob);

      const link = document.createElement('a');
      link.href = url;
      link.download = result.fileName;

      document.body.appendChild(link);
      link.click();

      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    });
  }

  openNewPatientDialog() {
    this.patientDialogTitle = 'New Patient Record';
    this.resetselectpatient();
    this.patientDialog = true;
    this.isEditMode = false;
  }

  editPatient(Patient: any) {
    this.resetselectpatient();
    this.patientDialogTitle = 'Edit Patient';
    this.patientService.getPatientRecordById(Patient.id).subscribe(result => {
      this.selectedPatient = result;
      this.selectedPatient.patientId = this.patientId;
      this.selectdateOfAdmission = new Date(this.selectedPatient.dateOfAdmission);
      this.selectnextFollowUp = new Date(this.selectedPatient.nextFollowUp);
      this.labReportUrlpath = result.labReportUrl != null ? result.labReportUrl.split('\\')[3] : '';
      this.medicationUrlpath =
        result.medicationUrl != null ? result.medicationUrl.split('\\')[3] : '';
      this.medicationHistoryUrlpath =
        result.medicationHistoryUrl != null ? result.medicationHistoryUrl.split('\\')[3] : '';
      console.log(result);
    });
    this.patientDialog = true;
    this.isEditMode = true;
  }

  deletePatient(id: any) {
    this.confirmation
      .warn('Do you really want to delete this record ?', {
        key: '::AreYouSure',
        defaultValue: 'Are you sure?',
      })
      .subscribe((status: Confirmation.Status) => {
        // your code here
        if (status == 'confirm') {
          this.patientService.deletePatientRecord(id).subscribe(() => {
            this.loadPatient(this.params, this.patientId);
            this.toaster.success('Patient deleted successfully', 'Success');
          });
        }
      });
  }

  handleLabReportUpload(event: Event): void {
    const input = event.target as HTMLInputElement;
    if (input && input.files) {
      const tag = 'Lab-Report';
      const formdata = new FormData();
      formdata.append('file', input.files[0]);
      this.UploadFileData(tag, formdata);
    }
  }

  handleMedicationsUpload(event: any): void {
    const input = event.target as HTMLInputElement;
    if (input && input.files) {
      const tag = 'Medication';
      const formdata = new FormData();
      formdata.append('file', input.files[0]);
      this.UploadFileData(tag, formdata);
    }
  }

  handleMedicationHistoryUpload(event: any): void {
    const input = event.target as HTMLInputElement;
    if (input && input.files) {
      const tag = 'Medication-History';
      const formdata = new FormData();
      formdata.append('file', input.files[0]);
      this.UploadFileData(tag, formdata);
    }
  }

  UploadFileData(tag: string, formdata: FormData) {
    this.patientService.uploadFile(tag, formdata).subscribe(result => {
      switch (tag) {
        case 'Lab-Report':
          this.selectedPatient.labReportUrlID = result;
          break;
        case 'Medication':
          this.selectedPatient.medicationUrlID = result;
          break;
        case 'Medication-History':
          this.selectedPatient.medicationHistoryUrlID = result;
          break;
      }
    });
  }

  savePatient(form: NgForm) {
    // console.log(form);
    this.selectedPatient.patientId = this.patientId;
    this.selectedPatient.status = this.patientdto.status;
    this.selectedPatient.dateOfAdmission = this.selectdateOfAdmission.toDateString();
    this.selectedPatient.nextFollowUp = this.selectnextFollowUp.toDateString();
    this.selectedPatient.labReportUrlID = this.selectedPatient.labReportUrlID
      ? this.selectedPatient.labReportUrlID.replace('"', '').replace('"', '')
      : this.guid;
    this.selectedPatient.medicationUrlID = this.selectedPatient.medicationUrlID
      ? this.selectedPatient.medicationUrlID.replace('"', '').replace('"', '')
      : this.guid;
    this.selectedPatient.medicationHistoryUrlID = this.selectedPatient.medicationHistoryUrlID
      ? this.selectedPatient.medicationHistoryUrlID.replace('"', '').replace('"', '')
      : this.guid;
    console.log(this.selectedPatient);

    if (this.isEditMode) {
      this.patientService
        .updatePatientRecord(this.selectedPatient.id, this.selectedPatient)
        .subscribe(
          result => {
            this.toaster.success('Patient updated successfully', 'Success');
            this.patientDialog = false;
            console.log(result);

            this.loadPatient(
              {
                first: 0,
                rows: 10,
                sortField: 'id',
                sortOrder: 1,
                globalFilter: null,
              },
              this.patientId
            );
          },
          error => {
            console.log(error);
            this.closeDialog();
          }
        );
    } else {
      this.patientService.createPatientRecord(this.selectedPatient).subscribe(
        () => {
          this.toaster.success('Patient created successfully', 'Success');
          this.patientDialog = false;
          this.loadPatient(
            {
              first: 0,
              rows: 10,
              sortField: 'id',
              sortOrder: 1,
              globalFilter: null,
            },
            this.patientId
          );
        },
        error => {
          console.log(error);
          this.closeDialog();
        }
      );
    }
  }

  closeDialog() {
    this.patientDialog = false;
  }
}
