import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CartService } from '../services/cart.service'; // 根据实际路径调整
import { BehaviorSubject } from 'rxjs';
import { CartItem } from '../services/cart.service'; // 确保路径正确
import { OrderService } from '../services/order.service'; 
import { take } from 'rxjs/operators';
import { trigger, state, style, transition, animate } from '@angular/animations';

@Component({
  selector: 'app-medicine-purchase',
  templateUrl: './medicine-purchase.page.html',
  styleUrls: ['./medicine-purchase.page.scss'],
  animations: [
    trigger('fadeItem', [
      state('void', style({ opacity: 0 })),
      state('*', style({ opacity: 1 })),
      transition(':enter', [animate('300ms ease-in')]),
      transition(':leave', [animate('300ms ease-out')])
    ])
  ]
})
export class MedicinePurchasePage implements OnInit {
  medicines = [
    { id: 1, name: '阿司匹林', price: 15.99, description: '用于缓解轻度至中度疼痛...', imageUrl: '../assets/images/药1.png' },
    { id: 2, name: '布洛芬', price: 12.99, description: '非甾体抗炎药...', imageUrl: '../assets/images/药2.png' },
    // 添加更多药品...
  ];

  cartItems$ = this.cartService.cartItems$;
  private cartTotalSubject = new BehaviorSubject<number>(0);
  cartTotal$ = this.cartTotalSubject.asObservable();

  constructor(
    private router: Router,
    private cartService: CartService,
    private orderService: OrderService // 注入OrderService
  ) {}

  ngOnInit() {
    this.cartService.cartItems$.subscribe(items => {
      const total = this.cartService.getCartTotal();
      this.cartTotalSubject.next(total);
    });
  }

  goToDetail(id: number) {
    this.router.navigate(['/medicine-detail', id]);
  }

  addToCart(medicine: any) {
    this.cartService.addToCart({ ...medicine, quantity: 1 });
  }

  removeFromCart(item: CartItem) {
    this.cartService.removeFromCart(item.id);
  }

  incrementQuantity(item: CartItem) {
    this.cartService.updateCartItem(item.id, item.quantity + 1);
  }

  decrementQuantity(item: CartItem) {
    if (item.quantity > 1) {
      this.cartService.updateCartItem(item.id, item.quantity - 1);
    } else {
      this.removeFromCart(item);
    }
  }

  updateQuantity(item: CartItem) {
    this.cartService.updateCartItem(item.id, item.quantity);
  }

  purchase() {
    this.cartService.cartItems$.pipe(take(1)).subscribe(cartItems => {
      if (cartItems.length === 0) {
        alert('购物车为空，请选择商品后再进行购买');
        return;
      }

      // 创建订单
      const orderId = this.orderService.createOrder(cartItems); // 确保类型匹配

      // 清空购物车
      this.cartService.clearCart();

      // 提示用户购买成功
      alert(`购买成功！订单号：${orderId}`);

      // 导航到订单页面
      this.router.navigate(['/orders']);
    });
  }
}