// src/app/medicine-detail/medicine-detail.page.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MedicineService } from '../services/medicine.service'; // 确认路径是否正确
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Medicine } from '../services/medicine.service'; // 导入 Medicine 接口

@Component({
  selector: 'app-medicine-detail',
  templateUrl: './medicine-detail.page.html',
  styleUrls: ['./medicine-detail.page.scss']
})
export class MedicineDetailPage implements OnInit {
  medicine: Medicine | null = null; // 更新为使用 Medicine 接口
  loading: boolean = true;
  error: string | null = null;

  constructor(
    private route: ActivatedRoute,
    private medicineService: MedicineService // 确保已经定义了 MedicineService
  ) {}

  ngOnInit() {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.loadMedicineDetails(id);
  }

  loadMedicineDetails(id: number) {
    this.loading = true;
    this.error = null;

    this.medicineService.getMedicineById(id).pipe(
      catchError((err) => {
        this.error = err.message || 'An unexpected error occurred';
        this.loading = false;
        return throwError(() => err);
      })
    ).subscribe(
      (data: Medicine) => { // 使用 Medicine 接口作为类型
        this.medicine = data;
        this.loading = false;
      },
      (error) => {
        this.error = error.message || 'An unexpected error occurred';
        this.loading = false;
      }
    );
  }
}