import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CloudObject, CloudQuery } from 'src/lib/ncloud';
import { ModalController } from '@ionic/angular';
import { AllProductsModalComponent } from '../all-products-modal/all-products-modal.component';
import { IonicModule } from '@ionic/angular';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-drug-category',
  templateUrl: './drug-category.page.html',
  styleUrls: ['./drug-category.page.scss'],
  standalone: true,
  imports: [
    IonicModule,
    CommonModule,
    AllProductsModalComponent
  ]
})
export class DrugCategoryPage implements OnInit {
  categoryName: string = '';
  products: Array<CloudObject> = [];

  constructor(
    private route: ActivatedRoute,
    private modalCtrl: ModalController
  ) {}

  async ngOnInit() {
    this.route.paramMap.subscribe(async params => {
      this.categoryName = params.get('name') || '';
      await this.loadProducts();
    });
  }

  async loadProducts() {
    try {
      const query = new CloudQuery('Drug');
      query.equalTo('category', this.categoryName);
      this.products = await query.find();
    } catch (error) {
      console.error('加载分类药品数据失败', error);
    }
  }

  async openDetailModal(product: any) {
    const modal = await this.modalCtrl.create({
      component: AllProductsModalComponent, // 确保存在此组件
      componentProps: { product: product },
      cssClass: 'bottom-modal'
    });
    return await modal.present();
  }

  dismiss() {
    window.history.back();
  }
}