import { Component } from '@angular/core';
import { ModalController, IonModal, IonHeader, IonToolbar, IonTitle, IonContent, IonList, IonItem, IonLabel, IonAvatar, IonButton, IonSegment, IonSegmentButton, IonSegmentContent, IonSegmentView, IonCardContent, IonCardTitle, IonCardHeader, IonCard, IonIcon, IonButtons, IonGrid, IonRow, IonThumbnail, IonSearchbar, IonCol } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { airplane, bluetooth, call, wifi, close } from 'ionicons/icons';
import { SaleCardComponent } from '../component/sale-card/sale-card.component';
import { CommonModule } from '@angular/common';
import { CloudObject, CloudQuery } from 'src/lib/ncloud';
import { Router } from '@angular/router';
import { FmChatModalInput } from 'fmode-ng';
import { AllProductsModalComponent } from '../all-products-modal/all-products-modal.component';
import { DetailModalComponent } from '../detail-modal/detail-modal.component'; // 确保此组件已创建
import { IonicModule } from '@ionic/angular';

addIcons({ airplane, bluetooth, call, wifi });

@Component({
  selector: 'app-tab3',
  templateUrl: 'tab3.page.html',
  styleUrls: ['tab3.page.scss'],
  standalone: true,
  imports: [
    IonicModule,
    CommonModule,
    AllProductsModalComponent,
    DetailModalComponent,
    SaleCardComponent,
    FmChatModalInput
  ]
})
export class Tab3Page {
  showDetailModal = false;  // 控制详情模态显示与否
  currentProduct: any;      // 当前选择的药品信息

  categories = [
    { name: '皮肤用药', image: 'https://app.fmode.cn/dev/jxnu/202226701019/yao1.png' },
    { name: '肠胃消化', image: 'https://app.fmode.cn/dev/jxnu/202226701019/yao5.png' },
    { name: '呼吸用药', image: 'https://app.fmode.cn/dev/jxnu/202226701019/yao11.png' },
    { name: '营养补充', image: 'https://app.fmode.cn/dev/jxnu/202226701019/yao9.png' },
    { name: '家庭常备', image: 'https://app.fmode.cn/dev/jxnu/202226701019/yao12.png' },
    { name: '耳鼻咽喉', image: 'https://app.fmode.cn/dev/jxnu/202226701019/yao10.png' },
    { name: '骨科疼痛', image: 'https://app.fmode.cn/dev/jxnu/202226701019/yao6.png' },
    { name: '心脑血管', image: 'https://app.fmode.cn/dev/jxnu/202226701019/yao7.png' },
  ];

  products: Array<CloudObject> = [];
  allProducts: Array<CloudObject> = []; // 存储所有药品数据，用于分类过滤

  hotProducts: Array<CloudObject> = [];
  specialProducts: Array<CloudObject> = [];

  constructor(
    private modalCtrl: ModalController,
    private router: Router,
  ) {}

  async ngOnInit() {
    await this.loadProducts();
  }

  async loadProducts() {
    try {
      const query = new CloudQuery('Drug');
      this.products = await query.find();
      this.allProducts = [...this.products]; // 初始化所有产品

      // 分类“热销”和“特价”药品
      this.hotProducts = this.allProducts.filter(product => product.get('marketing') === 'hot');
      this.specialProducts = this.allProducts.filter(product => product.get('marketing') === 'special');
    } catch (error) {
      console.error('加载药品数据失败', error);
    }
  }

  // 打开详情模态窗口
  openDetailModal(product: any) {
    this.currentProduct = product;
    this.showDetailModal = true;
  }

  // 关闭详情模态窗口
  closeDetailModal() {
    this.showDetailModal = false;
    this.currentProduct = null;
  }

  // 根据分类导航到 drug-category 页面
  onCategoryClick(category: any) {
    this.router.navigate(['/drug-category', category.name]);
  }

  // 分享链接功能（可选）
  shareDetailModal() {
    // 实现分享功能
    console.log('分享功能待实现');
  }

  // 复制链接功能
  copyLink() {
    const link = window.location.href;
    navigator.clipboard.writeText(link).then(() => {
      console.log('链接已复制');
      // 可添加用户提示
    }).catch(err => {
      console.error('复制失败', err);
    });
  }

  // 搜索功能
  searchTerm: string = '';

  async searchProducts(event: any) {
    this.searchTerm = event.detail.value.toLowerCase();
    if (this.searchTerm) {
      this.products = this.allProducts.filter(product =>
        product.get('name').toLowerCase().includes(this.searchTerm) ||
        product.get('function').toLowerCase().includes(this.searchTerm) ||
        product.get('composition').toLowerCase().includes(this.searchTerm)
      );
    } else {
      this.products = [...this.allProducts];
    }
  }

  // 查看更多功能，打开 AllProductsModalComponent 模态窗口
  async viewMore(type: string) {
    let filteredProducts: Array<CloudObject> = [];
    let title: string = '';

    if (type === 'hot') {
      filteredProducts = this.hotProducts;
      title = '热销药品';
    } else if (type === 'special') {
      filteredProducts = this.specialProducts;
      title = '特价药品';
    }

    const modal = await this.modalCtrl.create({
      component: AllProductsModalComponent,
      componentProps: {
        products: filteredProducts,
        title: title
      },
      cssClass: 'bottom-modal'
    });

    return await modal.present();
  }
}