// dish-management.component.ts
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { CloudObject, CloudQuery } from '../../../../../lib/ncloud';

@Component({
  selector: 'app-dish-management',
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './dish-management.component.html',
  styleUrls: ['./dish-management.component.css']
})
export class DishManagementComponent implements OnInit {
  // 菜品数据
  dishes: any[] = [];
  categories: any[] = [];
  
  // 当前编辑的菜品
  currentDish: any = {
    name: '',
    description: '',
    isActive: true,
    category: null,
    preparationTime: 0,
    spicyLevel: 0,
    tags: []
  };
  
  // UI状态
  isEditing = false;
  newTag = '';
  isLoading = true;
  showForm = false;
  searchTerm = '';

  async ngOnInit() {
    await this.loadDishes();
    await this.loadCategories();
  }

  // 加载菜品列表
  async loadDishes() {
    this.isLoading = true;
    try {
      const query = new CloudQuery('Dish');
      query.include('category');
    //   query.descending('createdAt');
      
      // 添加搜索条件
      if (this.searchTerm) {
        query.equalTo('name', this.searchTerm);
      }
      
      this.dishes = await query.find();
    } catch (error) {
      console.error('加载菜品失败:', error);
    } finally {
      this.isLoading = false;
    }
  }

  // 加载分类
  async loadCategories() {
    try {
      const query = new CloudQuery('Category');
    //   query.ascending('sortOrder');
      this.categories = await query.find();
    } catch (error) {
      console.error('加载分类失败:', error);
    }
  }

  // 开始创建新菜品
  startCreate() {
    this.isEditing = false;
    this.showForm = true;
    this.currentDish = {
      name: '',
      description: '',
      isActive: true,
      category: null,
      preparationTime: 0,
      spicyLevel: 0,
      tags: []
    };
  }

  // 开始编辑菜品
  startEdit(dish: any) {
    this.isEditing = true;
    this.showForm = true;
    this.currentDish = {
      ...dish,
      category: dish.category?.objectId || null
    };
  }

  // 取消编辑
  cancelEdit() {
    this.showForm = false;
    this.currentDish = {
      name: '',
      description: '',
      isActive: true,
      category: null,
      preparationTime: 0,
      spicyLevel: 0,
      tags: []
    };
  }

  // 添加标签
  addTag() {
    if (this.newTag.trim() && !this.currentDish.tags.includes(this.newTag.trim())) {
      this.currentDish.tags.push(this.newTag.trim());
      this.newTag = '';
    }
  }

  // 移除标签
  removeTag(tag: string) {
    this.currentDish.tags = this.currentDish.tags.filter((t: string) => t !== tag);
  }

  // 保存菜品
  async saveDish() {
    const dish = new CloudObject('Dish');
    
    // 如果是编辑，设置对象ID
    if (this.isEditing && this.currentDish.objectId) {
      dish.id = this.currentDish.objectId;
    }
    
    // 设置菜品属性
    dish.set({
      name: this.currentDish.name,
      description: this.currentDish.description,
      isActive: this.currentDish.isActive,
      category: this.currentDish.category 
        ? { __type: 'Pointer', className: 'Category', objectId: this.currentDish.category } 
        : null,
      preparationTime: Number(this.currentDish.preparationTime),
      spicyLevel: Number(this.currentDish.spicyLevel),
      tags: this.currentDish.tags
    });

    try {
      await dish.save();
      this.showForm = false;
      await this.loadDishes();
    } catch (error) {
      console.error('保存菜品失败:', error);
    }
  }

  // 删除菜品
  async deleteDish(dishId: string) {
    if (confirm('确定要删除这个菜品吗？')) {
      const dish = new CloudObject('Dish');
      dish.id = dishId;
      
      try {
        await dish.destroy();
        await this.loadDishes();
      } catch (error) {
        console.error('删除菜品失败:', error);
      }
    }
  }

  // 切换菜品状态
  async toggleStatus(dish: any) {
    const dishObj = new CloudObject('Dish');
    dishObj.id = dish.objectId;
    dishObj.set({ isActive: !dish.get('isActive') });
    
    try {
      await dishObj.save();
      await this.loadDishes();
    } catch (error) {
      console.error('更新状态失败:', error);
    }
  }

  // 搜索菜品
  async search() {
    await this.loadDishes();
  }
}