import { defineStore } from 'pinia' import type { FoodMealMenu, FoodMealServiceArea } from '@/types/meal' const CURRENT_SERVICE_AREA_ID_KEY = 'meal_current_service_area_id' const LEGACY_CURRENT_RESTAURANT_ID_KEY = 'meal_current_restaurant_id' export const useMealStore = defineStore('meal', { state: () => ({ selectedDate: '', selectedMealType: '', menu: null as FoodMealMenu | null, quantities: {} as Record, serviceAreas: [] as FoodMealServiceArea[], currentServiceArea: null as FoodMealServiceArea | null }), getters: { selectedItems: state => Object.entries(state.quantities).filter(([, quantity]) => quantity > 0), currentServiceAreaId: state => state.currentServiceArea?.id || '', restaurants: state => state.serviceAreas, currentRestaurant: state => state.currentServiceArea, currentRestaurantId: state => state.currentServiceArea?.id || '' }, actions: { setServiceAreas(serviceAreas: FoodMealServiceArea[]) { this.serviceAreas = serviceAreas const savedId = uni.getStorageSync(CURRENT_SERVICE_AREA_ID_KEY) || uni.getStorageSync(LEGACY_CURRENT_RESTAURANT_ID_KEY) const saved = savedId ? serviceAreas.find(item => item.id === savedId) : null const currentStillExists = this.currentServiceArea ? serviceAreas.find(item => item.id === this.currentServiceArea?.id) : null this.currentServiceArea = saved || currentStillExists || serviceAreas[0] || null if (this.currentServiceArea?.id) uni.setStorageSync(CURRENT_SERVICE_AREA_ID_KEY, this.currentServiceArea.id) }, setRestaurants(serviceAreas: FoodMealServiceArea[]) { this.setServiceAreas(serviceAreas) }, setCurrentServiceArea(serviceArea: FoodMealServiceArea) { if (this.currentServiceArea?.id !== serviceArea.id) this.clearServiceAreaRelatedState() this.currentServiceArea = serviceArea uni.setStorageSync(CURRENT_SERVICE_AREA_ID_KEY, serviceArea.id) }, setCurrentRestaurant(serviceArea: FoodMealServiceArea) { this.setCurrentServiceArea(serviceArea) }, setDate(date: string) { this.selectedDate = date }, setMealType(mealType: string) { this.selectedMealType = mealType }, setMenu(menu: FoodMealMenu | null) { this.menu = menu this.quantities = {} }, setQuantity(menuItemId: string, quantity: number) { if (quantity <= 0) delete this.quantities[menuItemId] else this.quantities[menuItemId] = quantity }, clearCart() { this.quantities = {} }, clearServiceAreaRelatedState() { this.selectedDate = '' this.selectedMealType = '' this.menu = null this.quantities = {} }, clearRestaurantRelatedState() { this.clearServiceAreaRelatedState() } } })