<?php
/**
 * 方言字词句考证页面模板
 *
 * @package Chinese-Character-Dictionary
 */

get_header(); ?>

<div class="dialect-research-wrapper">
    <div class="dialect-research-container">
        <!--<div class="dialect-research-header">-->
            <!--<h1>方言字词句考证</h1>-->
            <!--<p>本页面提供对方言中特殊字词句的详细考证和解释</p>-->
        <!--</div>-->
        
        <div class="dialect-research-content">
            <div class="dialect-filter-section">
                <h2>按方言区筛选</h2>
                <div class="dialect-filter-options">
                    <input type="text" id="dialect-search-input" class="dialect-search-box" placeholder="搜索方言条目...">
                    <select id="dialect-group-selector" class="dialect-selector">
                        <option value="">选择方言区</option>
                        <option value="北方方言(官话)">北方方言(官话)</option>
                        <option value="晋语">晋语</option>
                        <option value="吴语">吴语</option>
                        <option value="徽语">徽语</option>
                        <option value="赣语">赣语</option>
                        <option value="湘语">湘语</option>
                        <option value="闽语">闽语</option>
                        <option value="粤语">粤语</option>
                        <option value="平话">平话</option>
                        <option value="客家话">客家话</option>
                    </select>
                    
                    <select id="dialect-subgroup-selector" class="dialect-selector" disabled>
                        <option value="">选择次方言</option>
                    </select>
                    
                    <select id="province-selector" class="dialect-selector">
                        <option value="">选择省份</option>
                        <option value="北京市">北京市</option>
                        <option value="天津市">天津市</option>
                        <option value="河北省">河北省</option>
                        <option value="山西省">山西省</option>
                        <option value="内蒙古自治区">内蒙古自治区</option>
                        <option value="辽宁省">辽宁省</option>
                        <option value="吉林省">吉林省</option>
                        <option value="黑龙江省">黑龙江省</option>
                        <option value="上海市">上海市</option>
                        <option value="江苏省">江苏省</option>
                        <option value="浙江省">浙江省</option>
                        <option value="安徽省">安徽省</option>
                        <option value="福建省">福建省</option>
                        <option value="江西省">江西省</option>
                        <option value="山东省">山东省</option>
                        <option value="河南省">河南省</option>
                        <option value="湖北省">湖北省</option>
                        <option value="湖南省">湖南省</option>
                        <option value="广东省">广东省</option>
                        <option value="广西壮族自治区">广西壮族自治区</option>
                        <option value="海南省">海南省</option>
                        <option value="重庆市">重庆市</option>
                        <option value="四川省">四川省</option>
                        <option value="贵州省">贵州省</option>
                        <option value="云南省">云南省</option>
                        <option value="西藏自治区">西藏自治区</option>
                        <option value="陕西省">陕西省</option>
                        <option value="甘肃省">甘肃省</option>
                        <option value="青海省">青海省</option>
                        <option value="宁夏回族自治区">宁夏回族自治区</option>
                        <option value="新疆维吾尔自治区">新疆维吾尔自治区</option>
                        <option value="台湾省">台湾省</option>
                        <option value="香港特别行政区">香港特别行政区</option>
                        <option value="澳门特别行政区">澳门特别行政区</option>
                    </select>
                </div>
            </div>
            
            <div class="dialect-entries-section">
                <h2>方言条目</h2>
                <div class="dialect-entries-list">
                    <div class="dialect-entry-placeholder">
                        <p>正在加载所有方言条目...</p>
                    </div>
                </div>
            </div>
            
            <div class="dialect-entry-detail-section" style="display: none;">
                <h2>条目详情</h2>
                <div class="dialect-entry-detail-content">
                    <!-- 详细内容将通过 AJAX 加载 -->
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.dialect-research-wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

.dialect-research-header {
    text-align: center;
    margin-bottom: 30px;
}

.dialect-research-header h1 {
    font-size: 2.5em;
    margin-bottom: 10px;
    color: #333;
}

.dialect-research-header p {
    font-size: 1.2em;
    color: #666;
}

.dialect-filter-section {
    background: #f9f9f9;
    padding: 20px;
    border-radius: 5px;
    margin-bottom: 30px;
}

.dialect-filter-section h2 {
    margin-top: 0;
}

.dialect-filter-options {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
}

.dialect-selector {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 1em;
    min-width: 150px;
}

.dialect-search-box {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 1em;
    min-width: 200px;
}

.dialect-entries-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    margin-top: 20px;
}

.dialect-entry-card {
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 15px;
    cursor: pointer;
    transition: box-shadow 0.3s ease;
    background: #fff;
}

.dialect-entry-card:hover {
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.entry-character {
    font-size: 2em;
    font-weight: bold;
    text-align: center;
    margin-bottom: 10px;
    color: #333;
}

.dialect-entry-card h3 {
    margin: 10px 0;
    color: #555;
    font-size: 1.1em;
}

.dialect-entry-card p {
    color: #666;
    margin: 10px 0;
    min-height: 40px;
}

.entry-dialect {
    display: inline-block;
    background: #e0f7fa;
    padding: 4px 8px;
    border-radius: 3px;
    font-size: 0.85em;
    color: #006064;
}

.dialect-entry-placeholder {
    grid-column: 1 / -1;
    text-align: center;
    padding: 40px;
    color: #888;
}

.dialect-entry-detail-section {
    margin-top: 30px;
    padding: 20px;
    background: #f9f9f9;
    border-radius: 5px;
}

.entry-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ddd;
}

.entry-header .entry-character {
    font-size: 3em;
    margin-right: 20px;
    margin-bottom: 0;
}

.entry-pronunciation {
    font-size: 1.5em;
    color: #555;
    margin-right: 20px;
}

.entry-definition {
    margin: 15px 0;
    line-height: 1.6;
}

.entry-etymology {
    margin: 15px 0;
    line-height: 1.6;
    background: #fff;
    padding: 15px;
    border-radius: 5px;
}

.entry-examples {
    margin: 15px 0;
}

.entry-examples h4 {
    margin-top: 0;
}

.example-item {
    margin: 10px 0;
    padding: 10px;
    background: #fff;
    border-left: 3px solid #00acc1;
}

.loading-message {
    text-align: center;
    padding: 20px;
    color: #888;
}

@media (max-width: 768px) {
    .dialect-filter-options {
        flex-direction: column;
    }
    
    .dialect-selector {
        min-width: 100%;
    }
    
    .dialect-entries-list {
        grid-template-columns: repeat(auto-fill, minmax(100%, 1fr));
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const dialectSearchInput = document.getElementById('dialect-search-input');
    const dialectGroupSelector = document.getElementById('dialect-group-selector');
    const dialectSubgroupSelector = document.getElementById('dialect-subgroup-selector');
    const provinceSelector = document.getElementById('province-selector');
    const dialectEntriesList = document.querySelector('.dialect-entries-list');
    
    // 定义中国主要方言区及代表城市
    const chineseDialects = {
        '北方方言(官话)': {
            '北京话': '北京',
            '东北话': '东北',
            '冀鲁官话': '河北/山东',
            '胶辽官话': '山东/辽宁',
            '中原官话': '河南/陕西/山西/甘肃',
            '兰银官话': '甘肃/宁夏/青海/新疆',
            '江淮官话': '江苏/安徽',
            '西南官话': '四川/重庆/云南/贵州/广西/湖北'
        },
        '晋语': {
            '并州片': '山西太原',
            '吕梁片': '山西吕梁',
            '上党片': '山西长治',
            '五台片': '山西忻州',
            '邯新片': '河北邯郸/河南新乡',
            '大包片': '内蒙古包头/山西大同'
        },
        '吴语': {
            '太湖片': '上海/江苏苏州/浙江杭州',
            '台州片': '浙江台州',
            '瓯江片': '浙江温州',
            '婺州片': '浙江金华',
            '处衢片': '浙江衢州/丽水',
            '宣州片': '安徽宣城'
        },
        '徽语': {
            '绩歙片': '安徽绩溪/歙县',
            '休黟片': '安徽休宁/黟县',
            '祁婺片': '安徽祁门/江西婺源',
            '旌占片': '安徽旌德/黟县',
            '严州片': '浙江建德'
        },
        '赣语': {
            '昌都片': '江西南昌',
            '鹰弋片': '江西鹰潭/弋阳',
            '大通片': '江西九江/湖北',
            '甬江片': '江西鹰潭/浙江宁波',
            '洞绥片': '湖南洞口/绥宁',
            '宜浏片': '江西宜春/湖南浏阳',
            '吉茶片': '江西吉安/湖南茶陵'
        },
        '湘语': {
            '长益片': '湖南长沙/益阳',
            '娄邵片': '湖南娄底/邵阳',
            '辰溆片': '湖南怀化/溆浦',
            '衡州片': '湖南衡阳',
            '永州片': '湖南永州'
        },
        '闽语': {
            '闽南语': '福建厦门/泉州/漳州',
            '闽东语': '福建福州',
            '闽北语': '福建南平',
            '闽中语': '福建三明',
            '莆仙语': '福建莆田',
            '海南话': '海南',
            '雷州话': '广东雷州'
        },
        '粤语': {
            '广府话': '广东广州',
            '四邑话': '广东江门',
            '高阳话': '广东阳江',
            '吴化话': '广东湛江',
            '邕浔粤语': '广西南宁/柳州',
            '勾漏粤语': '广西玉林/贵港',
            '四色话': '广西贺州'
        },
        '客家话': {
            '粤台片': '广东梅州',
            '海陆片': '广东汕尾/台湾',
            '客家话': '福建长汀/江西',
            '宁龙片': '江西赣州/福建',
            '于桂片': '江西于都/广西'
        },
        '平话': {
            '桂北平话': '广西桂林',
            '桂南平话': '广西南宁'
        }
    };
    
    // 页面加载时默认加载所有方言条目
    loadAllDialectEntries();
    
    // 搜索框输入事件
    dialectSearchInput.addEventListener('input', function() {
        const searchTerm = this.value.trim();
        const selectedGroup = dialectGroupSelector.value;
        const selectedSubgroup = dialectSubgroupSelector.value;
        const selectedProvince = provinceSelector.value;
        
        // 清空其他筛选器的选择
        if (searchTerm) {
            const filters = {};
            
            if (selectedGroup) {
                filters.dialect_region = selectedGroup;
            }
            
            if (selectedSubgroup) {
                filters.dialect_city = selectedSubgroup;
            }
            
            if (selectedProvince) {
                filters.province = selectedProvince;
            }
            
            filters.search = searchTerm;
            loadDialectEntries(filters);
        } else {
            // 如果搜索框为空，根据其他筛选条件加载
            handleFilterChange();
        }
    });
    
    // 方言区选择事件
    dialectGroupSelector.addEventListener('change', function() {
        const selectedGroup = this.value;
        
        // 清空并重置次方言选择器
        dialectSubgroupSelector.innerHTML = '<option value="">选择次方言</option>';
        dialectSubgroupSelector.disabled = true;
        
        if (selectedGroup && chineseDialects[selectedGroup]) {
            dialectSubgroupSelector.disabled = false;
            for (const subgroup in chineseDialects[selectedGroup]) {
                const option = document.createElement('option');
                option.value = subgroup;
                option.textContent = subgroup;
                dialectSubgroupSelector.appendChild(option);
            }
        }
        
        // 处理筛选变更
        handleFilterChange();
    });
    
    // 次方言选择事件
    dialectSubgroupSelector.addEventListener('change', function() {
        // 处理筛选变更
        handleFilterChange();
    });
    
    // 省份选择事件
    provinceSelector.addEventListener('change', function() {
        // 处理筛选变更
        handleFilterChange();
    });
    
    // 统一处理筛选变更
    function handleFilterChange() {
        const searchTerm = dialectSearchInput.value.trim();
        const selectedGroup = dialectGroupSelector.value;
        const selectedSubgroup = dialectSubgroupSelector.value;
        const selectedProvince = provinceSelector.value;
        
        const filters = {};
        
        if (selectedGroup) {
            filters.dialect_region = selectedGroup;
        }
        
        if (selectedSubgroup && selectedGroup) {
            filters.dialect_city = selectedSubgroup;
        }
        
        if (selectedProvince) {
            filters.province = selectedProvince;
        }
        
        if (searchTerm) {
            filters.search = searchTerm;
        }
        
        if (Object.keys(filters).length > 0) {
            loadDialectEntries(filters);
        } else {
            loadAllDialectEntries();
        }
    }
    
    // 加载所有方言条目
    function loadAllDialectEntries() {
        dialectEntriesList.innerHTML = '<div class="loading-message"><p>正在加载所有方言条目...</p></div>';
        
        // 使用 AJAX 从 WordPress 后端获取所有方言条目
        const xhr = new XMLHttpRequest();
        const params = new URLSearchParams();
        
        params.append('action', 'get_dialect_entries');
        
        xhr.open('POST', '<?php echo admin_url('admin-ajax.php'); ?>', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        displayDialectEntries(response.data);
                    } else {
                        dialectEntriesList.innerHTML = '<div class="dialect-entry-placeholder"><p>加载失败: ' + response.data + '</p></div>';
                    }
                } catch (e) {
                    dialectEntriesList.innerHTML = '<div class="dialect-entry-placeholder"><p>数据解析错误</p></div>';
                }
            } else {
                dialectEntriesList.innerHTML = '<div class="dialect-entry-placeholder"><p>请求失败，请稍后重试</p></div>';
            }
        };
        xhr.send(params.toString());
    }
    
    // 加载方言条目
    function loadDialectEntries(filters) {
        dialectEntriesList.innerHTML = '<div class="loading-message"><p>正在加载条目...</p></div>';
        
        // 使用 AJAX 从 WordPress 后端获取真实数据
        const xhr = new XMLHttpRequest();
        const params = new URLSearchParams();
        
        params.append('action', 'get_dialect_entries');
        for (const key in filters) {
            params.append(key, filters[key]);
        }
        
        xhr.open('POST', '<?php echo admin_url('admin-ajax.php'); ?>', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        displayDialectEntries(response.data);
                    } else {
                        dialectEntriesList.innerHTML = '<div class="dialect-entry-placeholder"><p>加载失败: ' + response.data + '</p></div>';
                    }
                } catch (e) {
                    dialectEntriesList.innerHTML = '<div class="dialect-entry-placeholder"><p>数据解析错误</p></div>';
                }
            } else {
                dialectEntriesList.innerHTML = '<div class="dialect-entry-placeholder"><p>请求失败，请稍后重试</p></div>';
            }
        };
        xhr.send(params.toString());
    }

    // 显示方言条目
    function displayDialectEntries(entries) {
        if (entries.length === 0) {
            dialectEntriesList.innerHTML = '<div class="dialect-entry-placeholder"><p>该筛选条件下暂无条目</p></div>';
            return;
        }
        
        let entriesHTML = '';
        entries.forEach(entry => {
            entriesHTML += `
                <div class="dialect-entry-card" data-entry-id="${entry.id}" data-post-id="${entry.post_id}">
                    <div class="entry-character">${entry.character}</div>
                    <h3>${entry.pronunciation || '无发音'}</h3>
                    <p>${entry.definition || '无释义'}</p>
                    <span class="entry-dialect">${entry.location}</span>
                </div>
            `;
        });
        
        dialectEntriesList.innerHTML = entriesHTML;
        
        // 为每个条目添加点击事件
        document.querySelectorAll('.dialect-entry-card').forEach(card => {
            card.addEventListener('click', function() {
                const entryId = this.getAttribute('data-entry-id');
                const postId = this.getAttribute('data-post-id');
                showEntryDetail(postId);
            });
        });
    }
    
    // 显示条目详情
    function showEntryDetail(postId) {
        const detailSection = document.querySelector('.dialect-entry-detail-section');
        const detailContent = document.querySelector('.dialect-entry-detail-content');
        
        detailContent.innerHTML = '<div class="loading-message"><p>正在加载详情...</p></div>';
        detailSection.style.display = 'block';
        detailSection.scrollIntoView({ behavior: 'smooth' });
        
        // 使用 AJAX 获取条目详情
        const xhr = new XMLHttpRequest();
        const params = new URLSearchParams();
        params.append('action', 'get_dialect_entry_detail');
        params.append('post_id', postId);
        
        xhr.open('POST', '<?php echo admin_url('admin-ajax.php'); ?>', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.success) {
                        const entry = response.data;
                        detailContent.innerHTML = `
                            <div class="entry-header">
                                <div class="entry-character">${entry.character}</div>
                                <div class="entry-pronunciation">${entry.pronunciation || '无发音'}</div>
                                <div class="entry-dialect">${entry.location}</div>
                            </div>
                            <div class="entry-definition">
                                <strong>释义：</strong>${entry.definition || '无释义'}
                            </div>
                            <div class="entry-etymology">
                                <strong>考据：</strong>${entry.research || '无考据信息'}
                            </div>
                            <div class="entry-examples">
                                <h4>用例：</h4>
                                ${entry.examples && entry.examples.length > 0 
                                    ? entry.examples.map(example => `<div class="example-item">${example}</div>`).join('')
                                    : '<p>无用例信息</p>'
                                }
                            </div>
                        `;
                    } else {
                        detailContent.innerHTML = '<p>加载详情失败: ' + response.data + '</p>';
                    }
                } catch (e) {
                    detailContent.innerHTML = '<p>数据解析错误</p>';
                }
            } else {
                detailContent.innerHTML = '<p>请求失败，请稍后重试</p>';
            }
        };
        xhr.send(params.toString());
    }
});
</script>

<?php get_footer(); ?>