product-editor.js

6.13 KB
05/11/2024 06:28
JS
product-editor.js
const ProductEditor = {
    init() {
        this.bindEvents();
        this.loadFontAwesome();
    },

    loadFontAwesome() {
        // Load Font Awesome from CDN
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css';
        document.head.appendChild(link);
    },

    bindEvents() {
        // File Upload Handler
        document.getElementById('jsonUpload')?.addEventListener('change', (e) => {
            this.handleFileUpload(e.target.files[0]);
        });

        // Download Current Data
        document.getElementById('downloadJson')?.addEventListener('click', () => {
            this.downloadProductData();
        });
    },

    async handleFileUpload(file) {
        try {
            if (!file) return;

            Utils.showLoading();
            const reader = new FileReader();

            reader.onload = async (e) => {
                try {
                    const data = JSON.parse(e.target.result);
                    if (this.validateProductData(data)) {
                        await this.updateProductData(data);
                        NotificationManager.showSuccess('อัปเดตข้อมูลสินค้าสำเร็จ');
                        ProductManager.loadProducts(); // Refresh product display
                    }
                } catch (error) {
                    NotificationManager.showError('ไฟล์ JSON ไม่ถูกต้อง');
                    console.error('JSON parse error:', error);
                }
            };

            reader.readAsText(file);
        } catch (error) {
            NotificationManager.showError('เกิดข้อผิดพลาดในการอ่านไฟล์');
            console.error('File upload error:', error);
        } finally {
            Utils.hideLoading();
        }
    },

    validateProductData(data) {
        // Basic validation
        if (!data.products || !Array.isArray(data.products)) {
            NotificationManager.showError('รูปแบบข้อมูลไม่ถูกต้อง');
            return false;
        }

        // Validate each product
        const isValid = data.products.every(product => 
            product.id && 
            product.name && 
            typeof product.price === 'number' &&
            typeof product.available === 'boolean'
        );

        if (!isValid) {
            NotificationManager.showError('ข้อมูลสินค้าไม่ครบถ้วน');
            return false;
        }

        return true;
    },

    async updateProductData(data) {
        try {
            // ในที่นี้จะเก็บข้อมูลใน localStorage
            // ในการใช้งานจริงควรส่งไปยัง server
            Storage.save('productData', data);
            
            // Update state
            State.products = data.products;
            
            // Emit event
            EventBus.emit('productsUpdated', data);
            
            return true;
        } catch (error) {
            console.error('Update product data error:', error);
            return false;
        }
    },

    downloadProductData() {
        try {
            const data = Storage.load('productData') || {
                products: State.products,
                version: "1.0",
                lastUpdated: new Date().toISOString()
            };

            const blob = new Blob([JSON.stringify(data, null, 2)], {
                type: 'application/json'
            });

            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `products_${new Date().toISOString().split('T')[0]}.json`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
        } catch (error) {
            NotificationManager.showError('เกิดข้อผิดพลาดในการดาวน์โหลดไฟล์');
            console.error('Download error:', error);
        }
    },

    createEditorModal() {
        return `
        <div class="modal-content">
            <h2><i class="fas fa-edit"></i> จัดการข้อมูลสินค้า</h2>
            
            <div class="editor-actions">
                <div class="upload-section">
                    <label for="jsonUpload" class="button-modern">
                        <i class="fas fa-upload"></i> อัปโหลดไฟล์ JSON
                    </label>
                    <input type="file" id="jsonUpload" accept=".json" style="display: none;">
                </div>
                
                <button id="downloadJson" class="button-modern">
                    <i class="fas fa-download"></i> ดาวน์โหลดข้อมูลปัจจุบัน
                </button>
            </div>

            <div class="current-products">
                <h3><i class="fas fa-list"></i> รายการสินค้าปัจจุบัน</h3>
                <div class="product-list">
                    ${this.renderProductList()}
                </div>
            </div>
        </div>`;
    },

    renderProductList() {
        return State.products.map(product => `
            <div class="product-item">
                <img src="${product.image}" alt="${product.name}" width="50">
                <div class="product-info">
                    <h4>${product.name}</h4>
                    <p>${Utils.formatPrice(product.price)}</p>
                </div>
                <div class="product-status">
                    <span class="badge ${product.available ? 'success' : 'error'}">
                        <i class="fas fa-${product.available ? 'check' : 'times'}"></i>
                        ${product.available ? 'พร้อมขาย' : 'ไม่พร้อมขาย'}
                    </span>
                </div>
            </div>
        `).join('');
    }
};