// JavaScript для страницы каталога товаров class CatalogManager { constructor() { this.warehouse = new WarehouseManager(); this.currentItems = []; this.filteredItems = []; this.currentPage = 1; this.itemsPerPage = 12; this.currentView = 'grid'; this.filters = {}; this.init(); } init() { $(document).ready(() => { this.loadCatalog(); this.bindEvents(); this.initializeFilters(); }); } bindEvents() { // Поиск и фильтры $('#searchInput').on('input', (e) => this.handleSearch(e.target.value)); $('#categoryFilter').on('change', (e) => this.handleCategoryFilter(e.target.value)); $('#priceMin, #priceMax').on('input', () => this.handlePriceFilter()); $('#inStockFilter, #lowStockFilter').on('change', () => this.applyFilters()); $('#clearFiltersBtn').on('click', () => this.clearFilters()); // Переключение вида $('input[name="viewMode"]').on('change', (e) => { this.currentView = e.target.id === 'gridView' ? 'grid' : 'list'; this.renderCatalog(); }); // Модальные окна $('#saveItemBtn').on('click', () => this.addNewItem()); $('#updateItemBtn').on('click', () => this.updateItem()); // Экспорт $('#exportBtn').on('click', () => this.exportCatalog()); } // Загрузка каталога async loadCatalog() { try { this.showLoading(); // Загружаем товары this.currentItems = await this.warehouse.getAllItems(); // Загружаем категории const categories = await this.warehouse.getCategories(); this.populateCategoryFilters(categories); // Применяем фильтры и рендерим this.applyFilters(); this.updateStatistics(); this.hideLoading(); } catch (error) { console.error('Ошибка при загрузке каталога:', error); auth.showNotification('Ошибка при загрузке каталога', 'danger'); this.hideLoading(); } } // Инициализация фильтров initializeFilters() { // Устанавливаем значения по умолчанию this.filters = { search: '', category: '', minPrice: null, maxPrice: null, inStock: false, lowStock: false }; } // Заполнение фильтра категорий populateCategoryFilters(categories) { const categoryFilter = $('#categoryFilter'); const addItemCategory = $('#itemCategory'); const editItemCategory = $('#editItemCategory'); // Очищаем существующие опции (кроме первой) categoryFilter.find('option:not(:first)').remove(); addItemCategory.find('option:not(:first)').remove(); editItemCategory.find('option:not(:first)').remove(); // Добавляем категории categories.forEach(category => { const option = ``; categoryFilter.append(option); addItemCategory.append(option); editItemCategory.append(option); }); } // Обработка поиска handleSearch(query) { this.filters.search = query; this.applyFilters(); } // Обработка фильтра категории handleCategoryFilter(category) { this.filters.category = category; this.applyFilters(); } // Обработка фильтра цены handlePriceFilter() { this.filters.minPrice = $('#priceMin').val() ? parseFloat($('#priceMin').val()) : null; this.filters.maxPrice = $('#priceMax').val() ? parseFloat($('#priceMax').val()) : null; this.applyFilters(); } // Применение всех фильтров applyFilters() { this.filters.inStock = $('#inStockFilter').is(':checked'); this.filters.lowStock = $('#lowStockFilter').is(':checked'); // Фильтруем товары this.filteredItems = this.currentItems.filter(item => { // Поиск по названию, описанию и штрих-коду if (this.filters.search) { const searchQuery = this.filters.search.toLowerCase(); const matchesSearch = item.name.toLowerCase().includes(searchQuery) || item.description.toLowerCase().includes(searchQuery) || item.barcode.includes(searchQuery); if (!matchesSearch) return false; } // Фильтр по категории if (this.filters.category && item.category !== this.filters.category) { return false; } // Фильтр по цене if (this.filters.minPrice && item.price < this.filters.minPrice) { return false; } if (this.filters.maxPrice && item.price > this.filters.maxPrice) { return false; } // Фильтр по наличию if (this.filters.inStock && item.quantity <= 0) { return false; } // Фильтр по низкому запасу if (this.filters.lowStock && item.quantity > item.minQuantity) { return false; } return true; }); this.currentPage = 1; this.renderCatalog(); this.updateStatistics(); } // Очистка фильтров clearFilters() { $('#searchInput').val(''); $('#categoryFilter').val(''); $('#priceMin').val(''); $('#priceMax').val(''); $('#inStockFilter').prop('checked', false); $('#lowStockFilter').prop('checked', false); this.initializeFilters(); this.applyFilters(); } // Рендеринг каталога renderCatalog() { const container = $('#catalogContainer'); container.empty(); if (this.filteredItems.length === 0) { container.html(`
Попробуйте изменить параметры поиска или фильтры
${item.description.substring(0, 60)}${item.description.length > 60 ? '...' : ''}
Загрузка каталога...