<?php 
include './head.php';
?>
<br><br>
<div class="mdui-card">
  <div class="mdui-card-media">
    <img src="https://api.fuxsto.cn/img.php"/>
  </div>
  <div class="mdui-card-header">
    <img class="mdui-card-header-avatar" src="https://q1.qlogo.cn/g?b=qq&nk=<?=$user?>&s=640"/>
    <div class="mdui-card-header-title">产品中心</div>
    <div class="mdui-card-header-subtitle">选择合适的产品</div>
  </div>
  <div class="mdui-card-content">
    <div class="mdui-ripple-blue mdui-typo">                    
      <div class="mdui-row">
        <div class="mdui-col-xs-12">
          <div id="primary-category-container" class="mdui-row mdui-chip-set rk-jump-in"></div>
        </div>
      </div>
      <div class="mdui-row" id="secondary-category-container" style="margin-top: 5px; display: none;">
        <div class="mdui-col-xs-12">
          <div id="sub-category-container" class="mdui-row mdui-chip-set rk-jump-in"></div>
        </div>
      </div>
    </div>
  </div>                     
</div>
<div class="mdui-row" id="product-container" class="rk-jump-in" style="margin-top: 20px;"></div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    fetch('./get_products.fx')
        .then(response => response.json())
        .then(data => {
            if (data) {
                initializePrimaryCategories(data);
            } else {
                document.getElementById('product-container').innerHTML = '<p>没有找到可用的产品。</p>';
            }
        })
        .catch(error => console.error('Error fetching data:', error));

    function initializePrimaryCategories(products) {
        const primaryCategoryContainer = document.getElementById('primary-category-container');
        const categories = {};

        Object.keys(products).forEach(id => {
            const { fid } = products[id];
            const [primaryName, primaryOrder] = parseCategory(fid);

            if (!categories[primaryOrder]) {
                categories[primaryOrder] = primaryName;
            }
        });

        const sortedPrimaryCategories = Object.keys(categories).sort().reverse();

        sortedPrimaryCategories.forEach(primaryOrder => {
            const primaryCategoryName = categories[primaryOrder];
            const primaryChip = createCategoryChip(primaryCategoryName, 'category');

            primaryChip.addEventListener('click', () => {
                toggleChipSelection(primaryChip, 'category');
                showSecondaryCategories(products, primaryCategoryName);
            });

            primaryCategoryContainer.appendChild(primaryChip);
        });

        if (sortedPrimaryCategories.length > 0) {
            const firstPrimaryCategory = categories[sortedPrimaryCategories[0]];
            showSecondaryCategories(products, firstPrimaryCategory, true);
        }
    }

    function showSecondaryCategories(products, primaryCategoryName, isDefault = false) {
        const secondaryContainer = document.getElementById('secondary-category-container');
        secondaryContainer.style.display = 'block';
        secondaryContainer.classList.add('mdui-fade-in');
        const subCategoryContainer = document.getElementById('sub-category-container');
        subCategoryContainer.innerHTML = '';

        const subCategories = {};

        Object.keys(products).forEach(id => {
            const product = products[id];
            if (product.fid.includes(primaryCategoryName)) {
                const [secondaryName, secondaryOrder] = parseCategory(product.sid);
                subCategories[secondaryOrder] = secondaryName;
            }
        });

        const sortedSecondaryCategories = Object.keys(subCategories).sort().reverse();

        sortedSecondaryCategories.forEach(secondaryOrder => {
            const subCategoryName = subCategories[secondaryOrder];
            const subCategoryChip = createCategoryChip(subCategoryName, 'subcategory');

            subCategoryChip.addEventListener('click', () => {
                toggleChipSelection(subCategoryChip, 'subcategory');
                filterAndDisplayProducts(products, primaryCategoryName, subCategoryName);
            });

            subCategoryContainer.appendChild(subCategoryChip);
        });

        if (isDefault && sortedSecondaryCategories.length > 0) {
            const firstSecondaryCategory = subCategories[sortedSecondaryCategories[0]];
            filterAndDisplayProducts(products, primaryCategoryName, firstSecondaryCategory);
        }
    }

    function createCategoryChip(name, type) {
        const chip = document.createElement('div');
        chip.classList.add('mdui-chip', 'mdui-m-b-2', 'mdui-hoverable');
        const icon = type === 'category' ? 'assistant_photo' : 'subdirectory_arrow_right';
        const color = type === 'category' ? 'mdui-color-blue' : 'mdui-color-blue-300';

        chip.innerHTML = `
            <span class="mdui-chip-icon ${color}">
                <i class="mdui-icon material-icons">${icon}</i>
            </span>
            <span class="mdui-chip-title">${name}</span>
        `;
        
        chip.dataset.type = type;
        return chip;
    }

    function toggleChipSelection(chip, type) {
        document.querySelectorAll(`.mdui-chip[data-type="${type}"]`).forEach(element => {
            element.classList.remove('selected');
            const iconElement = element.querySelector('.mdui-icon');
            iconElement.innerHTML = type === 'category' ? 'assistant_photo' : 'subdirectory_arrow_right';
        });

        chip.classList.add('selected');
        const selectedIcon = chip.querySelector('.mdui-icon');
        selectedIcon.innerHTML = type === 'category' ? 'arrow_drop_down_circle' : 'adjust';
    }

    function parseCategory(category) {
        const match = category.match(/(.+)\[\[(\d+)\]\]/);
        return match ? [match[1], parseInt(match[2], 10)] : [category, 0];
    }

    function filterAndDisplayProducts(products, primaryCategory, secondaryCategory) {
        const filteredProducts = Object.keys(products).reduce((result, id) => {
            const product = products[id];
            const matchesPrimary = !primaryCategory || product.fid.includes(primaryCategory);
            const matchesSecondary = !secondaryCategory || product.sid.includes(secondaryCategory);
            if (matchesPrimary && matchesSecondary) {
                result[id] = product;
            }
            return result;
        }, {});

        parseProducts(filteredProducts);
    }

    function parseProducts(products) {
        const container = document.getElementById('product-container');
        container.classList.add('mdui-fade-in');
        container.innerHTML = '';

        if (Object.keys(products).length === 0) {
            container.innerHTML = '<p>没有找到符合条件的产品。</p>';
            return;
        }

        Object.keys(products).forEach(id => {
            const product = products[id];
            const isSoldOut = product.have <= 0;

            const productHtml = `
                <div style="margin-bottom: 10px" class="mdui-col-xs-12 mdui-col-sm-3 mdui-fade-in">
                    <div class="mdui-card rk-jump-in">
                        <div class="mdui-card-primary mdui-ripple mdui-ripple-blue mdui-typo">
                            <div class="mdui-card-primary-title"><code>${product.name}</code></div>
                            <div class="mdui-card-primary-subtitle"><kbd><i style="font-size:13px" class="mdui-icon material-icons">widgets</i>${product.have}</kbd></div>
                        </div>
                        <div style="padding-top:0px" class="mdui-card-content">
                            <div class="mdui-typo">${product.describe}</div>
                        </div>
                        <div class="mdui-card-actions mdui-typo">
                            <button class="mdui-hoverable mdui-text-color-blue-a200 mdui-btn mdui-ripple mdui-float-right exchange-btn" data-id="${id}" ${isSoldOut ? 'disabled' : ''}>
                                <i class="mdui-icon material-icons">add_circle_outline</i>
                                ${getProductActionText(product, isSoldOut)}
                            </button>
                        </div>
                    </div>
                </div>`;
            container.insertAdjacentHTML('beforeend', productHtml);
        });

        bindExchangeButtonEvents();
    }

    function getProductActionText(product, isSoldOut) {
        if (isSoldOut) return '<code>已售罄</code>';
        if (product.star > 0) return `<kbd>${product.star}</kbd><code>Star</code>`;
        if (product.bi > 0) return `<kbd>${product.bi}</kbd><code>积分</code>`;
        return '<code>免费</code>';
    }

    function bindExchangeButtonEvents() {
        document.querySelectorAll('.exchange-btn').forEach(button => {
            button.addEventListener('click', function() {
                const productId = this.dataset.id;
                showPurchaseConfirmation(productId);
            });
        });
    }

    function showPurchaseConfirmation(productId) {
        mdui.snackbar({
            message: '确认购买该商品吗？',
            position: 'top',
            buttonText: '确认',
            onButtonClick: function() {
                purchaseProduct(productId);
            }
        });
    }

    function purchaseProduct(productId) {
        document.querySelectorAll('.exchange-btn').forEach(button => button.disabled = true);
        rk.tip('Loading...', '<div class="mdui-progress"><div class="mdui-progress-indeterminate"></div></div>', 6000);

        fetch('./then_products.fx', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `id=${encodeURIComponent(productId)}`,
        })
        .then(response => response.text())
        .then(result => {
            rk.tip('Tip', result, 5);
        })
        .catch(error => {
            console.error('Error purchasing product:', error);
            rk.tip('Tip', '购买失败，请稍后重试', 5);
        })
        .finally(() => {
            document.querySelectorAll('.exchange-btn').forEach(button => button.disabled = false);
        });
    }
});
</script>
