<?php
/**
 * 单个藏品页面模板
 */

get_header();

// 获取当前藏品信息
$collection = get_post();
$dynasty = get_post_meta($collection->ID, '_collection_dynasty', true);
$category = get_post_meta($collection->ID, '_collection_category', true);
$material = get_post_meta($collection->ID, '_collection_material', true);
$dimensions = get_post_meta($collection->ID, '_collection_dimensions', true);
$acquisition_date = get_post_meta($collection->ID, '_collection_acquisition_date', true);
$collection_type = get_post_meta($collection->ID, '_collection_type', true); // 添加类别信息
$description = get_post_meta($collection->ID, '_collection_description', true); // 添加介绍文字

// 获取关联的博物馆
$related_museum_id = get_post_meta($collection->ID, '_collection_related_museum', true);
$related_museum = null;
if ($related_museum_id) {
    $related_museum = get_post($related_museum_id);
}

// 获取所有图片附件
$attachments = get_posts(array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'post_parent' => $collection->ID,
    'orderby' => 'menu_order',
    'order' => 'ASC'
));

// 提取内容中的图片
function extract_images_from_content($content) {
    $images = array();
    preg_match_all('/<img[^>]+src="([^">]+)"[^>]*>/i', $content, $matches);
    if (!empty($matches[1])) {
        foreach ($matches[1] as $src) {
            // 获取完整尺寸图片URL
            $full_src = preg_replace('/-(\d+x\d+)(\.[^.]+)$/', '$2', $src);
            $images[] = array(
                'src' => $src,
                'full_src' => $full_src
            );
        }
    }
    return $images;
}

$content_images = extract_images_from_content($collection->post_content);
?>

<div class="collection-container">
    <div class="collection-header">
        <h1 class="collection-title"><?php the_title(); ?></h1>
        
        <div class="collection-meta">
            <?php if ($collection_type): ?>
                <div class="collection-type">
                    <strong>类别：</strong><?php echo esc_html($collection_type); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($dynasty): ?>
                <div class="collection-dynasty">
                    <strong>朝代：</strong><?php echo esc_html($dynasty); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($category): ?>
                <div class="collection-category">
                    <strong>分类：</strong><?php echo esc_html($category); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($material): ?>
                <div class="collection-material">
                    <strong>材质：</strong><?php echo esc_html($material); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($dimensions): ?>
                <div class="collection-dimensions">
                    <strong>尺寸：</strong><?php echo esc_html($dimensions); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($acquisition_date): ?>
                <div class="collection-acquisition-date">
                    <strong>入藏日期：</strong><?php echo esc_html(date('Y年m月d日', strtotime($acquisition_date))); ?>
                </div>
            <?php endif; ?>
            
            <?php if ($related_museum): ?>
                <div class="collection-museum">
                    <strong>所属博物馆：</strong>
                    <a href="<?php echo get_permalink($related_museum->ID); ?>">
                        <?php echo esc_html($related_museum->post_title); ?>
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="collection-content">
        <?php if (!empty($attachments)): ?>
            <div class="collection-gallery">
                <div class="collection-main-image">
                    <?php echo wp_get_attachment_image($attachments[0]->ID, 'large'); ?>
                </div>
                <?php if (count($attachments) > 1): ?>
                    <div class="collection-thumbnails">
                        <?php foreach ($attachments as $index => $attachment): ?>
                            <div class="collection-thumbnail-item <?php echo $index === 0 ? 'active' : ''; ?>" data-index="<?php echo $index; ?>">
                                <?php echo wp_get_attachment_image($attachment->ID, 'thumbnail'); ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                <?php if (!empty($description)): ?>
                    <div class="collection-introduction">
                        <?php echo wpautop(wp_kses_post($description)); ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php elseif (has_post_thumbnail()): ?>
            <div class="collection-thumbnail">
                <?php the_post_thumbnail('large'); ?>
                <?php if (!empty($description)): ?>
                    <div class="collection-introduction">
                        <?php echo wpautop(wp_kses_post($description)); ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
        
        <div class="collection-description">
            <?php 
            // 处理内容中的图片，添加幻灯片功能
            $content = $collection->post_content;
            $content = preg_replace('/<img([^>]+src="([^">]+)"[^>]*)>/i', '<div class="content-image-wrapper"><img$1 data-full-src="$2"></div>', $content);
            echo apply_filters('the_content', $content);
            ?>
        </div>
    </div>
</div>

<!-- 图片查看器模态框 -->
<div id="collection-image-viewer" class="collection-image-viewer">
    <span class="collection-image-viewer-close">&times;</span>
    <button class="collection-image-viewer-zoom">放大</button>
    <button class="collection-image-viewer-reset">重置</button>
    <div class="collection-image-viewer-content">
        <div class="collection-image-viewer-main">
            <!-- 图片将通过JavaScript动态加载 -->
        </div>
        <button class="collection-image-viewer-prev">&#10094;</button>
        <button class="collection-image-viewer-next">&#10095;</button>
        <div class="collection-image-viewer-counter">
            <span class="current">1</span> / <span class="total">0</span>
        </div>
    </div>
    <div class="collection-image-viewer-thumbs">
        <!-- 缩略图将通过JavaScript动态加载 -->
    </div>
</div>

<style>
.collection-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.collection-header {
    text-align: center;
    margin-bottom: 30px;
    border-bottom: 1px solid #eee;
    padding-bottom: 20px;
}

.collection-title {
    margin: 0 0 20px;
    font-size: 2.5em;
    color: #333;
}

.collection-meta {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    gap: 20px;
    margin-bottom: 20px;
}

.collection-meta > div {
    background: #f9f9f9;
    padding: 10px 15px;
    border-radius: 5px;
    font-size: 0.9em;
}

.collection-content {
    display: flex;
    gap: 30px;
    margin-bottom: 40px;
}

.collection-gallery {
    flex: 1;
    min-width: 300px;
}

.collection-main-image {
    margin-bottom: 15px;
    cursor: pointer;
}

.collection-main-image img {
    width: 100%;
    height: auto;
    display: block;
}

.collection-thumbnails {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.collection-thumbnail-item {
    width: 80px;
    height: 80px;
    cursor: pointer;
    border: 2px solid transparent;
    overflow: hidden;
}

.collection-thumbnail-item.active {
    border-color: #0073aa;
}

.collection-thumbnail-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.collection-thumbnail {
    flex: 1;
    min-width: 300px;
}

.collection-thumbnail img {
    max-width: 100%;
    height: auto;
    border-radius: 5px;
    cursor: pointer;
}

.collection-introduction {
    margin-top: 20px;
    padding: 15px;
    background-color: #f9f9f9;
    /*border-left: 4px solid #0073aa;*/
    border-left: 0px solid #0073aa;
    font-style: italic;
}

.collection-description {
    flex: 2;
    font-size: 1.1em;
    line-height: 1.6;
}

/* 内容中的图片样式 */
.content-image-wrapper {
    display: inline-block;
    cursor: pointer;
    margin: 10px 0;
}

.content-image-wrapper img {
    max-width: 100%;
    height: auto;
    display: block;
    border-radius: 5px;
}

/* 图片查看器样式 */
.collection-image-viewer {
    display: none;
    position: fixed;
    z-index: 10000;
    padding: 20px;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.9);
}

.collection-image-viewer-content {
    position: relative;
    margin: auto;
    width: 90%;
    height: 80%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.collection-image-viewer-main {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
}

.collection-image-viewer-main img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    cursor: zoom-in;
    transition: transform 0.3s ease;
    transform-origin: center center;
    user-select: none;
    -webkit-user-drag: none;
}

.collection-image-viewer-main.img-dragging {
    cursor: grabbing;
}

.collection-image-viewer-close {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #f1f1f1;
    font-size: 40px;
    font-weight: bold;
    cursor: pointer;
    z-index: 10001;
}

.collection-image-viewer-close:hover {
    color: #bbb;
}

.collection-image-viewer-zoom {
    position: absolute;
    top: 15px;
    right: 100px;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border: none;
    padding: 10px 15px;
    font-size: 16px;
    cursor: pointer;
    border-radius: 3px;
    z-index: 10001;
    user-select: none;
}

.collection-image-viewer-zoom:hover {
    background-color: rgba(0, 0, 0, 0.7);
}

.collection-image-viewer-reset {
    position: absolute;
    top: 15px;
    right: 180px;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border: none;
    padding: 10px 15px;
    font-size: 16px;
    cursor: pointer;
    border-radius: 3px;
    z-index: 10001;
    user-select: none;
}

.collection-image-viewer-reset:hover {
    background-color: rgba(0, 0, 0, 0.7);
}

.collection-image-viewer-prev,
.collection-image-viewer-next {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border: none;
    padding: 16px;
    font-size: 18px;
    cursor: pointer;
    border-radius: 0 3px 3px 0;
    z-index: 10001;
}

.collection-image-viewer-prev {
    left: 10px;
    border-radius: 3px 0 0 3px;
}

.collection-image-viewer-next {
    right: 10px;
    border-radius: 0 3px 3px 0;
}

.collection-image-viewer-counter {
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    color: white;
    background-color: rgba(0, 0, 0, 0.5);
    padding: 5px 10px;
    border-radius: 3px;
    font-size: 14px;
}

.collection-image-viewer-thumbs {
    position: absolute;
    bottom: 50px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    gap: 10px;
    max-width: 80%;
    overflow-x: auto;
    padding: 10px;
}

.collection-image-viewer-thumb {
    width: 60px;
    height: 60px;
    object-fit: cover;
    cursor: pointer;
    border: 2px solid transparent;
    opacity: 0.7;
    transition: all 0.3s ease;
}

.collection-image-viewer-thumb:hover,
.collection-image-viewer-thumb.active {
    opacity: 1;
    border-color: #fff;
}

@media (max-width: 768px) {
    .collection-meta {
        flex-direction: column;
        align-items: center;
        gap: 10px;
    }
    
    .collection-content {
        flex-direction: column;
    }
    
    .collection-gallery,
    .collection-thumbnail {
        min-width: auto;
    }
    
    .collection-image-viewer-content {
        height: 90%;
    }
    
    .collection-image-viewer-thumbs {
        max-width: 90%;
        bottom: 10px;
    }
    
    .collection-image-viewer-thumb {
        width: 40px;
        height: 40px;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 获取元素
    const modal = document.getElementById('collection-image-viewer');
    const mainImage = document.querySelector('.collection-main-image');
    const thumbnails = document.querySelectorAll('.collection-thumbnail-item');
    const modalMain = document.querySelector('.collection-image-viewer-main');
    const modalThumbs = document.querySelectorAll('.collection-image-viewer-thumb');
    const prevBtn = document.querySelector('.collection-image-viewer-prev');
    const nextBtn = document.querySelector('.collection-image-viewer-next');
    const closeBtn = document.querySelector('.collection-image-viewer-close');
    const currentSpan = document.querySelector('.collection-image-viewer-counter .current');
    const totalSpan = document.querySelector('.collection-image-viewer-counter .total');
    const collectionThumbnail = document.querySelector('.collection-thumbnail');
    const contentImages = document.querySelectorAll('.content-image-wrapper img');
    
    // 图片数据
    const attachmentImages = <?php echo json_encode(array_map(function($attachment) {
        return array(
            'id' => $attachment->ID,
            'url' => wp_get_attachment_image_url($attachment->ID, 'large'),
            'thumbnail' => wp_get_attachment_image_url($attachment->ID, 'thumbnail')
        );
    }, $attachments)); ?>;
    
    // 内容图片数据
    const contentImageData = <?php echo json_encode($content_images); ?>;
    
    // 合并所有图片
    let allImages = [];
    attachmentImages.forEach(img => {
        allImages.push({
            url: img.url,
            thumbnail: img.thumbnail
        });
    });
    
    contentImageData.forEach(img => {
        allImages.push({
            url: img.full_src,
            thumbnail: img.src
        });
    });
    
    let currentIndex = 0;
    
    // 图片缩放相关变量
    let scale = 1;
    let currentImageElement = null;
    
    // 图片拖动相关变量
    let isDragging = false;
    let startX, startY;
    let imgStartX, imgStartY;
    let currentX = 0;
    let currentY = 0;
    let translateX = 0;
    let translateY = 0;
    
    // 打开模态框
    function openModal(index) {
        currentIndex = index;
        scale = 1; // 重置缩放
        translateX = 0;
        translateY = 0;
        updateModal();
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden'; // 防止背景滚动
    }
    
    // 关闭模态框
    function closeModal() {
        modal.style.display = 'none';
        document.body.style.overflow = 'auto'; // 恢复背景滚动
        scale = 1; // 重置缩放
        isDragging = false;
        translateX = 0;
        translateY = 0;
        currentX = 0;
        currentY = 0;
    }
    
    // 更新模态框内容
    function updateModal() {
        if (allImages.length > 0 && modalMain) {
            const transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
            modalMain.innerHTML = '<img src="' + allImages[currentIndex].url + '" alt="藏品图片" style="transform: ' + transform + '; transform-origin: center center;">';
            currentImageElement = modalMain.querySelector('img');
            
            // 为图片添加拖动事件监听器
            if (currentImageElement) {
                currentImageElement.addEventListener('mousedown', startDrag);
                currentImageElement.addEventListener('mousemove', drag);
                currentImageElement.addEventListener('mouseup', endDrag);
                currentImageElement.addEventListener('mouseleave', endDrag);
            }
            
            if (currentSpan) {
                currentSpan.textContent = currentIndex + 1;
            }
            
            if (totalSpan) {
                totalSpan.textContent = allImages.length;
            }
            
            // 更新缩略图
            updateThumbnails();
        }
    }
    
    // 开始拖动
    function startDrag(e) {
        if (scale <= 1) return; // 只有在放大时才能拖动
        
        isDragging = true;
        startX = e.clientX;
        startY = e.clientY;
        imgStartX = translateX;
        imgStartY = translateY;
        
        currentImageElement.style.cursor = 'grabbing';
        currentImageElement.classList.add('img-dragging');
        e.preventDefault();
    }
    
    // 拖动中
    function drag(e) {
        if (!isDragging || scale <= 1) return;
        
        const dx = e.clientX - startX;
        const dy = e.clientY - startY;
        
        translateX = imgStartX + dx;
        translateY = imgStartY + dy;
        
        const transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
        currentImageElement.style.transform = transform;
        e.preventDefault();
    }
    
    // 结束拖动
    function endDrag(e) {
        if (isDragging) {
            isDragging = false;
            currentImageElement.style.cursor = scale > 1 ? 'grab' : 'zoom-in';
            currentImageElement.classList.remove('img-dragging');
            e.preventDefault();
        }
    }
    
    // 放大图片
    function zoomIn() {
        if (scale < 3) { // 限制最大放大3倍
            scale += 0.2;
            updateImageScale();
            
            // 更新光标样式
            if (currentImageElement) {
                currentImageElement.style.cursor = scale > 1 ? (isDragging ? 'grabbing' : 'grab') : 'zoom-in';
            }
        }
    }
    
    // 缩小图片
    function zoomOut() {
        if (scale > 0.2) { // 限制最小缩小到0.2倍
            scale -= 0.2;
            
            // 如果缩放到1或以下，重置位置
            if (scale <= 1) {
                translateX = 0;
                translateY = 0;
            }
            
            updateImageScale();
            
            // 更新光标样式
            if (currentImageElement) {
                currentImageElement.style.cursor = scale > 1 ? (isDragging ? 'grabbing' : 'grab') : 'zoom-in';
            }
        }
    }
    
    // 重置图片缩放
    function resetZoom() {
        scale = 1;
        translateX = 0;
        translateY = 0;
        updateImageScale();
        
        // 重置光标样式
        if (currentImageElement) {
            currentImageElement.style.cursor = 'zoom-in';
        }
    }
    
    // 更新图片缩放
    function updateImageScale() {
        if (currentImageElement) {
            const transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
            currentImageElement.style.transform = transform;
        }
    }
    
    // 更新缩略图
    function updateThumbnails() {
        if (modal && allImages.length > 0) {
            const thumbsContainer = document.querySelector('.collection-image-viewer-thumbs');
            if (thumbsContainer) {
                thumbsContainer.innerHTML = '';
                allImages.forEach((img, index) => {
                    const thumb = document.createElement('div');
                    thumb.className = 'collection-image-viewer-thumb' + (index === currentIndex ? ' active' : '');
                    thumb.innerHTML = '<img src="' + img.thumbnail + '" alt="缩略图">';
                    thumb.addEventListener('click', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        currentIndex = index;
                        updateModal();
                    });
                    thumbsContainer.appendChild(thumb);
                });
            }
        }
    }
    
    // 切换到下一张图片
    function nextImage(e) {
        if (e) e.preventDefault();
        currentIndex = (currentIndex + 1) % allImages.length;
        updateModal();
    }
    
    // 切换到上一张图片
    function prevImage(e) {
        if (e) e.preventDefault();
        currentIndex = (currentIndex - 1 + allImages.length) % allImages.length;
        updateModal();
    }
    
    // 事件监听
    if (mainImage) {
        mainImage.addEventListener('click', function(e) {
            e.preventDefault();
            openModal(0);
        });
    }
    
    if (collectionThumbnail) {
        collectionThumbnail.addEventListener('click', function(e) {
            e.preventDefault();
            openModal(0);
        });
    }
    
    if (thumbnails && thumbnails.length > 0) {
        thumbnails.forEach((thumb, index) => {
            thumb.addEventListener('click', function(e) {
                e.preventDefault();
                currentIndex = index;
                updateModal();
                
                // 更新缩略图选中状态
                thumbnails.forEach(t => t.classList.remove('active'));
                this.classList.add('active');
            });
        });
    }
    
    // 内容图片点击事件
    if (contentImages && contentImages.length > 0) {
        contentImages.forEach((img, index) => {
            const wrapper = img.closest('.content-image-wrapper');
            if (wrapper) {
                wrapper.addEventListener('click', function(e) {
                    e.preventDefault();
                    // 计算在所有图片中的索引位置
                    const contentImageIndex = attachmentImages.length + index;
                    openModal(contentImageIndex);
                });
            }
        });
    }
    
    if (modal) {
        if (closeBtn) {
            closeBtn.addEventListener('click', function(e) {
                e.preventDefault();
                closeModal();
            });
        }
        
        // 添加放大按钮事件监听
        const zoomBtn = document.querySelector('.collection-image-viewer-zoom');
        if (zoomBtn) {
            zoomBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                zoomIn();
            });
        }
        
        // 添加重置按钮事件监听
        const resetBtn = document.querySelector('.collection-image-viewer-reset');
        if (resetBtn) {
            resetBtn.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                resetZoom();
            });
        }
        
        if (prevBtn) {
            prevBtn.addEventListener('click', function(e) {
                e.preventDefault();
                prevImage(e);
            });
        }
        
        if (nextBtn) {
            nextBtn.addEventListener('click', function(e) {
                e.preventDefault();
                nextImage(e);
            });
        }
        
        // 点击模态框背景关闭
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                closeModal();
            }
        });
        
        // 键盘事件
        document.addEventListener('keydown', function(e) {
            if (modal && modal.style.display === 'block') {
                if (e.key === 'Escape') {
                    closeModal();
                } else if (e.key === 'ArrowLeft') {
                    prevImage(e);
                } else if (e.key === 'ArrowRight') {
                    nextImage(e);
                } else if (e.key === '+' || e.key === '=') {
                    zoomIn();
                } else if (e.key === '-') {
                    zoomOut();
                } else if (e.key === '0') {
                    resetZoom();
                }
            }
        });
        
        // 鼠标滚轮缩放
        if (modalMain) {
            modalMain.addEventListener('wheel', function(e) {
                e.preventDefault();
                if (e.deltaY < 0) {
                    zoomIn();
                } else {
                    zoomOut();
                }
            });
        }
    }
});
</script>

<?php
get_footer();