import { PermissionService } from '@abp/ng.core';
import { Confirmation, ConfirmationService, ToasterService } from '@abp/ng.theme.shared';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { PagingSortPatientResultDto } from '@proxy/dto';
import { Gender, Status } from '@proxy/global-enum';
import { PatientService } from '@proxy/patients';
import { PatientDto, CreateUpdatePatientDto } from '@proxy/patients/dto';

@Component({
  selector: 'app-all-patients',
  templateUrl: './all-patients.component.html',
  styleUrl: './all-patients.component.scss',
  providers: [PatientService, ConfirmationService, ToasterService, PermissionService],
})
export class AllPatientsComponent implements OnInit {
  globalFilter: string = '';
  patients: PatientDto[];
  totalRecords: number = 0;
  loading: boolean = false;
  patientDialog: boolean = false;
  selectedPatient: CreateUpdatePatientDto;
  isEditMode: boolean = false;
  patientDialogTitle: string = '';
  params: PagingSortPatientResultDto;
  status: any;
  gender: any;
  statuslist: any;
  selectedstatus: any = 0;
  selectedgender: any = 0;
  selectadmissionDate: Date = new Date();
  selectdischargeDate: Date = new Date();
  createpermission: boolean;
  editpermission: boolean;
  deletepermission: boolean;
  error: string = '';
  imgpath: 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 http: HttpClient,
    private confirmation: ConfirmationService,
    private toaster: ToasterService,
    private permissionChecker: PermissionService,
    private router: Router
  ) {}

  ngOnInit() {
    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();
    this.loadPatient({
      first: 0,
      rows: 10,
      sortField: 'id',
      sortOrder: 1,
      globalFilter: null,
    });
  }
  resetselectpatient() {
    this.selectedPatient = {
      name: '',
      gender: Gender.Male,
      mobile: '',
      email: '',
      age: 0,
      treatment: '',
      doctorAssigned: '',
      address: '',
      bloodGroup: '',
      admissionDate: '',
      dischargeDate: '',
      status: Status.InTreatment,
    };
    this.imgpath = '';
    this.selectedgender = 0;
    this.selectedstatus = 0;
  }

  loadPatient(event: any) {
    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.getPatientList(this.params).subscribe(data => {
      this.patients = data.items;
      this.totalRecords = data.totalCount;
      this.loading = false;
    });
  }

  exportPatient() {
    this.patientService.getExportPatientData().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';
    this.resetselectpatient();
    this.selectedgender = 0;
    this.selectedstatus = 0;
    this.patientDialog = true;
    this.isEditMode = false;
  }

  addnewrecord(id: any) {
    this.router.navigate(['/patients/patient-record', id]);
  }

  profileimageupload(event: Event) {
    if (this.selectedPatient.name == '') {
      this.error = 'Please Type a Name';
      return;
    }
    const input = event.target as HTMLInputElement;
    if (input.files.length > 0) {
      const tag = 'Image';
      const formdata = new FormData();
      formdata.append('file', input.files[0]);
      this.UploadFileData(tag, formdata);
    } else {
      return;
    }
  }

  UploadFileData(tag: string, formdata: FormData) {
    this.patientService.uploadFile(tag, formdata).subscribe(result => {
      this.selectedPatient.imageID = result;
    });
  }

  editPatient(Patient: any) {
    this.resetselectpatient();
    this.patientDialogTitle = 'Edit Patient';
    this.patientService.getPatientById(Patient.id).subscribe(result => {
      this.selectedPatient = result;
      this.imgpath = result.imagepath != null ? result.imagepath.split('\\')[3] : '';
      this.selectadmissionDate = new Date(this.selectedPatient.admissionDate);
      this.selectedgender = this.selectedPatient.gender;
      this.selectedstatus = this.selectedPatient.status;
    });
    this.patientDialog = true;
    this.isEditMode = true;
  }

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

  savePatient(form: NgForm) {
    console.log(form.controls);
    if (form.invalid) {
      Object.values(form.controls).forEach(control => control.markAsTouched());
      return;
    }
    this.selectedPatient.gender = this.selectedgender;
    this.selectedPatient.status = this.selectedstatus;
    this.selectedPatient.admissionDate = this.selectadmissionDate.toDateString();
    this.selectedPatient.dischargeDate = this.selectdischargeDate.toDateString();
    this.selectedPatient.imageID = this.selectedPatient.imageID
      ? this.selectedPatient.imageID.replace('"', '').replace('"', '')
      : this.guid;
    console.log(this.selectedPatient);

    if (this.isEditMode) {
      this.patientService.updatePatient(this.selectedPatient.id, this.selectedPatient).subscribe(
        () => {
          this.toaster.success('Patient updated successfully', 'Success');
          this.patientDialog = false;
          this.loadPatient({
            first: 0,
            rows: 10,
            sortField: 'id',
            sortOrder: 1,
            globalFilter: null,
          });
        },
        error => {
          console.log(error);
          this.closeDialog();
        }
      );
    } else {
      this.patientService.createPatient(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,
          });
        },
        error => {
          console.log(error);
          this.closeDialog();
        }
      );
    }
  }

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