<?php
/**
 * Plugin Name: 汉字字典
 * Description: 一个汉字字典 WordPress 插件，提供汉字的详细解释和多维度信息。
 * Version: 1.0.0
 * Plugin URI: http://wuchai.net/plugins/
 * Author: 吾侪主题&易西
 * Author URI: http://wuchai.net/
 * Text Domain: chinese-character-dictionary
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 加载自定义分类元框
require_once plugin_dir_path( __FILE__ ) . 'includes/custom-category-meta-box.php';

// 加载增强评论功能
require_once plugin_dir_path( __FILE__ ) . 'includes/enhanced-comments.php';

// 加载子分类筛选功能
require_once plugin_dir_path( __FILE__ ) . 'includes/subcategory-filter.php';

// 加载默认汉字数据
require_once plugin_dir_path( __FILE__ ) . 'includes/default-characters.php';

// 加载古文字章节功能
require_once plugin_dir_path( __FILE__ ) . 'includes/ancient-text-chapters.php';

// 加载发音含义对功能
require_once plugin_dir_path( __FILE__ ) . 'includes/pronunciation-meaning-pairs.php';

// 加载古文字管理页面
require_once plugin_dir_path( __FILE__ ) . 'includes/ancient-text-admin-page.php';

// 加载搜索短代码功能
require_once plugin_dir_path( __FILE__ ) . 'includes/search-shortcode.php';

class ChineseCharacterDictionary {
    // 预定义的拼音列表，按字母顺序排列
    private $pinyin_list = array(
        // A
        'a', 'ā', 'á', 'ǎ', 'à',
        'ai', 'āi', 'ái', 'ǎi', 'ài',
        'an', 'ān', 'án', 'ǎn', 'àn',
        'ang', 'āng', 'áng', 'ǎng', 'àng',
        'ao', 'āo', 'áo', 'ǎo', 'ào',
        
        // B
        'ba', 'bā', 'bá', 'bǎ', 'bà',
        'bo', 'bō', 'bó', 'bǒ', 'bò',
        'bai', 'bāi', 'bái', 'bǎi', 'bài',
        'bei', 'bēi', 'béi', 'běi', 'bèi',
        'bao', 'bāo', 'báo', 'bǎo', 'bào',
        'ban', 'bān', 'bán', 'bǎn', 'bàn',
        'ben', 'bēn', 'bén', 'běn', 'bèn',
        'bang', 'bāng', 'báng', 'bǎng', 'bàng',
        'beng', 'bēng', 'béng', 'běng', 'bèng',
        'bi', 'bī', 'bí', 'bǐ', 'bì',
        'bie', 'biē', 'bié', 'biě', 'biè',
        'biao', 'biāo', 'biáo', 'biǎo', 'biào',
        'bian', 'biān', 'bián', 'biǎn', 'biàn',
        'bin', 'bīn', 'bín', 'bǐn', 'bìn',
        'bing', 'bīng', 'bíng', 'bǐng', 'bìng',
        'bu', 'bū', 'bú', 'bǔ', 'bù',
        
        // C
        'ca', 'cā', 'cá', 'cǎ', 'cà',
        'ce', 'cē', 'cé', 'cě', 'cè',
        'cai', 'cāi', 'cái', 'cǎi', 'cài',
        'cao', 'cāo', 'cáo', 'cǎo', 'cào',
        'cou', 'cōu', 'còu', 'cǒu', 'còu',
        'can', 'cān', 'cán', 'cǎn', 'càn',
        'cen', 'cēn', 'cén', 'cěn', 'cèn',
        'cang', 'cāng', 'cáng', 'cǎng', 'càng',
        'ceng', 'cēng', 'céng', 'cěng', 'cèng',
        'ci', 'cī', 'cí', 'cǐ', 'cì',
        'cong', 'cōng', 'cóng', 'cǒng', 'còng',
        'cu', 'cū', 'cú', 'cǔ', 'cù',
        'cui', 'cuī', 'cuí', 'cuǐ', 'cuì',
        'cuan', 'cuān', 'cuán', 'cuǎn', 'cuàn',
        'cun', 'cūn', 'cún', 'cǔn', 'cùn',
        'chu', 'chū', 'chú', 'chǔ', 'chù',
        'chai', 'chāi', 'chái', 'chǎi', 'chài',
        'chao', 'chāo', 'cháo', 'chǎo', 'chào',
        'che', 'chē', 'ché', 'chě', 'chè',
        'chen', 'chēn', 'chén', 'chěn', 'chèn',
        'cheng', 'chēng', 'chéng', 'chěng', 'chèng',
        'chi', 'chī', 'chí', 'chǐ', 'chì',
        'chong', 'chōng', 'chóng', 'chǒng', 'chòng',
        'chou', 'chōu', 'chóu', 'chǒu', 'chòu',
        'chuai', 'chuāi', 'chuái', 'chuǎi', 'chuài',
        'chuan', 'chuān', 'chuán', 'chuǎn', 'chuàn',
        'chuang', 'chuāng', 'chuáng', 'chuǎng', 'chuàng',
        'chui', 'chuī', 'chuí', 'chuǐ', 'chuì',
        'chun', 'chūn', 'chún', 'chǔn', 'chùn',
        'chuo', 'chuō', 'chuó', 'chuǒ', 'chuò',
        
        // D
        'da', 'dā', 'dá', 'dǎ', 'dà',
        'de', 'dē', 'dé', 'dě', 'dè',
        'dai', 'dāi', 'dái', 'dǎi', 'dài',
        'dao', 'dāo', 'dáo', 'dǎo', 'dào',
        'dou', 'dōu', 'dóu', 'dǒu', 'dòu',
        'dan', 'dān', 'dán', 'dǎn', 'dàn',
        'den', 'dēn', 'dén', 'děn', 'dèn',
        'dang', 'dāng', 'dáng', 'dǎng', 'dàng',
        'deng', 'dēng', 'déng', 'děng', 'dèng',
        'di', 'dī', 'dí', 'dǐ', 'dì',
        'dia', 'diā', 'diá', 'diǎ', 'dià',
        'die', 'diē', 'dié', 'diě', 'diè',
        'diao', 'diāo', 'diáo', 'diǎo', 'diào',
        'diu', 'diū', 'diú', 'diǔ', 'diù',
        'dian', 'diān', 'dián', 'diǎn', 'diàn',
        'ding', 'dīng', 'díng', 'dǐng', 'dìng',
        'dong', 'dōng', 'dóng', 'dǒng', 'dòng',
        'du', 'dū', 'dú', 'dǔ', 'dù',
        'dui', 'duī', 'duí', 'duǐ', 'duì',
        'duan', 'duān', 'duán', 'duǎn', 'duàn',
        'dun', 'dūn', 'dún', 'dǔn', 'dùn',
        'duo', 'duō', 'duó', 'duǒ', 'duò',
        
        // E
        'e', 'ē', 'é', 'ě', 'è',
        'ei', 'ēi', 'éi', 'ěi', 'èi',
        'en', 'ēn', 'én', 'ěn', 'èn',
        'er', 'ēr', 'ér', 'ěr', 'èr',
        
        // F
        'fa', 'fā', 'fá', 'fǎ', 'fà',
        'fo', 'fō', 'fé', 'fě', 'fè',
        'fei', 'fēi', 'féi', 'fěi', 'fèi',
        'fou', 'fōu', 'fóu', 'fǒu', 'fòu',
        'fan', 'fān', 'fán', 'fǎn', 'fàn',
        'fen', 'fēn', 'fén', 'fěn', 'fèn',
        'fang', 'fāng', 'fáng', 'fǎng', 'fàng',
        'feng', 'fēng', 'féng', 'fěng', 'fèng',
        'fu', 'fū', 'fú', 'fǔ', 'fù',
        
        // G
        'ga', 'gā', 'gá', 'gǎ', 'gà',
        'ge', 'gē', 'gé', 'gě', 'gè',
        'gai', 'gāi', 'gái', 'gǎi', 'gài',
        'gao', 'gāo', 'gáo', 'gǎo', 'gào',
        'gou', 'gōu', 'góu', 'gǒu', 'gòu',
        'gan', 'gān', 'gán', 'gǎn', 'gàn',
        'gen', 'gēn', 'gén', 'gěn', 'gèn',
        'gang', 'gāng', 'gáng', 'gǎng', 'gàng',
        'geng', 'gēng', 'géng', 'gěng', 'gèng',
        'gu', 'gū', 'gú', 'gǔ', 'gù',
        'gua', 'guā', 'guá', 'guǎ', 'guà',
        'guo', 'guō', 'guó', 'guǒ', 'guò',
        'guai', 'guāi', 'guái', 'guǎi', 'guài',
        'guan', 'guān', 'guán', 'guǎn', 'guàn',
        'gun', 'gūn', 'gún', 'gǔn', 'gùn',
        'guang', 'guāng', 'guáng', 'guǎng', 'guàng',
        'gui', 'guī', 'guí', 'guǐ', 'guì',
        
        // H
        'ha', 'hā', 'há', 'hǎ', 'hà',
        'he', 'hē', 'hé', 'hě', 'hè',
        'hai', 'hāi', 'hái', 'hǎi', 'hài',
        'hao', 'hāo', 'háo', 'hǎo', 'hào',
        'hou', 'hōu', 'hóu', 'hǒu', 'hòu',
        'han', 'hān', 'hán', 'hǎn', 'hàn',
        'hen', 'hēn', 'hén', 'hěn', 'hèn',
        'hang', 'hāng', 'háng', 'hǎng', 'hàng',
        'heng', 'hēng', 'héng', 'hěng', 'hèng',
        'hong', 'hōng', 'hóng', 'hǒng', 'hòng',
        'hu', 'hū', 'hú', 'hǔ', 'hù',
        'hua', 'huā', 'huá', 'huǎ', 'huà',
        'huo', 'huō', 'huó', 'huǒ', 'huò',
        'huai', 'huāi', 'huái', 'huǎi', 'huài',
        'huan', 'huān', 'huán', 'huǎn', 'huàn',
        'hun', 'hūn', 'hún', 'hǔn', 'hùn',
        'huang', 'huāng', 'huáng', 'huǎng', 'huàng',
        'hui', 'huī', 'huí', 'huǐ', 'huì',
        
        // J
        'ji', 'jī', 'jí', 'jǐ', 'jì',
        'jia', 'jiā', 'jiá', 'jiǎ', 'jià',
        'jie', 'jiē', 'jié', 'jiě', 'jiè',
        'jiao', 'jiāo', 'jiáo', 'jiǎo', 'jiào',
        'jiu', 'jiū', 'jiú', 'jiǔ', 'jiù',
        'jian', 'jiān', 'jián', 'jiǎn', 'jiàn',
        'jin', 'jīn', 'jín', 'jǐn', 'jìn',
        'jiang', 'jiāng', 'jiáng', 'jiǎng', 'jiàng',
        'jing', 'jīng', 'jíng', 'jǐng', 'jìng',
        'jiong', 'jiōng', 'jióng', 'jiǒng', 'jiòng',
        'ju', 'jū', 'jú', 'jǔ', 'jù',
        'juan', 'juān', 'juán', 'juǎn', 'juàn',
        'jun', 'jūn', 'jún', 'jǔn', 'jùn',
        'jue', 'juē', 'jué', 'juě', 'juè',
        
        // K
        'ka', 'kā', 'ká', 'kǎ', 'kà',
        'ke', 'kē', 'ké', 'kě', 'kè',
        'kai', 'kāi', 'kái', 'kǎi', 'kài',
        'kao', 'kāo', 'káo', 'kǎo', 'kào',
        'kou', 'kōu', 'kóu', 'kǒu', 'kòu',
        'kan', 'kān', 'kán', 'kǎn', 'kàn',
        'ken', 'kēn', 'kén', 'kěn', 'kèn',
        'kang', 'kāng', 'káng', 'kǎng', 'kàng',
        'keng', 'kēng', 'kéng', 'kěng', 'kèng',
        'kong', 'kōng', 'kóng', 'kǒng', 'kòng',
        'ku', 'kū', 'kú', 'kǔ', 'kù',
        'kua', 'kuā', 'kuá', 'kuǎ', 'kuà',
        'kuo', 'kuō', 'kuó', 'kuǒ', 'kuò',
        'kuai', 'kuāi', 'kuái', 'kuǎi', 'kuài',
        'kuan', 'kuān', 'kuán', 'kuǎn', 'kuàn',
        'kun', 'kūn', 'kún', 'kǔn', 'kùn',
        'kuang', 'kuāng', 'kuáng', 'kuǎng', 'kuàng',
        'kui', 'kuī', 'kuí', 'kuǐ', 'kuì',
        
        // L
        'la', 'lā', 'lá', 'lǎ', 'là',
        'le', 'lē', 'lé', 'lě', 'lè',
        'lai', 'lāi', 'lái', 'lǎi', 'lài',
        'lao', 'lāo', 'láo', 'lǎo', 'lào',
        'lou', 'lōu', 'lóu', 'lǒu', 'lòu',
        'lan', 'lān', 'lán', 'lǎn', 'làn',
        'lang', 'lāng', 'láng', 'lǎng', 'làng',
        'leng', 'lēng', 'léng', 'lěng', 'lèng',
        'li', 'lī', 'lí', 'lǐ', 'lì',
        'lia', 'liā', 'liá', 'liǎ', 'lià',
        'lie', 'liē', 'lié', 'liě', 'liè',
        'liao', 'liāo', 'liáo', 'liǎo', 'liào',
        'liu', 'liū', 'liú', 'liǔ', 'liù',
        'lian', 'liān', 'lián', 'liǎn', 'liàn',
        'lin', 'līn', 'lín', 'lǐn', 'lìn',
        'liang', 'liāng', 'liáng', 'liǎng', 'liàng',
        'ling', 'līng', 'líng', 'lǐng', 'lìng',
        'long', 'lōng', 'lóng', 'lǒng', 'lòng',
        'lu', 'lū', 'lú', 'lǔ', 'lù',
        'luo', 'luō', 'luó', 'luǒ', 'luò',
        'luan', 'luān', 'luán', 'luǎn', 'luàn',
        'lun', 'lūn', 'lún', 'lǔn', 'lùn',
        'luo', 'luō', 'luó', 'luǒ', 'luò',
        'lve', 'lüe', 'lve', 'lve', 'lve',
        'lue', 'lüe', 'lüe', 'lüe', 'lüe',
        
        // M
        'ma', 'mā', 'má', 'mǎ', 'mà',
        'me', 'mē', 'mé', 'mě', 'mè',
        'mai', 'māi', 'mái', 'mǎi', 'mài',
        'mao', 'māo', 'máo', 'mǎo', 'mào',
        'mou', 'mōu', 'móu', 'mǒu', 'mòu',
        'man', 'mān', 'mán', 'mǎn', 'màn',
        'men', 'mēn', 'mén', 'měn', 'mèn',
        'mang', 'māng', 'máng', 'mǎng', 'màng',
        'meng', 'mēng', 'méng', 'měng', 'mèng',
        'mi', 'mī', 'mí', 'mǐ', 'mì',
        'mie', 'miē', 'mié', 'miě', 'miè',
        'miao', 'miāo', 'miáo', 'miǎo', 'miào',
        'miu', 'miū', 'miú', 'miǔ', 'miù',
        'mian', 'miān', 'mián', 'miǎn', 'miàn',
        'min', 'mīn', 'mín', 'mǐn', 'mìn',
        'ming', 'mīng', 'míng', 'mǐng', 'mìng',
        'mong', 'mōng', 'méng', 'mǒng', 'mòng',
        'mu', 'mū', 'mú', 'mǔ', 'mù',
        
        // N
        'n', 'nā', 'ná', 'nǎ', 'nà',
        'ne', 'nē', 'né', 'ně', 'nè',
        'nai', 'nāi', 'nái', 'nǎi', 'nài',
        'nao', 'nāo', 'náo', 'nǎo', 'nào',
        'nou', 'nōu', 'nóu', 'nǒu', 'nòu',
        'nan', 'nān', 'nán', 'nǎn', 'nàn',
        'nen', 'nēn', 'nén', 'něn', 'nèn',
        'nang', 'nāng', 'náng', 'nǎng', 'nàng',
        'neng', 'nēng', 'néng', 'něng', 'nèng',
        'ni', 'nī', 'ní', 'nǐ', 'nì',
        'nia', 'niā', 'niá', 'niǎ', 'nià',
        'nie', 'niē', 'nié', 'niě', 'niè',
        'niao', 'niāo', 'niáo', 'niǎo', 'niào',
        'niu', 'niū', 'niú', 'niǔ', 'niù',
        'nian', 'niān', 'nián', 'niǎn', 'niàn',
        'nin', 'nīn', 'nín', 'nǐn', 'nìn',
        'niang', 'niāng', 'niáng', 'niǎng', 'niàng',
        'ning', 'nīng', 'níng', 'nǐng', 'nìng',
        'nong', 'nōng', 'nóng', 'nǒng', 'nòng',
        'nu', 'nū', 'nú', 'nǔ', 'nù',
        'nuo', 'nuō', 'nuó', 'nuǒ', 'nuò',
        'nuan', 'nuān', 'nuán', 'nuǎn', 'nuàn',
        'nun', 'nūn', 'nún', 'nǔn', 'nùn',
        'nve', 'nve', 'nve', 'nve', 'nve',
        'nue', 'nue', 'nue', 'nue', 'nue',
        
        // O
        'o', 'ō', 'ó', 'ǒ', 'ò',
        'ou', 'ōu', 'óu', 'ǒu', 'òu',
        'ong', 'ōng', 'óng', 'ǒng', 'òng',
        
        // P
        'pa', 'pā', 'pá', 'pǎ', 'pà',
        'po', 'pō', 'pó', 'pǒ', 'pò',
        'pai', 'pāi', 'pái', 'pǎi', 'pài',
        'pao', 'pāo', 'páo', 'pǎo', 'pào',
        'pou', 'pōu', 'póu', 'pǒu', 'pòu',
        'pan', 'pān', 'pán', 'pǎn', 'pàn',
        'pen', 'pēn', 'pén', 'pěn', 'pèn',
        'pang', 'pāng', 'páng', 'pǎng', 'pàng',
        'peng', 'pēng', 'péng', 'pěng', 'pèng',
        'pi', 'pī', 'pí', 'pǐ', 'pì',
        'pie', 'piē', 'pié', 'piě', 'piè',
        'piao', 'piāo', 'piáo', 'piǎo', 'piào',
        'pian', 'piān', 'pián', 'piǎn', 'piàn',
        'pin', 'pīn', 'pín', 'pǐn', 'pìn',
        'ping', 'pīng', 'píng', 'pǐng', 'pìng',
        'pong', 'pōng', 'péng', 'pǒng', 'pòng',
        'pu', 'pū', 'pú', 'pǔ', 'pù',
        
        // Q
        'qi', 'qī', 'qí', 'qǐ', 'qì',
        'qia', 'qiā', 'qiá', 'qiǎ', 'qià',
        'qie', 'qiē', 'qié', 'qiě', 'qiè',
        'qiao', 'qiāo', 'qiáo', 'qiǎo', 'qiào',
        'qiu', 'qiū', 'qiú', 'qiǔ', 'qiù',
        'qian', 'qiān', 'qián', 'qiǎn', 'qiàn',
        'qin', 'qīn', 'qín', 'qǐn', 'qìn',
        'qiang', 'qiāng', 'qiáng', 'qiǎng', 'qiàng',
        'qing', 'qīng', 'qíng', 'qǐng', 'qìng',
        'qiong', 'qiōng', 'qióng', 'qiǒng', 'qiòng',
        'qu', 'qū', 'qú', 'qǔ', 'qù',
        'quan', 'quān', 'quán', 'quǎn', 'quàn',
        'qun', 'qūn', 'qún', 'qǔn', 'qùn',
        'que', 'quē', 'qué', 'quě', 'què',
        
        // R
        'ran', 'rān', 'rán', 'rǎn', 'ràn',
        'ren', 'rén', 'rén', 'rěn', 'rèn',
        'rang', 'rāng', 'ráng', 'rǎng', 'ràng',
        'reng', 'rēng', 'réng', 'rěng', 'rèng',
        'ri', 'rì', 'rí', 'rǐ', 'rì',
        'rong', 'róng', 'róng', 'rǒng', 'ròng',
        'ru', 'rú', 'rú', 'rǔ', 'rù',
        'rua', 'ruā', 'ruá', 'ruǎ', 'ruà',
        'ruo', 'ruò', 'ruó', 'ruǒ', 'ruò',
        'ruan', 'ruān', 'ruán', 'ruǎn', 'ruàn',
        'rui', 'ruì', 'ruí', 'ruǐ', 'ruì',
        'run', 'rūn', 'rún', 'rǔn', 'rùn',
        'ruo', 'ruò', 'ruó', 'ruǒ', 'ruò',
        
        // S
        'sa', 'sā', 'sá', 'sǎ', 'sà',
        'se', 'sè', 'sé', 'sě', 'sè',
        'sai', 'sāi', 'sái', 'sǎi', 'sài',
        'sao', 'sāo', 'sáo', 'sǎo', 'sào',
        'sou', 'sōu', 'sóu', 'sǒu', 'sòu',
        'san', 'sān', 'sán', 'sǎn', 'sàn',
        'sen', 'sēn', 'sén', 'sěn', 'sèn',
        'sang', 'sāng', 'sáng', 'sǎng', 'sàng',
        'seng', 'sēng', 'séng', 'sěng', 'sèng',
        'si', 'sī', 'sí', 'sǐ', 'sì',
        'song', 'sōng', 'sóng', 'sǒng', 'sòng',
        'su', 'sū', 'sú', 'sǔ', 'sù',
        'sui', 'suī', 'suí', 'suǐ', 'suì',
        'suan', 'suān', 'suán', 'suǎn', 'suàn',
        'sun', 'sūn', 'sún', 'sǔn', 'sùn',
        'suo', 'suǒ', 'suó', 'suǒ', 'suò',
        'sha', 'shā', 'shá', 'shǎ', 'shà',
        'she', 'shē', 'shé', 'shě', 'shè',
        'shai', 'shāi', 'shái', 'shǎi', 'shài',
        'shei', 'shēi', 'shéi', 'shěi', 'shèi',
        'shao', 'shāo', 'sháo', 'shǎo', 'shào',
        'shou', 'shōu', 'shóu', 'shǒu', 'shòu',
        'shan', 'shān', 'shán', 'shǎn', 'shàn',
        'shen', 'shēn', 'shén', 'shěn', 'shèn',
        'shang', 'shāng', 'sháng', 'shǎng', 'shàng',
        'sheng', 'shēng', 'shéng', 'shěng', 'shèng',
        'shi', 'shī', 'shí', 'shǐ', 'shì',
        'shong', 'shōng', 'shóng', 'shǒng', 'shòng',
        'shu', 'shū', 'shú', 'shǔ', 'shù',
        'shua', 'shuā', 'shuá', 'shuǎ', 'shuà',
        'shuo', 'shuō', 'shuó', 'shuǒ', 'shuò',
        'shuai', 'shuāi', 'shuái', 'shuǎi', 'shuài',
        'shuan', 'shuān', 'shuán', 'shuǎн', 'shuàn',
        'shun', 'shūn', 'shún', 'shǔn', 'shùn',
        'shuang', 'shuāng', 'shuáng', 'shuǎng', 'shuàng',
        'shui', 'shuī', 'shuí', 'shuǐ', 'shuì',
        'shuo', 'shuō', 'shuó', 'shuǒ', 'shuò',
        
        // T
        'ta', 'tā', 'tá', 'tǎ', 'tà',
        'te', 'tè', 'té', 'tě', 'tè',
        'tai', 'tāi', 'tái', 'tǎi', 'tài',
        'tao', 'tāo', 'táo', 'tǎo', 'tào',
        'tou', 'tōu', 'tóu', 'tǒu', 'tòu',
        'tan', 'tān', 'tán', 'tǎн', 'tàn',
        'tang', 'tāng', 'táng', 'tǎng', 'tàng',
        'teng', 'tēng', 'téng', 'těng', 'tèng',
        'ti', 'tī', 'tí', 'tǐ', 'tì',
        'tie', 'tiē', 'tié', 'tiě', 'tiè',
        'tiao', 'tiāo', 'tiáo', 'tiǎo', 'tiào',
        'tian', 'tiān', 'tián', 'tiǎn', 'tiàn',
        'ting', 'tīng', 'tíng', 'tǐng', 'tìng',
        'tong', 'tōng', 'tóng', 'tǒng', 'tòng',
        'tu', 'tū', 'tú', 'tǔ', 'tù',
        'tuo', 'tuō', 'tuó', 'tuǒ', 'tuò',
        'tuan', 'tuān', 'tuán', 'tuǎn', 'tuàn',
        'tun', 'tūn', 'tún', 'tǔn', 'tùn',
        'tui', 'tuī', 'tuí', 'tuǐ', 'tuì',
        
        // W
        'wa', 'wā', 'wá', 'wǎ', 'wà',
        'wo', 'wō', 'wó', 'wǒ', 'wò',
        'wai', 'wāi', 'wái', 'wǎi', 'wài',
        'wei', 'wēi', 'wéi', 'wěi', 'wèi',
        'wan', 'wān', 'wán', 'wǎn', 'wàn',
        'wen', 'wēn', 'wén', 'wěn', 'wèn',
        'wang', 'wāng', 'wáng', 'wǎng', 'wàng',
        'weng', 'wēng', 'wéng', 'wěng', 'wèng',
        'wu', 'wū', 'wú', 'wǔ', 'wù',
        
        // X
        'xi', 'xī', 'xí', 'xǐ', 'xì',
        'xia', 'xiā', 'xiá', 'xiǎ', 'xià',
        'xie', 'xiē', 'xié', 'xiě', 'xiè',
        'xiao', 'xiāo', 'xiáo', 'xiǎo', 'xiào',
        'xiu', 'xiū', 'xiú', 'xiǔ', 'xiù',
        'xian', 'xiān', 'xián', 'xiǎn', 'xiàn',
        'xin', 'xīn', 'xín', 'xǐn', 'xìn',
        'xiang', 'xiāng', 'xiáng', 'xiǎng', 'xiàng',
        'xing', 'xīng', 'xíng', 'xǐng', 'xìng',
        'xiong', 'xiōng', 'xióng', 'xiǒng', 'xiòng',
        'xu', 'xū', 'xú', 'xǔ', 'xù',
        'xuan', 'xuān', 'xuán', 'xuǎn', 'xuàn',
        'xun', 'xūn', 'xún', 'xǔn', 'xùn',
        'xue', 'xuē', 'xué', 'xuě', 'xuè',
        
        // Y
        'ya', 'yā', 'yá', 'yǎ', 'yà',
        'yo', 'yō', 'yó', 'yǒ', 'yò',
        'ye', 'yē', 'yé', 'yě', 'yè',
        'yai', 'yāi', 'yái', 'yǎi', 'yài',
        'yao', 'yāo', 'yáo', 'yǎo', 'yào',
        'you', 'yōu', 'yóu', 'yǒu', 'yòu',
        'yan', 'yān', 'yán', 'yǎn', 'yàn',
        'yang', 'yāng', 'yáng', 'yǎng', 'yàng',
        'yeng', 'yēng', 'yéng', 'yěng', 'yèng',
        'yi', 'yī', 'yí', 'yǐ', 'yì',
        'yin', 'yīn', 'yín', 'yǐn', 'yìn',
        'ying', 'yīng', 'yíng', 'yǐng', 'yìng',
        'yong', 'yōng', 'yóng', 'yǒng', 'yòng',
        'yu', 'yū', 'yú', 'yǔ', 'yù',
        'yuan', 'yuān', 'yuán', 'yuǎn', 'yuàn',
        'yun', 'yūn', 'yún', 'yǔn', 'yùn',
        'yue', 'yuē', 'yué', 'yuě', 'yuè',
        
        // Z
        'za', 'zā', 'zá', 'zǎ', 'zà',
        'ze', 'zé', 'zé', 'zě', 'zè',
        'zai', 'zāi', 'zái', 'zǎi', 'zài',
        'zao', 'zāo', 'záo', 'zǎo', 'zào',
        'zou', 'zōu', 'zóu', 'zǒu', 'zòu',
        'zan', 'zān', 'zán', 'zǎn', 'zàn',
        'zen', 'zēn', 'zén', 'zěn', 'zèn',
        'zang', 'zāng', 'záng', 'zǎng', 'zàng',
        'zeng', 'zēng', 'zéng', 'zěng', 'zèng',
        'zi', 'zī', 'zí', 'zǐ', 'zì',
        'zong', 'zōng', 'zóng', 'zǒng', 'zòng',
        'zu', 'zū', 'zú', 'zǔ', 'zù',
        'zui', 'zuī', 'zuí', 'zuǐ', 'zuì',
        'zuan', 'zuān', 'zuán', 'zuǎn', 'zuàn',
        'zun', 'zūn', 'zún', 'zǔn', 'zùn',
        'zuo', 'zuǒ', 'zuó', 'zuǒ', 'zuò',
        'zha', 'zhā', 'zhá', 'zhǎ', 'zhà',
        'zhe', 'zhē', 'zhé', 'zhě', 'zhè',
        'zhai', 'zhāi', 'zhái', 'zhǎi', 'zhài',
        'zhao', 'zhāo', 'zháo', 'zhǎo', 'zhào',
        'zhou', 'zhōu', 'zhóu', 'zhǒu', 'zhòu',
        'zhan', 'zhān', 'zhán', 'zhǎn', 'zhàn',
        'zhen', 'zhēn', 'zhén', 'zhěn', 'zhèn',
        'zhang', 'zhāng', 'zháng', 'zhǎng', 'zhàng',
        'zheng', 'zhēng', 'zhéng', 'zhěng', 'zhèng',
        'zhi', 'zhī', 'zhí', 'zhǐ', 'zhì',
        'zhong', 'zhōng', 'zhóng', 'zhǒng', 'zhòng',
        'zhu', 'zhū', 'zhú', 'zhǔ', 'zhù',
        'zhua', 'zhuā', 'zhuá', 'zhuǎ', 'zhuà',
        'zhuo', 'zhuō', 'zhuó', 'zhuǒ', 'zhuò',
        'zhuai', 'zhuāi', 'zhuái', 'zhuǎi', 'zhuài',
        'zhuan', 'zhuān', 'zhuán', 'zhuǎn', 'zhuàn',
        'zhun', 'zhūn', 'zhún', 'zhǔn', 'zhùn',
        'zhuang', 'zhuāng', 'zhuáng', 'zhuǎng', 'zhuàng',
        'zhui', 'zhuī', 'zhuí', 'zhuǐ', 'zhuì',
        
        // 可以根据需要继续添加更多拼音
    );
    
    // 预定义的部首列表，按笔画数排列（完整214个部首，按照新华字典标准）
    private $radical_list = array(
        // 1画 (6个)
        '一', '丨', '丶', '丿', '乙', '亅',
        
        // 2画 (23个)
        '二', '亠', '人', '儿', '入', '八', '冂', '冖', '冫', '几', '凵', '刀', '力', '勹', '匕', '匚', '匸', '十', '卜', '卩', '厂', '厶', '又',
        
        // 3画 (31个)
        '口', '囗', '土', '士', '夂', '夊', '夕', '大', '女', '子', '宀', '寸', '小', '尢', '尸', '屮', '山', '巛', '工', '己', '巾', '干', '幺', '广', '廴', '廾', '弋', '弓', '彐', '彡', '彳',
        
        // 4画 (35个)
        '心', '戈', '戶', '手', '支', '攴', '文', '斗', '斤', '方', '无', '日', '曰', '月', '木', '欠', '止', '歹', '殳', '毋', '比', '毛', '氏', '气', '水', '火', '爪', '父', '爻', '爿', '片', '牙', '牛', '犬', '玄',
        
        // 5画 (29个)
        '玉', '瓜', '瓦', '甘', '生', '用', '田', '疋', '疒', '癶', '白', '皮', '皿', '目', '矛', '矢', '石', '示', '禸', '禾', '穴', '立', '竹', '米', '糸', '缶', '网', '羊', '羽',
        
        // 6画 (31个)
        '老', '而', '耒', '耳', '聿', '肉', '臣', '自', '至', '臼', '舌', '舛', '舟', '艮', '色', '艸', '虍', '虫', '血', '行', '衣', '襾', '見', '角', '言', '谷', '豆', '豕', '豸', '貝', '赤',
        
        // 7画 (23个)
        '走', '足', '身', '車', '辛', '辰', '辵', '邑', '酉', '釆', '里', '金', '長', '門', '阜', '隶', '隹', '雨', '青', '非', '面', '革', '韋',
        
        // 8画 (11个)
        '韭', '音', '頁', '風', '飛', '食', '首', '香', '馬', '骨', '高',
        
        // 9画 (7个)
        '髟', '鬥', '鬯', '鬲', '鬼', '魚', '鳥',
        
        // 10画 (6个)
        '鹵', '鹿', '麥', '麻', '黃', '黍',
        
        // 11画 (4个)
        '黑', '黹', '黽', '鼎',
        
        // 12画 (3个)
        '鼓', '鼠', '鼻',
        
        // 13画 (2个)
        '齊', '齒',
        
        // 14画 (1个)
        '龍',
        
        // 15画 (1个)
        '龜',
        
        // 17画 (1个)
        '龠'
    );
    
    public function __construct() {
        add_action('init', array($this, 'register_post_type'));
        add_action('init', array($this, 'add_rewrite_rules'), 20);
        add_action('template_redirect', array($this, 'maybe_redirect_search'), 1);
        add_action('admin_enqueue_scripts', array($this, 'admin_scripts'));
        add_action('wp_enqueue_scripts', array($this, 'frontend_scripts'));
        add_action('add_meta_boxes', array($this, 'add_meta_boxes'));
        add_action('save_post', array($this, 'save_character_meta'));
        add_action('save_post', array($this, 'save_calligraphy_meta'));
        add_action('save_post', array($this, 'save_ancient_text_meta'));
        add_action('save_post', array($this, 'save_dictionary_meta'));
        add_action('save_post', array($this, 'save_idiom_meta'));
        add_action('save_post', array($this, 'save_museum_meta')); // 添加保存博物馆元数据
        add_action('save_post', array($this, 'save_collection_meta')); // 添加保存藏品元数据
        add_shortcode('character_dictionary', array($this, 'character_dictionary_shortcode'));
        add_action('wp_ajax_search_character', array($this, 'search_character_callback'));
        add_action('wp_ajax_nopriv_search_character', array($this, 'search_character_callback'));
        add_action('template_redirect', array($this, 'character_template_redirect'), 20);
        add_filter('template_include', array($this, 'custom_search_template'));
        // 添加管理菜单
        add_action('admin_menu', array($this, 'add_admin_menu'));
        // 处理管理页面表单提交
        add_action('admin_init', array($this, 'handle_admin_form_submission'));
        // 添加查询变量
        add_filter('query_vars', array($this, 'add_query_vars'));
        // 添加部首查询AJAX动作
        add_action('wp_ajax_get_characters_by_radical', array($this, 'get_characters_by_radical_callback'));
        add_action('wp_ajax_nopriv_get_characters_by_radical', array($this, 'get_characters_by_radical_callback'));
        // 添加书法作品查询AJAX动作
        add_action('wp_ajax_get_calligraphy_by_character', array($this, 'get_calligraphy_by_character_callback'));
        add_action('wp_ajax_nopriv_get_calligraphy_by_character', array($this, 'get_calligraphy_by_character_callback'));
        // 添加书法作品筛选AJAX动作
        add_action('wp_ajax_filter_calligraphy', array($this, 'filter_calligraphy_callback'));
        add_action('wp_ajax_nopriv_filter_calligraphy', array($this, 'filter_calligraphy_callback'));
        // 添加书法家、朝代、书体分类AJAX动作
        add_action('wp_ajax_get_calligraphy_artists', array($this, 'get_calligraphy_artists_callback'));
        add_action('wp_ajax_nopriv_get_calligraphy_artists', array($this, 'get_calligraphy_artists_callback'));
        add_action('wp_ajax_get_calligraphy_dynasties', array($this, 'get_calligraphy_dynasties_callback'));
        add_action('wp_ajax_nopriv_get_calligraphy_dynasties', array($this, 'get_calligraphy_dynasties_callback'));
        add_action('wp_ajax_get_calligraphy_styles', array($this, 'get_calligraphy_styles_callback'));
        add_action('wp_ajax_nopriv_get_calligraphy_styles', array($this, 'get_calligraphy_styles_callback'));
        // 添加相关词语和成语查询AJAX动作
        add_action('wp_ajax_get_related_dictionaries', array($this, 'get_related_dictionaries_callback'));
        add_action('wp_ajax_nopriv_get_related_dictionaries', array($this, 'get_related_dictionaries_callback'));
        add_action('wp_ajax_get_related_idioms', array($this, 'get_related_idioms_callback'));
        add_action('wp_ajax_nopriv_get_related_idioms', array($this, 'get_related_idioms_callback'));
        // 添加方言条目查询AJAX动作
        add_action('wp_ajax_get_dialect_entries', array($this, 'get_dialect_entries_callback'));
        add_action('wp_ajax_nopriv_get_dialect_entries', array($this, 'get_dialect_entries_callback'));
        add_action('wp_ajax_get_dialect_entry_detail', array($this, 'get_dialect_entry_detail_callback'));
        add_action('wp_ajax_nopriv_get_dialect_entry_detail', array($this, 'get_dialect_entry_detail_callback'));
        
        // 添加批量导入功能
        add_action('admin_menu', array($this, 'add_import_menu'));
        // 添加分批导入汉字的AJAX处理函数
        add_action('wp_ajax_import_characters_batch', array($this, 'import_characters_batch_callback'));
        // 添加导入词语和成语的AJAX处理函数
        add_action('wp_ajax_import_phrases_batch', array($this, 'import_phrases_batch_callback'));
    }
    
    /**
     * 添加批量导入菜单
     */
    public function add_import_menu() {
        add_submenu_page(
            'edit.php?post_type=chinese_character',
            '批量导入汉字',
            '批量导入',
            'manage_options',
            'import-chinese-characters',
            array($this, 'import_characters_page')
        );
    }
    
    /**
     * 批量导入汉字页面
     */
    public function import_characters_page() {
        // 检查用户权限
        if (!current_user_can('manage_options')) {
            wp_die('您没有权限访问此页面。');
        }
        
        echo '<div class="wrap">';
        echo '<h1>批量导入内容</h1>';
        echo '<p>此功能将导入汉字、词语和成语等数据。</p>';
        
        echo '<form method="post" action="" style="display:inline-block; margin-right: 10px;">';
        wp_nonce_field('import_characters_nonce', 'import_characters_nonce');
        echo '<input type="submit" name="import_characters" class="button button-primary" value="导入汉字" onclick="return confirm(\'确定要导入6000个常用汉字吗？这可能需要一些时间。\')">';
        echo '</form>';
        
        echo '<form method="post" action="" style="display:inline-block;">';
        wp_nonce_field('import_phrases_nonce', 'import_phrases_nonce');
        echo '<input type="submit" name="import_phrases" class="button button-primary" value="导入词语和成语" onclick="return confirm(\'确定要导入词语和成语吗？这可能需要一些时间。\')">';
        echo '</form>';
        
        echo '<div id="import-progress" style="margin-top: 20px; display: none;">';
        echo '<div id="progress-bar" style="width: 100%; background-color: #f0f0f0; border-radius: 5px; overflow: hidden;">';
        echo '<div id="progress-fill" style="width: 0%; height: 20px; background-color: #0073aa; transition: width 0.3s;"></div>';
        echo '</div>';
        echo '<p id="progress-text" style="margin-top: 10px;">准备导入...</p>';
        echo '<div id="import-log" style="margin-top: 10px; max-height: 200px; overflow-y: auto; border: 1px solid #ddd; padding: 10px;"></div>';
        echo '</div>';
        
        echo '</div>';
        
        // 处理导入汉字请求
        if (isset($_POST['import_characters']) && wp_verify_nonce($_POST['import_characters_nonce'], 'import_characters_nonce')) {
            // 检查权限
            if (!current_user_can('manage_options')) {
                wp_die('权限不足');
            }
            
            // 引入数据文件
            if (file_exists(plugin_dir_path(__FILE__) . 'data/common_characters_6000.php')) {
                require_once plugin_dir_path(__FILE__) . 'data/common_characters_6000.php';
                
                if (function_exists('chinese_character_get_full_6000_characters')) {
                    echo '<div class="notice notice-success"><p>';
                    echo '开始导入汉字数据...';
                    echo '</p></div>';
                    
                    // 添加JavaScript处理批量导入
                    ?>
                    <script type="text/javascript">
                    jQuery(document).ready(function($) {
                        var offset = 0;
                        var batchSize = 50;
                        var totalImported = 0;
                        var totalSkipped = 0;
                        
                        $('#import-progress').show();
                        $('#progress-text').text('准备导入汉字...');
                        
                        function importBatch() {
                            $.post(ajaxurl, {
                                action: 'import_characters_batch',
                                nonce: '<?php echo wp_create_nonce("import_characters_batch_nonce"); ?>',
                                offset: offset
                            }, function(response) {
                                if (response.success) {
                                    var data = response.data;
                                    
                                    totalImported += data.imported;
                                    totalSkipped += data.skipped;
                                    
                                    $('#progress-fill').css('width', data.progress + '%');
                                    $('#progress-text').text('已导入: ' + totalImported + ', 跳过: ' + totalSkipped + ', 总进度: ' + data.progress + '%');
                                    $('#import-log').append('<div>批次 ' + (offset/batchSize + 1) + ': 导入 ' + data.imported + ' 个, 跳过 ' + data.skipped + ' 个</div>');
                                    $('#import-log').scrollTop($('#import-log')[0].scrollHeight);
                                    
                                    if (data.finished || data.progress >= 100) {
                                        $('#progress-text').text('导入完成! 总计导入: ' + totalImported + ', 跳过: ' + totalSkipped);
                                        $('#import-log').append('<div><strong>导入完成!</strong></div>');
                                    } else {
                                        offset = data.offset;
                                        setTimeout(importBatch, 1000); // 1秒后继续导入下一批
                                    }
                                } else {
                                    $('#progress-text').text('导入出错: ' + response.data.message);
                                    $('#import-log').append('<div style="color: red;">错误: ' + response.data.message + '</div>');
                                }
                            });
                        }
                        
                        // 开始导入
                        importBatch();
                    });
                    </script>
                    <?php
                } else {
                    echo '<div class="notice notice-error"><p>汉字数据函数不存在。</p></div>';
                }
            } else {
                echo '<div class="notice notice-error"><p>汉字数据文件不存在。</p></div>';
            }
        }
        
        // 处理导入词语和成语请求
        if (isset($_POST['import_phrases']) && wp_verify_nonce($_POST['import_phrases_nonce'], 'import_phrases_nonce')) {
            // 检查权限
            if (!current_user_can('manage_options')) {
                wp_die('权限不足');
            }
            
            // 引入数据文件
            if (file_exists(plugin_dir_path(__FILE__) . 'data/phrases_and_idioms.php')) {
                require_once plugin_dir_path(__FILE__) . 'data/phrases_and_idioms.php';
                
                if (function_exists('chinese_get_phrases_and_idioms')) {
                    echo '<div class="notice notice-success"><p>';
                    echo '开始导入词语和成语数据...';
                    echo '</p></div>';
                    
                    // 添加JavaScript处理批量导入
                    ?>
                    <script type="text/javascript">
                    jQuery(document).ready(function($) {
                        var offset = 0;
                        var batchSize = 50;
                        var totalImported = 0;
                        var totalSkipped = 0;
                        
                        $('#import-progress').show();
                        $('#progress-text').text('准备导入词语和成语...');
                        
                        function importBatch() {
                            $.post(ajaxurl, {
                                action: 'import_phrases_batch',
                                nonce: '<?php echo wp_create_nonce("import_phrases_batch_nonce"); ?>',
                                offset: offset
                            }, function(response) {
                                if (response.success) {
                                    var data = response.data;
                                    
                                    totalImported += data.imported;
                                    totalSkipped += data.skipped;
                                    
                                    $('#progress-fill').css('width', data.progress + '%');
                                    $('#progress-text').text('已导入: ' + totalImported + ', 跳过: ' + totalSkipped + ', 总进度: ' + data.progress + '%');
                                    $('#import-log').append('<div>批次 ' + (offset/batchSize + 1) + ': 导入 ' + data.imported + ' 个, 跳过 ' + data.skipped + ' 个</div>');
                                    $('#import-log').scrollTop($('#import-log')[0].scrollHeight);
                                    
                                    if (data.finished || data.progress >= 100) {
                                        $('#progress-text').text('导入完成! 总计导入: ' + totalImported + ', 跳过: ' + totalSkipped);
                                        $('#import-log').append('<div><strong>导入完成!</strong></div>');
                                    } else {
                                        offset = data.offset;
                                        setTimeout(importBatch, 1000); // 1秒后继续导入下一批
                                    }
                                } else {
                                    $('#progress-text').text('导入出错: ' + response.data.message);
                                    $('#import-log').append('<div style="color: red;">错误: ' + response.data.message + '</div>');
                                }
                            });
                        }
                        
                        // 开始导入
                        importBatch();
                    });
                    </script>
                    <?php
                } else {
                    echo '<div class="notice notice-error"><p>词语和成语数据函数不存在。</p></div>';
                }
            } else {
                echo '<div class="notice notice-error"><p>词语和成语数据文件不存在。</p></div>';
            }
        }
    }
    
    /**
     * 分批导入汉字的AJAX处理函数
     */
    public function import_characters_batch_callback() {
        // 验证nonce
        if (!wp_verify_nonce($_POST['nonce'], 'import_characters_batch_nonce')) {
            wp_send_json_error(array('message' => '安全验证失败'));
        }
        
        // 检查权限
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => '权限不足'));
        }
        
        // 获取偏移量
        $offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0;
        $batch_size = 50; // 每批导入50个汉字
        
        // 引入数据文件
        if (!file_exists(plugin_dir_path(__FILE__) . 'data/common_characters_6000.php')) {
            wp_send_json_error(array('message' => '数据文件不存在'));
        }
        
        require_once plugin_dir_path(__FILE__) . 'data/common_characters_6000.php';
        
        if (!function_exists('chinese_character_get_full_6000_characters')) {
            wp_send_json_error(array('message' => '数据函数不存在'));
        }
        
        // 获取完整汉字数据
        $all_characters = chinese_character_get_full_6000_characters();
        $total_count = count($all_characters);
        
        // 检查是否已完成所有导入
        if ($offset >= $total_count) {
            wp_send_json_success(array(
                'finished' => true,
                'imported' => 0,
                'skipped' => 0,
                'total' => $total_count,
                'progress' => 100
            ));
        }
        
        // 获取当前批次的数据
        $batch_characters = array_slice($all_characters, $offset, $batch_size);
        
        // 导入当前批次
        $imported_count = 0;
        $skipped_count = 0;
        
        foreach ($batch_characters as $character_data) {
            // 检查是否已存在同名汉字
            $existing = get_page_by_title($character_data['title'], OBJECT, 'chinese_character');
            
            if (!$existing) {
                // 创建新文章
                $post_id = wp_insert_post(array(
                    'post_title'    => $character_data['title'],
                    'post_content'  => $character_data['content'],
                    'post_status'   => 'publish',
                    'post_type'     => 'chinese_character'
                ));
                
                // 添加元数据
                if ($post_id) {
                    // 基本信息
                    update_post_meta($post_id, '_character_pinyin', $character_data['pinyin']);
                    update_post_meta($post_id, '_character_radical', $character_data['radical']);
                    update_post_meta($post_id, '_character_stroke_count', $character_data['stroke_count']);
                    update_post_meta($post_id, '_character_traditional_form', $character_data['traditional_form']);
                    
                    // 详细解释
                    update_post_meta($post_id, '_character_detailed_explanation', $character_data['detailed_explanation']);
                    update_post_meta($post_id, '_character_guoyu_dictionary', $character_data['guoyu_dictionary']);
                    update_post_meta($post_id, '_character_kangxi_dictionary', $character_data['kangxi_dictionary']);
                    
                    // 其他可选字段设置为空字符串
                    update_post_meta($post_id, '_character_shuowen_jiezi', '');
                    update_post_meta($post_id, '_character_dialects', '');
                    update_post_meta($post_id, '_character_etymology', '');
                    update_post_meta($post_id, '_character_other_meanings', '');
                    update_post_meta($post_id, '_character_variants', '');
                    
                    $imported_count++;
                }
            } else {
                $skipped_count++;
            }
        }
        
        // 计算进度
        $progress = min(100, round((($offset + $batch_size) / $total_count) * 100));
        
        // 返回结果
        wp_send_json_success(array(
            'finished' => false,
            'imported' => $imported_count,
            'skipped' => $skipped_count,
            'total' => $total_count,
            'progress' => $progress,
            'offset' => $offset + $batch_size
        ));
    }
    
    /**
     * 分批导入词语和成语的AJAX处理函数
     */
    public function import_phrases_batch_callback() {
        // 验证nonce
        if (!wp_verify_nonce($_POST['nonce'], 'import_phrases_batch_nonce')) {
            wp_send_json_error(array('message' => '安全验证失败'));
        }
        
        // 检查权限
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => '权限不足'));
        }
        
        // 引入数据文件
        if (!file_exists(plugin_dir_path(__FILE__) . 'data/phrases_and_idioms.php')) {
            wp_send_json_error(array('message' => '词语和成语数据文件不存在'));
        }
        
        require_once plugin_dir_path(__FILE__) . 'data/phrases_and_idioms.php';
        
        if (!function_exists('chinese_get_phrases_and_idioms')) {
            wp_send_json_error(array('message' => '词语和成语数据函数不存在'));
        }
        
        // 获取完整词语和成语数据
        $all_phrases = chinese_get_phrases_and_idioms();
        $total_count = count($all_phrases);
        
        // 每批导入的数量
        $batch_size = 50;
        $offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0;
        
        // 检查是否已完成所有导入
        if ($offset >= $total_count) {
            wp_send_json_success(array(
                'finished' => true,
                'imported' => 0,
                'skipped' => 0,
                'total' => $total_count,
                'progress' => 100
            ));
        }
        
        // 获取当前批次的数据
        $batch_phrases = array_slice($all_phrases, $offset, $batch_size);
        
        // 导入当前批次
        $imported_count = 0;
        $skipped_count = 0;
        
        foreach ($batch_phrases as $phrase_data) {
            // 根据类型确定要导入的文章类型
            $post_type = 'chinese_dictionary'; // 默认为词语
            if (isset($phrase_data['type']) && $phrase_data['type'] === '成语') {
                $post_type = 'chinese_idiom';
            }
            
            // 检查是否已存在同名词语或成语
            $existing = get_page_by_title($phrase_data['title'], OBJECT, $post_type);
            
            if (!$existing) {
                // 创建新文章
                $post_id = wp_insert_post(array(
                    'post_title'    => $phrase_data['title'],
                    'post_content'  => $phrase_data['content'],
                    'post_status'   => 'publish',
                    'post_type'     => $post_type
                ));
                
                // 添加元数据
                if ($post_id) {
                    // 基本信息
                    update_post_meta($post_id, '_dictionary_pinyin', $phrase_data['pinyin']);
                    
                    // 详细解释
                    update_post_meta($post_id, '_dictionary_detailed_explanation', $phrase_data['detailed_explanation']);
                    update_post_meta($post_id, '_dictionary_guoyu_dictionary', $phrase_data['guoyu_dictionary']);
                    
                    // 其他可选字段设置为空字符串
                    update_post_meta($post_id, '_dictionary_etymology', '');
                    update_post_meta($post_id, '_dictionary_synonyms', '');
                    update_post_meta($post_id, '_dictionary_antonyms', '');
                    update_post_meta($post_id, '_dictionary_example', $phrase_data['example']);
                    
                    $imported_count++;
                }
            } else {
                $skipped_count++;
            }
        }
        
        // 计算进度
        $processed = min($offset + $batch_size, $total_count);
        $progress = round(($processed / $total_count) * 100);
        
        // 返回结果
        wp_send_json_success(array(
            'finished' => $processed >= $total_count,
            'imported' => $imported_count,
            'skipped' => $skipped_count,
            'total' => $total_count,
            'progress' => $progress,
            'next_offset' => $offset + $batch_size
        ));
    }
    
    /**
     * 注册汉字文章类型
     */
    public function register_post_type() {
        $labels = array(
            'name'                  => '汉字',
            'singular_name'         => '汉字',
            'menu_name'             => '汉字字典',
            'name_admin_bar'        => '汉字',
            'archives'              => '汉字档案',
            'attributes'            => '汉字属性',
            'parent_item_colon'     => '父级汉字',
            'all_items'             => '所有汉字',
            'add_new_item'          => '新增汉字',
            'add_new'               => '新增',
            'new_item'              => '新汉字',
            'edit_item'             => '编辑汉字',
            'update_item'           => '更新汉字',
            'view_item'             => '查看汉字',
            'view_items'            => '查看汉字',
            'search_items'          => '搜索汉字',
            'not_found'             => '未找到',
            'not_found_in_trash'    => '回收站中没有',
            'featured_image'        => '特色图像',
            'set_featured_image'    => '设置特色图像',
            'remove_featured_image' => '移除特色图像',
            'use_featured_image'    => '用作特色图像',
            'insert_into_item'      => '插入到汉字中',
            'uploaded_to_this_item' => '上传到此汉字',
            'items_list'            => '汉字列表',
            'items_list_navigation' => '汉字列表导航',
            'filter_items_list'     => '筛选汉字列表',
        );
        
        $args = array(
            'label'                 => '汉字',
            'description'           => '汉字字典条目',
            'labels'                => $labels,
            'supports'              => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'revisions'),
            'hierarchical'          => false,
            'public'                => true,
            'show_ui'               => true,
            'show_in_menu'          => true,
            'menu_position'         => 5,
            'menu_icon'             => 'dashicons-book-alt',
            'show_in_admin_bar'     => true,
            'show_in_nav_menus'     => true,
            'can_export'            => true,
            'has_archive'           => true,
            'exclude_from_search'   => false,
            'publicly_queryable'    => true,
            'capability_type'       => 'post',
            'show_in_rest'          => true,
            'rewrite'               => array('slug' => 'character'),
        );
        
        register_post_type('chinese_character', $args);
        
        // 注册书法作品文章类型
        $calligraphy_labels = array(
            'name'                  => '书法作品',
            'singular_name'         => '书法作品',
            'menu_name'             => '书法作品',
            'name_admin_bar'        => '书法作品',
            'archives'              => '书法作品档案',
            'attributes'            => '书法作品属性',
            'parent_item_colon'     => '父级书法作品',
            'all_items'             => '所有书法作品',
            'add_new_item'          => '新增书法作品',
            'add_new'               => '新增',
            'new_item'              => '新书法作品',
            'edit_item'             => '编辑书法作品',
            'update_item'           => '更新书法作品',
            'view_item'             => '查看书法作品',
            'view_items'            => '查看书法作品',
            'search_items'          => '搜索书法作品',
            'not_found'             => '未找到',
            'not_found_in_trash'    => '回收站中没有',
            'featured_image'        => '书法作品图像',
            'set_featured_image'    => '设置书法作品图像',
            'remove_featured_image' => '移除书法作品图像',
            'use_featured_image'    => '用作书法作品图像',
            'insert_into_item'      => '插入到书法作品中',
            'uploaded_to_this_item' => '上传到此书法作品',
            'items_list'            => '书法作品列表',
            'items_list_navigation' => '书法作品列表导航',
            'filter_items_list'     => '筛选书法作品列表',
        );
        
        $calligraphy_args = array(
            'label'                 => '书法作品',
            'description'           => '汉字书法作品',
            'labels'                => $calligraphy_labels,
            'supports'              => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'revisions'),
            'hierarchical'          => false,
            'public'                => true,
            'show_ui' => true,
            'show_in_menu'          => 'edit.php?post_type=chinese_character',
            'menu_position'         => 6,
            'menu_icon'             => 'dashicons-art',
            'show_in_admin_bar'     => true,
            'show_in_nav_menus'     => true,
            'can_export'            => true,
            'has_archive'           => true,
            'exclude_from_search'   => false,
            'publicly_queryable'    => true,
            'capability_type'       => 'post',
            'show_in_rest'          => true,
            'rewrite'               => array('slug' => 'calligraphy'),
        );
        
        register_post_type('chinese_calligraphy', $calligraphy_args);
        
         // 注册古籍文章类型
        $ancient_text_labels = array(
            'name'                  => '古籍',
            'singular_name'         => '古籍',
            'menu_name'             => '古籍文献',
            'name_admin_bar'        => '古籍',
            'archives'              => '古籍档案',
            'attributes'            => '古籍属性',
            'parent_item_colon'     => '父级古籍',
            'all_items'             => '所有古籍',
            'add_new_item'          => '新增古籍',
            'add_new'               => '新增',
            'new_item'              => '新古籍',
            'edit_item'             => '编辑古籍',
            'update_item'           => '更新古籍',
            'view_item'             => '查看古籍',
            'view_items'            => '查看古籍',
            'search_items'          => '搜索古籍',
            'not_found'             => '未找到',
            'not_found_in_trash'    => '回收站中没有',
            'featured_image'        => '古籍封面',
            'set_featured_image'    => '设置古籍封面',
            'remove_featured_image' => '移除古籍封面',
            'use_featured_image'    => '用作古籍封面',
            'insert_into_item'      => '插入到古籍中',
            'uploaded_to_this_item' => '上传到此古籍',
            'items_list'            => '古籍列表',
            'items_list_navigation' => '古籍列表导航',
            'filter_items_list'     => '筛选古籍列表',
        );
        
        $ancient_text_args = array(
            'label'                 => '古籍',
            'description'           => '古籍条目',
            'labels'                => $ancient_text_labels,
            'supports'              => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'revisions'),
            'hierarchical'          => false,
            'public'                => true,
            'show_ui'               => true,
            'show_in_menu'          => false,
            'menu_position'         => 6, // 调整菜单位置，与古籍管理菜单一致
            'menu_icon'             => 'dashicons-book',
            'show_in_admin_bar'     => true,
            'show_in_nav_menus'     => true,
            'can_export'            => true,
            'has_archive'           => true,
            'exclude_from_search'   => false,
            'publicly_queryable'    => true,
            'capability_type'       => 'post',
            'show_in_rest'          => true,
            'rewrite'               => array('slug' => 'ancient-text'),
        );
        
        register_post_type('chinese_ancient_text', $ancient_text_args);
       
       
       // 注册词典文章类型
        $dictionary_labels = array(
            'name'                  => '词典',
            'singular_name'         => '词语',
            'menu_name'             => '词典',
            'name_admin_bar'        => '词语',
            'archives'              => '词典档案',
            'attributes'            => '词语属性',
            'parent_item_colon'     => '父级词语',
            'all_items'             => '所有词语',
            'add_new_item'          => '新增词语',
            'add_new'               => '新增',
            'new_item'              => '新词语',
            'edit_item'             => '编辑词语',
            'update_item'           => '更新词语',
            'view_item'             => '查看词语',
            'view_items'            => '查看词语',
            'search_items'          => '搜索词语',
            'not_found'             => '未找到',
            'not_found_in_trash'    => '回收站中没有',
            'featured_image'        => '特色图像',
            'set_featured_image'    => '设置特色图像',
            'remove_featured_image' => '移除特色图像',
            'use_featured_image'    => '用作特色图像',
            'insert_into_item'      => '插入到词语中',
            'uploaded_to_this_item' => '上传到此词语',
            'items_list'            => '词语列表',
            'items_list_navigation' => '词语列表导航',
            'filter_items_list'     => '筛选词语列表',
        );
        
        $dictionary_args = array(
            'label'                 => '词典',
            'description'           => '词语条目',
            'labels'                => $dictionary_labels,
            'supports'              => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'revisions'),
            'hierarchical'          => false,
            'public'                => true,
            'show_ui'               => true,
            'show_in_menu'          => 'edit.php?post_type=chinese_character',
            'menu_position'         => 7,
            'menu_icon'             => 'dashicons-book',
            'show_in_admin_bar'     => true,
            'show_in_nav_menus'     => true,
            'can_export'            => true,
            'has_archive'           => true,
            'exclude_from_search'   => false,
            'publicly_queryable'    => true,
            'capability_type'       => 'post',
            'show_in_rest'          => true,
            'rewrite'               => array('slug' => 'dictionary'),
        );
        
        register_post_type('chinese_dictionary', $dictionary_args);
        
        // 注册成语词典文章类型
        $idiom_labels = array(
            'name'                  => '成语词典',
            'singular_name'         => '成语',
            'menu_name'             => '成语词典',
            'name_admin_bar'        => '成语',
            'archives'              => '成语档案',
            'attributes'            => '成语属性',
            'parent_item_colon'     => '父级成语',
            'all_items'             => '所有成语',
            'add_new_item'          => '新增成语',
            'add_new'               => '新增',
            'new_item'              => '新成语',
            'edit_item'             => '编辑成语',
            'update_item'           => '更新成语',
            'view_item'             => '查看成语',
            'view_items'            => '查看成语',
            'search_items'          => '搜索成语',
            'not_found'             => '未找到',
            'not_found_in_trash'    => '回收站中没有',
            'featured_image'        => '特色图像',
            'set_featured_image'    => '设置特色图像',
            'remove_featured_image' => '移除特色图像',
            'use_featured_image'    => '用作特色图像',
            'insert_into_item'      => '插入到成语中',
            'uploaded_to_this_item' => '上传到此成语',
            'items_list'            => '成语列表',
            'items_list_navigation' => '成语列表导航',
            'filter_items_list'     => '筛选成语列表',
        );
        
        $idiom_args = array(
            'label'                 => '成语词典',
            'description'           => '成语条目',
            'labels'                => $idiom_labels,
            'supports'              => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'revisions'),
            'hierarchical'          => false,
            'public'                => true,
            'show_ui'               => true,
            'show_in_menu'          => 'edit.php?post_type=chinese_character',
            'menu_position'         => 8,
            'menu_icon'             => 'dashicons-book',
            'show_in_admin_bar'     => true,
            'show_in_nav_menus'     => true,
            'can_export'            => true,
            'has_archive'           => true,
            'exclude_from_search'   => false,
            'publicly_queryable'    => true,
            'capability_type'       => 'post',
            'show_in_rest'          => true,
            'rewrite'               => array('slug' => 'idiom'),
        );
        
        register_post_type('chinese_idiom', $idiom_args);
       
        // 注册博物馆文章类型
        $museum_labels = array(
            'name'                  => '博物馆',
            'singular_name'         => '博物馆',
            'menu_name'             => '博物馆',
            'name_admin_bar'        => '博物馆',
            'archives'              => '博物馆档案',
            'attributes'            => '博物馆属性',
            'parent_item_colon'     => '父级博物馆',
            'all_items'             => '所有博物馆',
            'add_new_item'          => '新增博物馆',
            'add_new'               => '新增',
            'new_item'              => '新博物馆',
            'edit_item'             => '编辑博物馆',
            'update_item'           => '更新博物馆',
            'view_item'             => '查看博物馆',
            'view_items'            => '查看博物馆',
            'search_items'          => '搜索博物馆',
            'not_found'             => '未找到',
            'not_found_in_trash'    => '回收站中没有',
            'featured_image'        => '博物馆封面',
            'set_featured_image'    => '设置博物馆封面',
            'remove_featured_image' => '移除博物馆封面',
            'use_featured_image'    => '用作博物馆封面',
            'insert_into_item'      => '插入到博物馆中',
            'uploaded_to_this_item' => '上传到此博物馆',
            'items_list'            => '博物馆列表',
            'items_list_navigation' => '博物馆列表导航',
            'filter_items_list'     => '筛选博物馆列表',
        );
        
        $museum_args = array(
            'label'                 => '博物馆',
            'description'           => '博物馆条目',
            'labels'                => $museum_labels,
            'supports'              => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'revisions'),
            'hierarchical'          => false,
            'public'                => true,
            'show_ui'               => true,
            'show_in_menu'          => false, // 将在下面添加到自定义菜单中
            'menu_position'         => 7,
            'menu_icon'             => 'dashicons-building',
            'show_in_admin_bar'     => true,
            'show_in_nav_menus'     => true,
            'can_export'            => true,
            'has_archive'           => true,
            'exclude_from_search'   => false,
            'publicly_queryable'    => true,
            'capability_type'       => 'post',
            'show_in_rest'          => true,
            'rewrite'               => array('slug' => 'museum'),
        );
        
        register_post_type('chinese_museum', $museum_args);
        
        // 注册藏品文章类型
        $collection_labels = array(
            'name'                  => '藏品',
            'singular_name'         => '藏品',
            'menu_name'             => '藏品',
            'name_admin_bar'        => '藏品',
            'archives'              => '藏品档案',
            'attributes'            => '藏品属性',
            'parent_item_colon'     => '父级藏品',
            'all_items'             => '所有藏品',
            'add_new_item'          => '新增藏品',
            'add_new'               => '新增',
            'new_item'              => '新藏品',
            'edit_item'             => '编辑藏品',
            'update_item'           => '更新藏品',
            'view_item'             => '查看藏品',
            'view_items'            => '查看藏品',
            'search_items'          => '搜索藏品',
            'not_found'             => '未找到',
            'not_found_in_trash'    => '回收站中没有',
            'featured_image'        => '藏品图片',
            'set_featured_image'    => '设置藏品图片',
            'remove_featured_image' => '移除藏品图片',
            'use_featured_image'    => '用作藏品图片',
            'insert_into_item'      => '插入到藏品中',
            'uploaded_to_this_item' => '上传到此藏品',
            'items_list'            => '藏品列表',
            'items_list_navigation' => '藏品列表导航',
            'filter_items_list'     => '筛选藏品列表',
        );
        
        $collection_args = array(
            'label'                 => '藏品',
            'description'           => '博物馆藏品条目',
            'labels'                => $collection_labels,
            'supports'              => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'revisions'),
            'hierarchical'          => false,
            'public'                => true,
            'show_ui'               => true,
            'show_in_menu'          => false, // 将在下面添加到自定义菜单中
            'menu_position'         => 8,
            'menu_icon'             => 'dashicons-images-alt2',
            'show_in_admin_bar'     => true,
            'show_in_nav_menus'     => true,
            'can_export'            => true,
            'has_archive'           => true,
            'exclude_from_search'   => false,
            'publicly_queryable'    => true,
            'capability_type'       => 'post',
            'show_in_rest'          => true,
            'rewrite'               => array('slug' => 'collection'),
        );
        
        register_post_type('chinese_collection', $collection_args);
        
        // 刷新重写规则
        flush_rewrite_rules();
    }
    
    /**
     * 添加后台元框
     */
    public function add_meta_boxes() {
        add_meta_box(
            'character-basic-info',
            '汉字基本信息',
            array($this, 'render_basic_info_meta_box'),
            'chinese_character',
            'normal',
            'high'
        );
        
        // 添加汉字发音含义对元框（放在基本信息元框后面）
        add_meta_box(
            'character-pronunciations',
            '汉字发音含义对',
            array($this, 'render_character_pronunciations_meta_box'),
            'chinese_character',
            'normal',
            'high'
        );
        
        add_meta_box(
            'character-detailed-explanation',
            '详细解释',
            array($this, 'render_detailed_explanation_meta_box'),
            'chinese_character',
            'normal',
            'high'
        );
        
        add_meta_box(
            'character-guoyu-dictionary',
            '国语辞典',
            array($this, 'render_guoyu_dictionary_meta_box'),
            'chinese_character',
            'normal',
            'high'
        );
        
        add_meta_box(
            'character-kangxi-dictionary',
            '康熙字典',
            array($this, 'render_kangxi_dictionary_meta_box'),
            'chinese_character',
            'normal',
            'high'
        );
        
        add_meta_box(
            'character-shuowen-jiezi',
            '说文解字',
            array($this, 'render_shuowen_jiezi_meta_box'),
            'chinese_character',
            'normal',
            'high'
        );
        
        add_meta_box(
            'character-dialects',
            '音韵方言',
            array($this, 'render_dialects_meta_box'),
            'chinese_character',
            'normal',
            'high'
        );
        
        add_meta_box(
            'character-etymology',
            '字源字形',
            array($this, 'render_etymology_meta_box'),
            'chinese_character',
            'normal',
            'high'
        );
        
        add_meta_box(
            'character-other-meanings',
            '其他释义',
            array($this, 'render_other_meanings_meta_box'),
            'chinese_character',
            'normal',
            'high'
        );

        // 为词典添加元框
        add_meta_box(
            'dictionary-basic-info',
            '词语基本信息',
            array($this, 'render_dictionary_basic_info_meta_box'),
            'chinese_dictionary',
            'normal',
            'high'
        );
        
        add_meta_box(
            'dictionary-detailed-explanation',
            '详细解释',
            array($this, 'render_dictionary_detailed_explanation_meta_box'),
            'chinese_dictionary',
            'normal',
            'high'
        );
        
        // 添加词典的额外元框
        add_meta_box(
            'dictionary-guoyu-dictionary',
            '国语辞典',
            array($this, 'render_dictionary_guoyu_dictionary_meta_box'),
            'chinese_dictionary',
            'normal',
            'high'
        );
        
        add_meta_box(
            'dictionary-dialects',
            '音韵方言',
            array($this, 'render_dictionary_dialects_meta_box'),
            'chinese_dictionary',
            'normal',
            'high'
        );
        
        add_meta_box(
            'dictionary-other-meanings',
            '其他释义',
            array($this, 'render_dictionary_other_meanings_meta_box'),
            'chinese_dictionary',
            'normal',
            'high'
        );
        
        // 为成语词典添加元框
        add_meta_box(
            'idiom-basic-info',
            '成语基本信息',
            array($this, 'render_idiom_basic_info_meta_box'),
            'chinese_idiom',
            'normal',
            'high'
        );
        
        add_meta_box(
            'idiom-detailed-explanation',
            '详细解释',
            array($this, 'render_idiom_detailed_explanation_meta_box'),
            'chinese_idiom',
            'normal',
            'high'
        );
        
        add_meta_box(
            'idiom-derivation',
            '成语典故',
            array($this, 'render_idiom_derivation_meta_box'),
            'chinese_idiom',
            'normal',
            'high'
        );
        
        // 添加成语词典的额外元框
        add_meta_box(
            'idiom-guoyu-dictionary',
            '国语辞典',
            array($this, 'render_idiom_guoyu_dictionary_meta_box'),
            'chinese_idiom',
            'normal',
            'high'
        );
        
        add_meta_box(
            'idiom-dialects',
            '音韵方言',
            array($this, 'render_idiom_dialects_meta_box'),
            'chinese_idiom',
            'normal',
            'high'
        );
        
        add_meta_box(
            'idiom-other-meanings',
            '其他释义',
            array($this, 'render_idiom_other_meanings_meta_box'),
            'chinese_idiom',
            'normal',
            'high'
        );
        
        // 为书法作品添加元框
        add_meta_box(
            'calligraphy-character-info',
            '汉字信息',
            array($this, 'render_calligraphy_character_meta_box'),
            'chinese_calligraphy',
            'normal',
            'high'
        );
        
        add_meta_box(
            'calligraphy-artist-info',
            '书法家信息',
            array($this, 'render_calligraphy_artist_meta_box'),
            'chinese_calligraphy',
            'normal',
            'high'
        );
        
        // 为古籍添加元框
        add_meta_box(
            'ancient-text-basic-info',
            '古籍基本信息',
            array($this, 'render_ancient_text_basic_info_meta_box'),
            'chinese_ancient_text',
            'normal',
            'high'
        );
        
        add_meta_box(
            'ancient-text-content',
            '古籍内容',
            array($this, 'render_ancient_text_content_meta_box'),
            'chinese_ancient_text',
            'normal',
            'high'
        );
        
        // 添加古籍关联汉字元框
        add_meta_box(
            'ancient-text-related-characters',
            '关联汉字',
            array($this, 'render_ancient_text_related_characters_meta_box'),
            'chinese_ancient_text',
            'normal',
            'high'
        );
        
        // 添加博物馆基本信息元框
        add_meta_box(
            'museum-basic-info',
            '博物馆基本信息',
            array($this, 'render_museum_basic_info_meta_box'),
            'chinese_museum',
            'normal',
            'high'
        );
        
        // 添加藏品基本信息元框
        add_meta_box(
            'collection-basic-info',
            '藏品基本信息',
            array($this, 'render_collection_basic_info_meta_box'),
            'chinese_collection',
            'normal',
            'high'
        );
        
        // 添加藏品关联博物馆元框
        add_meta_box(
            'collection-related-museum',
            '关联博物馆',
            array($this, 'render_collection_related_museum_meta_box'),
            'chinese_collection',
            'normal',
            'high'
        );
        
        // 添加藏品类别选项元框
        add_meta_box(
            'collection-type',
            '藏品类别',
            array($this, 'render_collection_type_meta_box'),
            'chinese_collection',
            'side',
            'default'
        );
        
        // 添加藏品介绍文字元框
        add_meta_box(
            'collection-description',
            '藏品介绍',
            array($this, 'render_collection_description_meta_box'),
            'chinese_collection',
            'normal',
            'high'
        );
    }
    
    /**
     * 藏品介绍文字元框
     */
    public function render_collection_description_meta_box($post) {
        $description = get_post_meta($post->ID, '_collection_description', true);
        wp_nonce_field('save_collection_meta', 'collection_meta_nonce');
        ?>
        <textarea id="collection_description" name="collection_description" rows="5" class="large-text" placeholder="请输入藏品的介绍文字"><?php echo esc_textarea($description); ?></textarea>
        <p class="description">输入藏品的详细介绍，将在藏品页面图片下方显示</p>
        <?php
    }
    
    /**
     * 藏品类别选项元框
     */
    public function render_collection_type_meta_box($post) {
        // 获取当前藏品的类别
        $collection_type = get_post_meta($post->ID, '_collection_type', true);
        
        // 如果没有设置类别，默认为"其他"
        if (empty($collection_type)) {
            $collection_type = '其他';
        }
        
        wp_nonce_field('save_collection_meta', 'collection_meta_nonce');
        
        ?>
        <fieldset>
            <legend class="screen-reader-text"><span>藏品类别</span></legend>
            
            <p>
                <label>
                    <input type="radio" name="collection_type" value="书法" <?php checked($collection_type, '书法'); ?> />
                    <span>书法</span>
                </label>
            </p>
            
            <p>
                <label>
                    <input type="radio" name="collection_type" value="绘画" <?php checked($collection_type, '绘画'); ?> />
                    <span>绘画</span>
                </label>
            </p>
            
            <p>
                <label>
                    <input type="radio" name="collection_type" value="藏品" <?php checked($collection_type, '藏品'); ?> />
                    <span>藏品</span>
                </label>
            </p>
            
            <p>
                <label>
                    <input type="radio" name="collection_type" value="其他" <?php checked($collection_type, '其他'); ?> />
                    <span>其他</span>
                </label>
            </p>
            
            <p class="description">请选择藏品的类别</p>
        </fieldset>
        <?php
    }
    
    /**
     * 博物馆基本信息元框
     */
    public function render_museum_basic_info_meta_box($post) {
        $location = get_post_meta($post->ID, '_museum_location', true);
        $founded_year = get_post_meta($post->ID, '_museum_founded_year', true);
        $director = get_post_meta($post->ID, '_museum_director', true);
        $website = get_post_meta($post->ID, '_museum_website', true);
        
        // 添加nonce字段以确保安全保存
        wp_nonce_field('save_museum_meta', 'museum_meta_nonce');
        ?>
        <table class="form-table">
            <tr>
                <th><label for="museum_location">位置</label></th>
                <td>
                    <input type="text" id="museum_location" name="museum_location" value="<?php echo esc_attr($location); ?>" class="regular-text" />
                    <p class="description">输入博物馆所在城市或具体地址</p>
                </td>
            </tr>
            <tr>
                <th><label for="museum_founded_year">建立年份</label></th>
                <td>
                    <input type="text" id="museum_founded_year" name="museum_founded_year" value="<?php echo esc_attr($founded_year); ?>" class="regular-text" />
                    <p class="description">输入博物馆建立年份</p>
                </td>
            </tr>
            <tr>
                <th><label for="museum_director">馆长</label></th>
                <td>
                    <input type="text" id="museum_director" name="museum_director" value="<?php echo esc_attr($director); ?>" class="regular-text" />
                    <p class="description">输入博物馆现任馆长姓名</p>
                </td>
            </tr>
            <tr>
                <th><label for="museum_website">官方网站</label></th>
                <td>
                    <input type="url" id="museum_website" name="museum_website" value="<?php echo esc_attr($website); ?>" class="regular-text" />
                    <p class="description">输入博物馆官方网站地址</p>
                </td>
            </tr>
        </table>
        <?php
    }
    
    /**
     * 藏品基本信息元框
     */
    public function render_collection_basic_info_meta_box($post) {
        $dynasty = get_post_meta($post->ID, '_collection_dynasty', true);
        $category = get_post_meta($post->ID, '_collection_category', true);
        $material = get_post_meta($post->ID, '_collection_material', true);
        $dimensions = get_post_meta($post->ID, '_collection_dimensions', true);
        $acquisition_date = get_post_meta($post->ID, '_collection_acquisition_date', true);
        ?>
        <table class="form-table">
            <tr>
                <th><label for="collection_dynasty">朝代</label></th>
                <td>
                    <input type="text" id="collection_dynasty" name="collection_dynasty" value="<?php echo esc_attr($dynasty); ?>" class="regular-text" />
                    <p class="description">输入藏品所属的朝代</p>
                </td>
            </tr>
            <tr>
                <th><label for="collection_category">分类</label></th>
                <td>
                    <input type="text" id="collection_category" name="collection_category" value="<?php echo esc_attr($category); ?>" class="regular-text" />
                    <p class="description">输入藏品的分类（如书画、陶瓷、青铜器等）</p>
                </td>
            </tr>
            <tr>
                <th><label for="collection_material">材质</label></th>
                <td>
                    <input type="text" id="collection_material" name="collection_material" value="<?php echo esc_attr($material); ?>" class="regular-text" />
                    <p class="description">输入藏品的材质（如纸、绢、铜、瓷等）</p>
                </td>
            </tr>
            <tr>
                <th><label for="collection_dimensions">尺寸</label></th>
                <td>
                    <input type="text" id="collection_dimensions" name="collection_dimensions" value="<?php echo esc_attr($dimensions); ?>" class="regular-text" />
                    <p class="description">输入藏品的尺寸信息</p>
                </td>
            </tr>
            <tr>
                <th><label for="collection_acquisition_date">入藏日期</label></th>
                <td>
                    <input type="date" id="collection_acquisition_date" name="collection_acquisition_date" value="<?php echo esc_attr($acquisition_date); ?>" />
                    <p class="description">选择藏品入藏日期</p>
                </td>
            </tr>
        </table>
        <?php
    }
    
    /**
     * 获取博物馆文章列表
     */
    private function get_museums_list() {
        $museums = get_posts(array(
            'post_type' => 'chinese_museum',
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        return $museums;
    }
    /**
     * 藏品关联博物馆元框
     */
    public function render_collection_related_museum_meta_box($post) {
        // 获取所有博物馆文章
        $museums = $this->get_museums_list();
        
        // 获取当前藏品关联的博物馆ID
        $related_museum = get_post_meta($post->ID, '_collection_related_museum', true);
        
        wp_nonce_field('save_collection_meta', 'collection_meta_nonce');
        ?>
        <table class="form-table">
            <tr>
                <th scope="row">
                    <label for="collection_related_museum">关联博物馆</label>
                </th>
                <td>
                    <select id="collection_related_museum" name="collection_related_museum" class="chinese-museum-select" style="width: 100%;">
                        <option value="">请选择关联的博物馆</option>
                        <?php foreach ($museums as $museum): ?>
                            <option value="<?php echo $museum->ID; ?>" <?php selected($related_museum, $museum->ID); ?>>
                                <?php echo esc_html($museum->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">选择藏品所属的博物馆。</p>
                </td>
            </tr>
        </table>
        
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#collection_related_museum').select2({
                placeholder: "搜索并选择博物馆",
                allowClear: true,
                width: '100%'
            });
        });
        </script>
        <?php
    }
    
    /**
     * 古籍基本信息元框
     */
    public function render_ancient_text_basic_info_meta_box($post) {
        $dynasty = get_post_meta($post->ID, '_ancient_text_dynasty', true);
        $author = get_post_meta($post->ID, '_ancient_text_author', true);
        $publisher = get_post_meta($post->ID, '_ancient_text_publisher', true);
        $publication_year = get_post_meta($post->ID, '_ancient_text_publication_year', true);
        $volume = get_post_meta($post->ID, '_ancient_text_volume', true);
        $chapter = get_post_meta($post->ID, '_ancient_text_chapter', true);
        $category = get_post_meta($post->ID, '_ancient_text_category', true); // 经史子集分类
        ?>
        <table class="form-table">
            <tr>
                <th><label for="ancient_text_dynasty">朝代</label></th>
                <td>
                    <input type="text" id="ancient_text_dynasty" name="ancient_text_dynasty" value="<?php echo esc_attr($dynasty); ?>" class="regular-text" />
                    <p class="description">输入古籍创作的朝代</p>
                </td>
            </tr>
            <tr>
                <th><label for="ancient_text_author">作者</label></th>
                <td>
                    <input type="text" id="ancient_text_author" name="ancient_text_author" value="<?php echo esc_attr($author); ?>" class="regular-text" />
                    <p class="description">输入古籍的作者</p>
                </td>
            </tr>
            <tr>
                <th><label for="ancient_text_publisher">出版者</label></th>
                <td>
                    <input type="text" id="ancient_text_publisher" name="ancient_text_publisher" value="<?php echo esc_attr($publisher); ?>" class="regular-text" />
                    <p class="description">输入古籍的出版者或刻印者</p>
                </td>
            </tr>
            <tr>
                <th><label for="ancient_text_publication_year">出版年份</label></th>
                <td>
                    <input type="text" id="ancient_text_publication_year" name="ancient_text_publication_year" value="<?php echo esc_attr($publication_year); ?>" class="regular-text" />
                    <p class="description">输入古籍的出版年份</p>
                </td>
            </tr>
            <tr>
                <th><label for="ancient_text_volume">卷数</label></th>
                <td>
                    <input type="text" id="ancient_text_volume" name="ancient_text_volume" value="<?php echo esc_attr($volume); ?>" class="regular-text" />
                    <p class="description">输入古籍的卷数</p>
                </td>
            </tr>
            <tr>
                <th><label for="ancient_text_chapter">章节</label></th>
                <td>
                    <input type="text" id="ancient_text_chapter" name="ancient_text_chapter" value="<?php echo esc_attr($chapter); ?>" class="regular-text" />
                    <p class="description">输入当前古籍条目对应的章节</p>
                </td>
            </tr>
            <tr>
                <th><label for="ancient_text_category">分类</label></th>
                <td>
                    <select id="ancient_text_category" name="ancient_text_category" class="regular-text">
                        <option value="">请选择分类</option>
                        <option value="经" <?php selected($category, '经'); ?>>经</option>
                        <option value="史" <?php selected($category, '史'); ?>>史</option>
                        <option value="子" <?php selected($category, '子'); ?>>子</option>
                        <option value="集" <?php selected($category, '集'); ?>>集</option>
                    </select>
                    <p class="description">选择古籍的经史子集分类</p>
                </td>
            </tr>
        </table>
        <?php
    }
    
    /**
     * 古籍内容元框
     */
    public function render_ancient_text_content_meta_box($post) {
        $content = get_post_meta($post->ID, '_ancient_text_content', true);
        wp_editor($content, 'ancient_text_content', array(
            'textarea_name' => 'ancient_text_content',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false,
            'quicktags' => true,
            'tinymce' => array(
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo'
            ),
        ));
    }
    
    /**
     * 获取汉字文章列表
     */
    private function get_characters_list() {
        $characters = get_posts(array(
            'post_type' => 'chinese_character',
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        return $characters;
    }
    
    /**
     * 获取词语文章列表
     */
    private function get_words_list() {
        $words = get_posts(array(
            'post_type' => 'chinese_dictionary',
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        return $words;
    }
    
    /**
     * 获取成语文章列表
     */
    private function get_idioms_list() {
        $idioms = get_posts(array(
            'post_type' => 'chinese_idiom',
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        return $idioms;
    }
    
    /**
     * 获取古籍文章列表
     */
    private function get_ancient_texts_list() {
        $ancient_texts = get_posts(array(
            'post_type' => 'chinese_ancient_text',
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        return $ancient_texts;
    }
    
    /**
     * 获取书法作品文章列表
     */
    private function get_calligraphies_list() {
        $calligraphies = get_posts(array(
            'post_type' => 'chinese_calligraphy',
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        return $calligraphies;
    }
    
    /**
     * 获取WordPress默认文章列表
     */
    private function get_default_posts_list() {
        $posts = get_posts(array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        return $posts;
    }
    
    /**
     * 获取WordPress默认页面列表
     */
    private function get_default_pages_list() {
        $pages = get_posts(array(
            'post_type' => 'page',
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        return $pages;
    }
    
    /**
     * 古籍关联汉字元框
     */
    public function render_ancient_text_related_characters_meta_box($post) {
        // 获取所有汉字文章
        $characters = $this->get_characters_list();
        
        // 获取当前古籍关联的汉字ID
        $related_characters = get_post_meta($post->ID, '_ancient_text_related_characters', true);
        if (!$related_characters) {
            $related_characters = array();
        } else if (!is_array($related_characters)) {
            $related_characters = array($related_characters);
        }
        
        wp_nonce_field('save_ancient_text_meta', 'ancient_text_meta_nonce');
        ?>
        <table class="form-table">
            <tr>
                <th scope="row">
                    <label for="ancient_text_related_characters">关联汉字</label>
                </th>
                <td>
                    <select multiple size="10" id="ancient_text_related_characters" name="ancient_text_related_characters[]" class="chinese-character-select" style="width: 100%;">
                        <?php foreach ($characters as $character): ?>
                            <option value="<?php echo $character->ID; ?>" <?php echo in_array($character->ID, $related_characters) ? 'selected' : ''; ?>>
                                <?php echo esc_html($character->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">可以选择多个汉字。输入汉字可进行搜索过滤。</p>
                </td>
            </tr>
        </table>
        
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#ancient_text_related_characters').select2({
                placeholder: "搜索并选择汉字",
                allowClear: true,
                width: '100%'
            });
        });
        </script>
        <?php
    }
    /**
     * 汉字基本信息元框
     */
    public function render_basic_info_meta_box($post) {
        $pinyin = get_post_meta($post->ID, '_character_pinyin', true);
        $radical = get_post_meta($post->ID, '_character_radical', true);
        $stroke_count = get_post_meta($post->ID, '_character_stroke_count', true);
        $traditional_form = get_post_meta($post->ID, '_character_traditional_form', true);
        $variants = get_post_meta($post->ID, '_character_variants', true);
        $related_ancient_text = get_post_meta($post->ID, '_character_related_ancient_text', true);
        $related_dictionaries = get_post_meta($post->ID, '_character_related_dictionaries', true);
        $related_idioms = get_post_meta($post->ID, '_character_related_idioms', true);
        
        // 获取所有古籍文章
        $ancient_texts = $this->get_ancient_texts_list();
        
        // 获取所有词语
        $dictionaries = $this->get_words_list();
        
        // 获取所有成语
        $idioms = $this->get_idioms_list();
        
        wp_nonce_field('save_character_meta', 'character_meta_nonce');
        ?>
        <table class="form-table">
            <tr>
                <th><label for="character_pinyin">拼音</label></th>
                <td>
                    <select id="character_pinyin" name="character_pinyin[]" class="regular-text pinyin-select" multiple size="10">
                        <option value="">请选择拼音（可多选）</option>
                        <?php 
                        // 将存储的拼音字符串转换为数组，支持空格分隔
                        $selected_pinyins = !empty($pinyin) ? preg_split('/\s+/', $pinyin, -1, PREG_SPLIT_NO_EMPTY) : array();
                        foreach ($this->pinyin_list as $p): ?>
                            <option value="<?php echo esc_attr($p); ?>" <?php echo in_array($p, $selected_pinyins) ? 'selected' : ''; ?>><?php echo esc_html($p); ?></option>
                        <?php endforeach; ?>
                        <?php 
                        // 添加自定义拼音选项
                        $custom_pinyin = get_option('chinese_character_custom_pinyin', array());
                        if (!empty($custom_pinyin)): ?>
                            <optgroup label="自定义拼音">
                                <?php foreach ($custom_pinyin as $cp): ?>
                                    <option value="<?php echo esc_attr($cp); ?>" <?php echo in_array($cp, $selected_pinyins) ? 'selected' : ''; ?>><?php echo esc_html($cp); ?></option>
                                <?php endforeach; ?>
                            </optgroup>
                        <?php endif; ?>
                    </select>
                    <p class="description">在上方输入框中输入拼音可搜索过滤选项，按住 Ctrl 键可选择多个拼音（Windows）或按住 Cmd 键选择多个拼音（Mac）</p>
                    <p class="description">选择汉字的拼音，支持带声调符号的拼音（可多选）</p>
                </td>
            </tr>
            <tr>
                <th><label for="character_pinyin_custom">或输入自定义拼音</label></th>
                <td>
                    <input type="text" id="character_pinyin_custom" name="character_pinyin_custom" value="<?php echo esc_attr($pinyin); ?>" class="regular-text" />
                    <p class="description">如果拼音列表中没有，请在此输入完整拼音，例如：yī fān fēng shùn</p>
                    <p class="description">
                        声调符号：<br>
                        第一声：ā ē ī ō ū ǖ<br>
                        第二声：á é í ó ú ǘ<br>
                        第三声：ǎ ě ǐ ǒ ǔ ǚ<br>
                        第四声：à è ì ò ù ǜ
                    </p>
                </td>
            </tr>
            
            <tr>
                <th><label for="character_radical">部首</label></th>
                <td>
                    <select id="character_radical" name="character_radical" class="regular-text">
                        <option value="">请选择部首</option>
                        <?php 
                        // 定义常用部首列表
                        $common_radicals = array('一', '丨', '丶', '丿', '乙', '亅', '二', '亠', '人', '儿', '入', '八', '冂', '冖', '冫', '几', '凵', '刀', '力', '勹', '匕', '匚', '匸', '十', '卜', '卩', '厂', '厶', '又', '口', '囗', '土', '士', '夂', '夊', '夕', '大', '女', '子', '宀', '寸', '小', '尢', '尸', '屮', '山', '巛', '工', '己', '巾', '干', '幺', '广', '廴', '廾', '弋', '弓', '彐', '彡', '彳', '心', '戈', '戶', '手', '支', '攴', '文', '斗', '斤', '方', '无', '日', '曰', '月', '木', '欠', '止', '歹', '殳', '毋', '比', '毛', '氏', '气', '水', '火', '爪', '父', '爻', '爿', '片', '牙', '牛', '犬', '玄', '玉', '瓜', '瓦', '甘', '生', '用', '田', '疋', '疒', '癶', '白', '皮', '皿', '目', '矛', '矢', '石', '示', '禸', '禾', '穴', '立', '竹', '米', '糸', '缶', '网', '羊', '羽', '老', '而', '耒', '耳', '聿', '肉', '臣', '自', '至', '臼', '舌', '舛', '舟', '艮', '色', '艸', '虍', '虫', '血', '行', '衣', '襾', '見', '角', '言', '谷', '豆', '豕', '豸', '貝', '赤', '走', '足', '身', '車', '辛', '辰', '辵', '邑', '酉', '釆', '里', '金', '長', '門', '阜', '隶', '隹', '雨', '青', '非', '面', '革', '韋', '韭', '音', '頁', '風', '飛', '食', '首', '香', '馬', '骨', '髟', '鬥', '鬯', '鬲', '鬼', '魚', '鳥', '鹵', '鹿', '麥', '麻', '黃', '黍', '黑', '黹', '黽', '鼎', '鼓', '鼠', '鼻', '齊', '齒', '龍', '龜', '龠');
                        foreach ($common_radicals as $r): ?>
                            <option value="<?php echo esc_attr($r); ?>" <?php selected($r, $radical); ?>><?php echo esc_html($r); ?></option>
                        <?php endforeach; ?>
                        <?php 
                        // 添加自定义部首选项
                        $custom_radical = get_option('chinese_character_custom_radical', array());
                        if (!empty($custom_radical)): ?>
                            <optgroup label="自定义部首">
                                <?php foreach ($custom_radical as $cr): ?>
                                    <option value="<?php echo esc_attr($cr); ?>" <?php selected($cr, $radical); ?>><?php echo esc_html($cr); ?></option>
                                <?php endforeach; ?>
                            </optgroup>
                        <?php endif; ?>
                    </select>
                    <p class="description">选择汉字的部首</p>
                </td>
            </tr>
            <tr>
                <th><label for="character_radical_custom">或输入自定义部首</label></th>
                <td><input type="text" id="character_radical_custom" name="character_radical_custom" value="<?php echo esc_attr($radical); ?>" class="regular-text" />
                <p class="description">如果部首列表中没有，请在此输入</p></td>
            </tr>
            <tr>
                <th><label for="character_stroke_count">笔画数</label></th>
                <td><input type="number" id="character_stroke_count" name="character_stroke_count" value="<?php echo esc_attr($stroke_count); ?>" class="regular-text" min="1" max="50" />
                <p class="description">输入汉字的笔画数</p></td>
            </tr>
            <tr>
                <th><label for="character_traditional_form">繁体字</label></th>
                <td><input type="text" id="character_traditional_form" name="character_traditional_form" value="<?php echo esc_attr($traditional_form); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="character_variants">异体字</label></th>
                <td><input type="text" id="character_variants" name="character_variants" value="<?php echo esc_attr($variants); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="character_related_ancient_text">关联古籍</label></th>
                <td>
                    <select id="character_related_ancient_text" name="character_related_ancient_text" class="regular-text">
                        <option value="">无关联古籍</option>
                        <?php foreach ($ancient_texts as $ancient_text): ?>
                            <option value="<?php echo esc_attr($ancient_text->ID); ?>" <?php selected($ancient_text->ID, $related_ancient_text); ?>>
                                <?php echo esc_html($ancient_text->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">选择与此汉字相关的古籍</p>
                </td>
            </tr>
            <tr>
                <th><label for="character_related_dictionaries">关联词语</label></th>
                <td>
                    <input type="text" id="dictionary-search" placeholder="搜索词语..." style="width: 100%; margin-bottom: 5px;" />
                    <select id="character_related_dictionaries" name="character_related_dictionaries[]" class="regular-text" multiple style="height: 150px; width: 100%;">
                        <?php foreach ($dictionaries as $dictionary): ?>
                            <option value="<?php echo esc_attr($dictionary->ID); ?>" <?php selected(is_array($related_dictionaries) && in_array($dictionary->ID, $related_dictionaries)); ?>>
                                <?php echo esc_html($dictionary->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">选择与此汉字相关的词语（可多选）。可以先搜索再选择。</p>
                </td>
            </tr>
            <tr>
                <th><label for="character_related_idioms">关联成语</label></th>
                <td>
                    <input type="text" id="idiom-search" placeholder="搜索成语..." style="width: 100%; margin-bottom: 5px;" />
                    <select id="character_related_idioms" name="character_related_idioms[]" class="regular-text" multiple style="height: 150px; width: 100%;">
                        <?php foreach ($idioms as $idiom): ?>
                            <option value="<?php echo esc_attr($idiom->ID); ?>" <?php selected(is_array($related_idioms) && in_array($idiom->ID, $related_idioms)); ?>>
                                <?php echo esc_html($idiom->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">选择与此汉字相关的成语（可多选）。可以先搜索再选择。</p>
                </td>
            </tr>
        </table>
        
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            // 词语搜索功能
            $('#dictionary-search').on('keyup', function() {
                var searchTerm = $(this).val().toLowerCase();
                $('#character_related_dictionaries option').each(function() {
                    var text = $(this).text().toLowerCase();
                    if (text.indexOf(searchTerm) !== -1) {
                        $(this).show();
                        $(this).prop('disabled', false);
                    } else {
                        $(this).hide();
                        $(this).prop('disabled', true);
                    }
                });
            });
            
            // 成语搜索功能
            $('#idiom-search').on('keyup', function() {
                var searchTerm = $(this).val().toLowerCase();
                $('#character_related_idioms option').each(function() {
                    var text = $(this).text().toLowerCase();
                    if (text.indexOf(searchTerm) !== -1) {
                        $(this).show();
                        $(this).prop('disabled', false);
                    } else {
                        $(this).hide();
                        $(this).prop('disabled', true);
                    }
                });
            });
            
            // 结构化解释中的词语搜索功能
            $(document).on('keyup', '.dictionary-search-in-structured', function() {
                var searchTerm = $(this).val().toLowerCase();
                $(this).siblings('select').find('option').each(function() {
                    var text = $(this).text().toLowerCase();
                    if (text.indexOf(searchTerm) !== -1) {
                        $(this).show();
                        $(this).prop('disabled', false);
                    } else {
                        $(this).hide();
                        $(this).prop('disabled', true);
                    }
                });
            });
            
            // 结构化解释中的成语搜索功能
            $(document).on('keyup', '.idiom-search-in-structured', function() {
                var searchTerm = $(this).val().toLowerCase();
                $(this).siblings('select').find('option').each(function() {
                    var text = $(this).text().toLowerCase();
                    if (text.indexOf(searchTerm) !== -1) {
                        $(this).show();
                        $(this).prop('disabled', false);
                    } else {
                        $(this).hide();
                        $(this).prop('disabled', true);
                    }
                });
            });
            
            // 结构化解释中的同义字词搜索功能
            $(document).on('keyup', '.synonymous-characters-search', function() {
                var searchTerm = $(this).val().toLowerCase();
                $(this).siblings('select').find('option').each(function() {
                    var text = $(this).text().toLowerCase();
                    if (text.indexOf(searchTerm) !== -1) {
                        $(this).show();
                        $(this).prop('disabled', false);
                    } else {
                        $(this).hide();
                        $(this).prop('disabled', true);
                    }
                });
            });
            
            // 结构化解释中的近义字词搜索功能
            $(document).on('keyup', '.similar-characters-search', function() {
                var searchTerm = $(this).val().toLowerCase();
                $(this).siblings('select').find('option').each(function() {
                    var text = $(this).text().toLowerCase();
                    if (text.indexOf(searchTerm) !== -1) {
                        $(this).show();
                        $(this).prop('disabled', false);
                    } else {
                        $(this).hide();
                        $(this).prop('disabled', true);
                    }
                });
            });
            
            // 结构化解释中的反义字词搜索功能
            $(document).on('keyup', '.antonymous-characters-search', function() {
                var searchTerm = $(this).val().toLowerCase();
                $(this).siblings('select').find('option').each(function() {
                    var text = $(this).text().toLowerCase();
                    if (text.indexOf(searchTerm) !== -1) {
                        $(this).show();
                        $(this).prop('disabled', false);
                    } else {
                        $(this).hide();
                        $(this).prop('disabled', true);
                    }
                });
            });
            
            // 结构化解释中的关联内容搜索功能
            $(document).on('keyup', '.related-content-search', function() {
                var searchTerm = $(this).val().toLowerCase();
                $(this).siblings('select').find('option').each(function() {
                    var text = $(this).text().toLowerCase();
                    if (text.indexOf(searchTerm) !== -1) {
                        $(this).show();
                        $(this).prop('disabled', false);
                    } else {
                        $(this).hide();
                        $(this).prop('disabled', true);
                    }
                });
            });
        });
        </script>
        <?php
    }
    
    /**
     * 详细解释元框
     */
    public function render_detailed_explanation_meta_box($post) {
        // 获取现有数据
        $detailed_explanation = get_post_meta($post->ID, '_character_detailed_explanation', true);
        $example_usage = get_post_meta($post->ID, '_character_example_usage', true);
        $structured_explanations = get_post_meta($post->ID, '_character_structured_explanations', true);
        
        // 获取所有词语和成语用于关联选择
        $dictionaries = $this->get_words_list();
        $idioms = $this->get_idioms_list();
        
        // 获取所有汉字用于同义字词和近义字词选择
        $characters = get_posts(array(
            'post_type' => 'chinese_character',
            'post_status' => 'publish',
            'numberposts' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        // 确保结构化解释是数组
        if (empty($structured_explanations) || !is_array($structured_explanations)) {
            $structured_explanations = array(
                array(
                    'part_of_speech' => '',
                    'explanation' => '',
                    'example_sentences' => '',
                    'custom_fields' => array(),
                    'related_dictionaries' => array(),
                    'related_idioms' => array(),
                    'synonymous_characters' => array(),
                    'similar_characters' => array()
                )
            );
        } else {
            // 确保每个结构化解释项都有所有必要的键
            foreach ($structured_explanations as $key => $exp) {
                if (!is_array($exp)) {
                    $structured_explanations[$key] = array(
                        'part_of_speech' => '',
                        'explanation' => '',
                        'example_sentences' => '',
                        'custom_fields' => array(),
                        'synonymous_characters' => '',
                        'similar_characters' => '',
                        'related_dictionaries' => array(),
                        'related_idioms' => array()
                    );
                } else {
                    // 确保所有必要的键都存在
                    $exp = wp_parse_args($exp, array(
                        'part_of_speech' => '',
                        'explanation' => '',
                        'example_sentences' => '',
                        'custom_fields' => array(),
                        'related_dictionaries' => array(),
                        'related_idioms' => array(),
                        'synonymous_characters' => array(),
                        'similar_characters' => array()
                    ));
                    $structured_explanations[$key] = $exp;
                }
            }
        }
        
        ?>
        ?>
        <table class="form-table">
            <tr>
                <th><label for="character_example_usage">使用示例</label></th>
                <td>
                    <textarea id="character_example_usage" name="character_example_usage" rows="5" cols="50" class="large-text"><?php echo esc_textarea($example_usage); ?></textarea>
                    <p class="description">输入汉字在实际语境中的使用示例，每行一个</p>
                </td>
            </tr>
            
            <tr>
                <th><label>结构化解释</label></th>
                <td>
                    <div id="structured-explanations-container">
                        <?php foreach ($structured_explanations as $index => $exp): ?>
                            <div class="structured-explanation-item" style="border: 1px solid #ddd; padding: 10px; margin-bottom: 10px;">
                                <h4>解释项 #<?php echo $index + 1; ?> <button type="button" class="button remove-structured-explanation" style="float: right;">删除</button></h4>
                                <div style="clear: both;">
                                    <p>
                                        <label>拼音:</label><br>
                                        <select name="structured_explanations[<?php echo $index; ?>][pinyin][]" class="regular-text pinyin-select" multiple size="8">
                                            <option value="">请选择拼音（可多选）</option>
                                            <?php 
                                            // 正确处理拼音数组
                                            $selected_pinyins = array();
                                            if (isset($exp['pinyin'])) {
                                                if (is_array($exp['pinyin'])) {
                                                    $selected_pinyins = $exp['pinyin'];
                                                } else if (!empty($exp['pinyin'])) {
                                                    // 如果是字符串，按空格分割
                                                    $selected_pinyins = preg_split('/\s+/', $exp['pinyin'], -1, PREG_SPLIT_NO_EMPTY);
                                                }
                                            }
                                            
                                            foreach ($this->pinyin_list as $p): ?>
                                                <option value="<?php echo esc_attr($p); ?>" <?php echo in_array($p, $selected_pinyins) ? 'selected' : ''; ?>><?php echo esc_html($p); ?></option>
                                            <?php endforeach; ?>
                                            
                                            <?php 
                                            // 添加自定义拼音选项
                                            $custom_pinyin = get_option('chinese_character_custom_pinyin', array());
                                            if (!empty($custom_pinyin)): ?>
                                                <optgroup label="自定义拼音">
                                                    <?php foreach ($custom_pinyin as $cp): ?>
                                                        <option value="<?php echo esc_attr($cp); ?>" <?php echo in_array($cp, $selected_pinyins) ? 'selected' : ''; ?>><?php echo esc_html($cp); ?></option>
                                                    <?php endforeach; ?>
                                                </optgroup>
                                            <?php endif; ?>
                                        </select>
                                        <p class="description">在上方输入框中输入拼音可搜索过滤选项，按住 Ctrl 键可选择多个拼音（Windows）或按住 Cmd 键选择多个拼音（Mac）</p>
                                        
                                        <?php 
                                        // 将存储的拼音数组转换为字符串
                                        $pinyin_custom_value = '';
                                        if (!empty($selected_pinyins)) {
                                            $pinyin_custom_value = implode(' ', $selected_pinyins);
                                        }
                                        ?>
                                        <label for="structured_explanations_<?php echo $index; ?>_pinyin_custom">或输入自定义拼音</label>
                                        <input type="text" id="structured_explanations_<?php echo $index; ?>_pinyin_custom" name="structured_explanations[<?php echo $index; ?>][pinyin_custom]" value="<?php echo esc_attr($pinyin_custom_value); ?>" class="regular-text" />
                                        <p class="description">如果拼音列表中没有，请在此输入完整拼音，例如：yī fān fēng shùn</p>
                                    </p>
                                    <p>
                                        <?php 
                                        // 获取当前解释项的音频ID
                                        $audio_id = isset($exp['audio']) ? $exp['audio'] : '';
                                        $audio_url = $audio_id ? wp_get_attachment_url($audio_id) : '';
                                        ?>
                                        <label>语音:</label><br>
                                        <input type="hidden" class="audio-id" name="structured_explanations[<?php echo $index; ?>][audio]" value="<?php echo esc_attr($audio_id); ?>">
                                        <div class="audio-preview">
                                            <?php if ($audio_url): ?>
                                                <audio controls style="width: 100%;">
                                                    <source src="<?php echo esc_url($audio_url); ?>" type="audio/mpeg">
                                                    您的浏览器不支持音频播放。
                                                </audio>
                                            <?php endif; ?>
                                        </div>
                                        <button type="button" class="button upload-audio-button">上传音频</button>
                                        <button type="button" class="button remove-audio-button" <?php echo !$audio_id ? 'style="display:none;"' : ''; ?>>移除音频</button>
                                        <p class="description">为这个解释项上传语音文件</p>
                                    </p>
                                    <p>
                                        <label>词性:</label><br>
                                        <select name="structured_explanations[<?php echo $index; ?>][part_of_speech]" class="regular-text">
                                            <option value="">请选择词性</option>
                                            <?php 
                                            $common_parts_of_speech = array(
                                                '名词' => '名词',
                                                '动词' => '动词',
                                                '形容词' => '形容词',
                                                '副词' => '副词',
                                                '代词' => '代词',
                                                '数词' => '数词',
                                                '量词' => '量词',
                                                '介词' => '介词',
                                                '连词' => '连词',
                                                '助词' => '助词',
                                                '叹词' => '叹词',
                                                '拟声词' => '拟声词',
                                                '成语' => '成语',
                                                '惯用语' => '惯用语',
                                                '歇后语' => '歇后语',
                                                '谚语' => '谚语'
                                            );
                                            foreach ($common_parts_of_speech as $pos_key => $pos_value): ?>
                                                <option value="<?php echo esc_attr($pos_key); ?>" <?php selected($pos_key, isset($exp['part_of_speech']) ? $exp['part_of_speech'] : ''); ?>><?php echo esc_html($pos_value); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </p>
                                    <p>
                                        <label>方言类别:</label><br>
                                        <?php
                                        // 定义中国主要方言区及代表城市
                                        $chinese_dialects = array(
                                            '北方方言(官话)' => array(
                                                '北京话' => '北京',
                                                '东北话' => '东北',
                                                '冀鲁官话' => '河北/山东',
                                                '胶辽官话' => '山东/辽宁',
                                                '中原官话' => '河南/陕西/山西/甘肃',
                                                '兰银官话' => '甘肃/宁夏/青海/新疆',
                                                '江淮官话' => '江苏/安徽',
                                                '西南官话' => '四川/重庆/云南/贵州/广西/湖北'
                                            ),
                                            '晋语' => array(
                                                '并州片' => '山西太原',
                                                '吕梁片' => '山西吕梁',
                                                '上党片' => '山西长治',
                                                '五台片' => '山西忻州',
                                                '邯新片' => '河北邯郸/河南新乡',
                                                '大包片' => '内蒙古包头/山西大同'
                                            ),
                                            '吴语' => array(
                                                '太湖片' => '上海/江苏苏州/浙江杭州',
                                                '台州片' => '浙江台州',
                                                '瓯江片' => '浙江温州',
                                                '婺州片' => '浙江金华',
                                                '处衢片' => '浙江衢州/丽水',
                                                '宣州片' => '安徽宣城'
                                            ),
                                            '徽语' => array(
                                                '绩歙片' => '安徽绩溪/歙县',
                                                '休黟片' => '安徽休宁/黟县',
                                                '祁婺片' => '安徽祁门/江西婺源',
                                                '旌占片' => '安徽旌德/黟县',
                                                '严州片' => '浙江建德'
                                            ),
                                            '赣语' => array(
                                                '昌都片' => '江西南昌',
                                                '鹰弋片' => '江西鹰潭/弋阳',
                                                '大通片' => '江西九江/湖北',
                                                '甬江片' => '江西鹰潭/浙江宁波',
                                                '洞绥片' => '湖南洞口/绥宁',
                                                '宜浏片' => '江西宜春/湖南浏阳',
                                                '吉茶片' => '江西吉安/湖南茶陵'
                                            ),
                                            '湘语' => array(
                                                '长益片' => '湖南长沙/益阳',
                                                '娄邵片' => '湖南娄底/邵阳',
                                                '辰溆片' => '湖南怀化/溆浦',
                                                '衡州片' => '湖南衡阳',
                                                '永州片' => '湖南永州'
                                            ),
                                            '闽语' => array(
                                                '闽南语' => '福建厦门/泉州/漳州',
                                                '闽东语' => '福建福州',
                                                '闽北语' => '福建南平',
                                                '闽中语' => '福建三明',
                                                '莆仙语' => '福建莆田',
                                                '海南话' => '海南',
                                                '雷州话' => '广东雷州'
                                            ),
                                            '粤语' => array(
                                                '广府话' => '广东广州',
                                                '四邑话' => '广东江门',
                                                '高阳话' => '广东阳江',
                                                '吴化话' => '广东湛江',
                                                '邕浔粤语' => '广西南宁/柳州',
                                                '勾漏粤语' => '广西玉林/贵港',
                                                '四色话' => '广西贺州'
                                            ),
                                            '客家话' => array(
                                                '粤台片' => '广东梅州',
                                                '海陆片' => '广东汕尾/台湾',
                                                '客家话' => '福建长汀/江西',
                                                '宁龙片' => '江西赣州/福建',
                                                '于桂片' => '江西于都/广西'
                                            ),
                                            '平话' => array(
                                                '桂北平话' => '广西桂林',
                                                '桂南平话' => '广西南宁'
                                            )
                                        );
                                        
                                        // 中国省份列表
                                        $provinces = array(
                                            '北京市' => '北京',
                                            '天津市' => '天津',
                                            '河北省' => '河北',
                                            '山西省' => '山西',
                                            '内蒙古自治区' => '内蒙古',
                                            '辽宁省' => '辽宁',
                                            '吉林省' => '吉林',
                                            '黑龙江省' => '黑龙江',
                                            '上海市' => '上海',
                                            '江苏省' => '江苏',
                                            '浙江省' => '浙江',
                                            '安徽省' => '安徽',
                                            '福建省' => '福建',
                                            '江西省' => '江西',
                                            '山东省' => '山东',
                                            '河南省' => '河南',
                                            '湖北省' => '湖北',
                                            '湖南省' => '湖南',
                                            '广东省' => '广东',
                                            '广西壮族自治区' => '广西',
                                            '海南省' => '海南',
                                            '重庆市' => '重庆',
                                            '四川省' => '四川',
                                            '贵州省' => '贵州',
                                            '云南省' => '云南',
                                            '西藏自治区' => '西藏',
                                            '陕西省' => '陕西',
                                            '甘肃省' => '甘肃',
                                            '青海省' => '青海',
                                            '宁夏回族自治区' => '宁夏',
                                            '新疆维吾尔自治区' => '新疆',
                                            '台湾省' => '台湾',
                                            '香港特别行政区' => '香港',
                                            '澳门特别行政区' => '澳门'
                                        );
                                        
                                        // 主要城市列表（按省份分组）
                                        $cities = array(
                                            '北京市' => array('北京市'),
                                            '天津市' => array('天津市'),
                                            '河北省' => array('石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市', '保定市', '张家口市', '承德市', '沧州市', '廊坊市', '衡水市'),
                                            '山西省' => array('太原市', '大同市', '阳泉市', '长治市', '晋城市', '朔州市', '晋中市', '运城市', '忻州市', '临汾市', '吕梁市'),
                                            '内蒙古自治区' => array('呼和浩特市', '包头市', '乌海市', '赤峰市', '通辽市', '鄂尔多斯市', '呼伦贝尔市', '巴彦淖尔市', '乌兰察布市'),
                                            '辽宁省' => array('沈阳市', '大连市', '鞍山市', '抚顺市', '本溪市', '丹东市', '锦州市', '营口市', '阜新市', '辽阳市', '盘锦市', '铁岭市', '朝阳市', '葫芦岛市'),
                                            '吉林省' => array('长春市', '吉林市', '四平市', '辽源市', '通化市', '白山市', '松原市', '白城市'),
                                            '黑龙江省' => array('哈尔滨市', '齐齐哈尔市', '鸡西市', '鹤岗市', '双鸭山市', '大庆市', '伊春市', '佳木斯市', '七台河市', '牡丹江市', '黑河市', '绥化市'),
                                            '上海市' => array('上海市'),
                                            '江苏省' => array('南京市', '无锡市', '徐州市', '常州市', '苏州市', '南通市', '连云港市', '淮安市', '盐城市', '扬州市', '镇江市', '泰州市', '宿迁市'),
                                            '浙江省' => array('杭州市', '宁波市', '温州市', '嘉兴市', '湖州市', '绍兴市', '金华市', '衢州市', '舟山市', '台州市', '丽水市'),
                                            '安徽省' => array('合肥市', '芜湖市', '蚌埠市', '淮南市', '马鞍山市', '淮北市', '铜陵市', '安庆市', '黄山市', '滁州市', '阜阳市', '宿州市', '六安市', '亳州市', '池州市', '宣城市'),
                                            '福建省' => array('福州市', '厦门市', '莆田市', '三明市', '泉州市', '漳州市', '南平市', '龙岩市', '宁德市'),
                                            '江西省' => array('南昌市', '景德镇市', '萍乡市', '九江市', '新余市', '鹰潭市', '赣州市', '吉安市', '宜春市', '抚州市', '上饶市'),
                                            '山东省' => array('济南市', '青岛市', '淄博市', '枣庄市', '东营市', '烟台市', '潍坊市', '济宁市', '泰安市', '威海市', '日照市', '临沂市', '德州市', '聊城市', '滨州市', '菏泽市'),
                                            '河南省' => array('郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '濮阳市', '许昌市', '漯河市', '三门峡市', '南阳市', '商丘市', '信阳市', '周口市', '驻马店市'),
                                            '湖北省' => array('武汉市', '黄石市', '十堰市', '宜昌市', '襄阳市', '鄂州市', '荆门市', '孝感市', '荆州市', '黄冈市', '咸宁市', '随州市'),
                                            '湖南省' => array('长沙市', '株洲市', '湘潭市', '衡阳市', '邵阳市', '岳阳市', '常德市', '张家界市', '益阳市', '郴州市', '永州市', '怀化市', '娄底市'),
                                            '广东省' => array('广州市', '韶关市', '深圳市', '珠海市', '汕头市', '佛山市', '江门市', '湛江市', '茂名市', '肇庆市', '惠州市', '梅州市', '汕尾市', '河源市', '阳江市', '清远市', '东莞市', '中山市', '潮州市', '揭阳市', '云浮市'),
                                            '广西壮族自治区' => array('南宁市', '柳州市', '桂林市', '梧州市', '北海市', '防城港市', '钦州市', '贵港市', '玉林市', '百色市', '贺州市', '河池市', '来宾市', '崇左市'),
                                            '海南省' => array('海口市', '三亚市', '三沙市', '儋州市'),
                                            '重庆市' => array('重庆市'),
                                            '四川省' => array('成都市', '自贡市', '攀枝花市', '泸州市', '德阳市', '绵阳市', '广元市', '遂宁市', '内江市', '乐山市', '南充市', '眉山市', '宜宾市', '广安市', '达州市', '雅安市', '巴中市', '资阳市'),
                                            '贵州省' => array('贵阳市', '六盘水市', '遵义市', '安顺市', '毕节市', '铜仁市'),
                                            '云南省' => array('昆明市', '曲靖市', '玉溪市', '保山市', '昭通市', '丽江市', '普洱市', '临沧市'),
                                            '西藏自治区' => array('拉萨市', '日喀则市', '昌都市', '林芝市', '山南市', '那曲市', '阿里地区'),
                                            '陕西省' => array('西安市', '铜川市', '宝鸡市', '咸阳市', '渭南市', '延安市', '汉中市', '榆林市', '安康市', '商洛市'),
                                            '甘肃省' => array('兰州市', '嘉峪关市', '金昌市', '白银市', '天水市', '武威市', '张掖市', '平凉市', '酒泉市', '庆阳市', '定西市', '陇南市'),
                                            '青海省' => array('西宁市', '海东市'),
                                            '宁夏回族自治区' => array('银川市', '石嘴山市', '吴忠市', '固原市', '中卫市'),
                                            '新疆维吾尔自治区' => array('乌鲁木齐市', '克拉玛依市', '吐鲁番市', '哈密市'),
                                            '台湾省' => array('台北市', '新北市', '桃园市', '台中市', '台南市', '高雄市'),
                                            '香港特别行政区' => array('香港岛', '九龙', '新界'),
                                            '澳门特别行政区' => array('澳门半岛', '氹仔岛', '路环岛')
                                        );
                                            
                                            // 获取当前选择的方言类别
                                            $selected_dialect_region = isset($exp['dialect_region']) ? $exp['dialect_region'] : '';
                                            $selected_dialect_city = isset($exp['dialect_city']) ? $exp['dialect_city'] : '';
                                            $selected_province = isset($exp['province']) ? $exp['province'] : '';
                                            $selected_city = isset($exp['city']) ? $exp['city'] : '';
                                            ?>
                                            <select name="structured_explanations[<?php echo $index; ?>][dialect_region]" class="regular-text dialect-region-select" data-index="<?php echo $index; ?>">
                                                <option value="">请选择方言区</option>
                                                <?php foreach ($chinese_dialects as $region => $cities): ?>
                                                    <option value="<?php echo esc_attr($region); ?>" <?php selected($region, $selected_dialect_region); ?>><?php echo esc_html($region); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                            
                                            <select name="structured_explanations[<?php echo $index; ?>][dialect_city]" class="regular-text dialect-city-select" data-index="<?php echo $index; ?>">
                                                <option value="">请选择方言点</option>
                                                <?php 
                                                if (!empty($selected_dialect_region) && isset($chinese_dialects[$selected_dialect_region])) {
                                                    foreach ($chinese_dialects[$selected_dialect_region] as $city => $area): ?>
                                                        <option value="<?php echo esc_attr($city); ?>" <?php selected($city, $selected_dialect_city); ?>><?php echo esc_html($city); ?> (<?php echo esc_html($area); ?>)</option>
                                                    <?php endforeach;
                                                } ?>
                                            </select>
                                            
                                            <p class="description">选择该解释适用的方言类别</p>
                                        </p>
                                        <p>
                                            <label>省份和城市:</label><br>
                                            <select name="structured_explanations[<?php echo $index; ?>][province]" class="regular-text province-select" data-index="<?php echo $index; ?>">
                                                <option value="">请选择省份</option>
                                                <?php foreach ($provinces as $province => $abbr): ?>
                                                    <option value="<?php echo esc_attr($province); ?>" <?php selected($province, $selected_province); ?>><?php echo esc_html($province); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                            
                                            <select name="structured_explanations[<?php echo $index; ?>][city]" class="regular-text city-select" data-index="<?php echo $index; ?>" data-selected="<?php echo esc_attr($selected_city); ?>">
                                                <option value="">请选择城市</option>
                                                <?php 
                                                // 确保在编辑时正确显示已保存的城市选项
                                                if (!empty($selected_province) && isset($cities[$selected_province])) {
                                                    foreach ($cities[$selected_province] as $city): ?>
                                                        <option value="<?php echo esc_attr($city); ?>" <?php selected($city, $selected_city); ?>><?php echo esc_html($city); ?></option>
                                                    <?php endforeach;
                                                } ?>
                                            </select>
                                            
                                            <p class="description">选择该解释适用的具体省份和城市</p>
                                        </p>
                                        <p>
                                            <label>县/区和镇/街道:</label><br>
                                            <input type="text" name="structured_explanations[<?php echo $index; ?>][county]" class="regular-text" value="<?php echo isset($exp['county']) ? esc_attr($exp['county']) : ''; ?>" placeholder="请输入县/区名称" />
                                            <input type="text" name="structured_explanations[<?php echo $index; ?>][town]" class="regular-text" value="<?php echo isset($exp['town']) ? esc_attr($exp['town']) : ''; ?>" placeholder="请输入镇/街道名称" style="margin-top: 5px;" />
                                            <p class="description">输入该解释适用的具体县/区和镇/街道名称</p>
                                        </p>
                                        
                                        <!-- 关联内容 -->
                                        <p>
                                            <label>关联内容:</label><br>
                                            <input type="text" class="related-content-search" placeholder="搜索汉字、词语或成语..." style="width: 100%; margin-bottom: 5px;" data-index="<?php echo $index; ?>" />
                                            <select name="structured_explanations[<?php echo $index; ?>][related_content][]" multiple style="height: 100px; width: 100%;">
                                                <optgroup label="汉字">
                                                    <?php 
                                                    $selected_content = array();
                                                    if (isset($exp['related_content']) && is_array($exp['related_content'])) {
                                                        $selected_content = $exp['related_content'];
                                                    } else if (!empty($exp['related_content'])) {
                                                        $selected_content = explode(',', $exp['related_content']);
                                                        $selected_content = array_map('trim', $selected_content);
                                                    }
                                                    
                                                    foreach ($characters as $character): ?>
                                                        <option value="char_<?php echo esc_attr($character->ID); ?>" <?php echo in_array("char_" . $character->ID, $selected_content) ? 'selected' : ''; ?>>
                                                            <?php echo esc_html($character->post_title); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </optgroup>
                                                <optgroup label="词语">
                                                    <?php foreach ($dictionaries as $dictionary): ?>
                                                        <option value="dict_<?php echo esc_attr($dictionary->ID); ?>" <?php echo in_array("dict_" . $dictionary->ID, $selected_content) ? 'selected' : ''; ?>>
                                                            <?php echo esc_html($dictionary->post_title); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </optgroup>
                                                <optgroup label="成语">
                                                    <?php foreach ($idioms as $idiom): ?>
                                                        <option value="idiom_<?php echo esc_attr($idiom->ID); ?>" <?php echo in_array("idiom_" . $idiom->ID, $selected_content) ? 'selected' : ''; ?>>
                                                            <?php echo esc_html($idiom->post_title); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </optgroup>
                                            </select>
                                            <p class="description">选择与此解释相关的汉字、词语或成语（可多选）</p>
                                        </p>
                                        
                                        <p>
                                            <label>解释:</label><br>
                                            <textarea name="structured_explanations[<?php echo $index; ?>][explanation]" rows="5" cols="50" class="large-text" id="structured_explanations_<?php echo $index; ?>_explanation"><?php echo esc_textarea($exp['explanation']); ?></textarea>
                                        </p>
                                        
                                     
                                        <p>
                                            <label>考据:</label><br>
                                            <textarea name="structured_explanations[<?php echo $index; ?>][research]" rows="5" cols="50" class="large-text" id="structured_explanations_<?php echo $index; ?>_research"><?php echo esc_textarea(isset($exp['research']) ? $exp['research'] : ''); ?></textarea>
                                        </p>
                                        
                                    <p>
                                        <label>例句:</label><br>
                                        <textarea name="structured_explanations[<?php echo $index; ?>][example_sentences]" rows="5" cols="50" class="large-text" id="structured_explanations_<?php echo $index; ?>_example_sentences"><?php echo esc_textarea($exp['example_sentences']); ?></textarea>
                                    </p>
                                    
                                    <!-- 同义字词 -->
                                    <p>
                                        <label>同义字词:</label><br>
                                        <input type="text" class="synonymous-characters-search" placeholder="搜索同义字词..." style="width: 100%; margin-bottom: 5px;" data-index="<?php echo $index; ?>" />
                                        <select name="structured_explanations[<?php echo $index; ?>][synonymous_characters][]" multiple style="height: 100px; width: 100%;">
                                            <?php 
                                            // 获取所有汉字
                                            $characters = get_posts(array(
                                                'post_type' => 'chinese_character',
                                                'post_status' => 'publish',
                                                'numberposts' => -1,
                                                'orderby' => 'title',
                                                'order' => 'ASC'
                                            ));
                                            
                                            $selected_synonymous = array();
                                            if (isset($exp['synonymous_characters']) && is_array($exp['synonymous_characters'])) {
                                                $selected_synonymous = $exp['synonymous_characters'];
                                            } else if (!empty($exp['synonymous_characters'])) {
                                                $selected_synonymous = explode(',', $exp['synonymous_characters']);
                                                $selected_synonymous = array_map('trim', $selected_synonymous);
                                            }
                                            
                                            foreach ($characters as $character): ?>
                                                <option value="<?php echo esc_attr($character->ID); ?>" <?php echo in_array($character->ID, $selected_synonymous) ? 'selected' : ''; ?>>
                                                    <?php echo esc_html($character->post_title); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <p class="description">选择与此解释相关的同义字词（可多选）</p>
                                    </p>
                                    
                                    <!-- 近义字词 -->
                                    <p>
                                        <label>近义字词:</label><br>
                                        <input type="text" class="similar-characters-search" placeholder="搜索近义字词..." style="width: 100%; margin-bottom: 5px;" data-index="<?php echo $index; ?>" />
                                        <select name="structured_explanations[<?php echo $index; ?>][similar_characters][]" multiple style="height: 100px; width: 100%;">
                                            <?php 
                                            $selected_similar = array();
                                            if (isset($exp['similar_characters']) && is_array($exp['similar_characters'])) {
                                                $selected_similar = $exp['similar_characters'];
                                            } else if (!empty($exp['similar_characters'])) {
                                                $selected_similar = explode(',', $exp['similar_characters']);
                                                $selected_similar = array_map('trim', $selected_similar);
                                            }
                                            
                                            foreach ($characters as $character): ?>
                                                <option value="<?php echo esc_attr($character->ID); ?>" <?php echo in_array($character->ID, $selected_similar) ? 'selected' : ''; ?>>
                                                    <?php echo esc_html($character->post_title); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <p class="description">选择与此解释相关的近义字词（可多选）</p>
                                    </p>
                                    
                                    <!-- 反义字词 -->
                                    <p>
                                        <label>反义字词:</label><br>
                                        <input type="text" class="antonymous-characters-search" placeholder="搜索反义字词..." style="width: 100%; margin-bottom: 5px;" data-index="<?php echo $index; ?>" />
                                        <select name="structured_explanations[<?php echo $index; ?>][antonymous_characters][]" multiple style="height: 100px; width: 100%;">
                                            <?php 
                                            $selected_antonymous = array();
                                            if (isset($exp['antonymous_characters']) && is_array($exp['antonymous_characters'])) {
                                                $selected_antonymous = $exp['antonymous_characters'];
                                            } else if (!empty($exp['antonymous_characters'])) {
                                                $selected_antonymous = explode(',', $exp['antonymous_characters']);
                                                $selected_antonymous = array_map('trim', $selected_antonymous);
                                            }
                                            
                                            foreach ($characters as $character): ?>
                                                <option value="<?php echo esc_attr($character->ID); ?>" <?php echo in_array($character->ID, $selected_antonymous) ? 'selected' : ''; ?>>
                                                    <?php echo esc_html($character->post_title); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <p class="description">选择与此解释相关的反义字词（可多选）</p>
                                    </p>
                                    
                                    <!-- 关联词语 -->
                                    <p>
                                        <label>关联词语:</label><br>
                                        <input type="text" class="dictionary-search-in-structured" placeholder="搜索词语..." style="width: 100%; margin-bottom: 5px;" data-index="<?php echo $index; ?>" />
                                        <select name="structured_explanations[<?php echo $index; ?>][related_dictionaries][]" multiple style="height: 100px; width: 100%;">
                                            <?php 
                                            $selected_dictionaries = array();
                                            if (isset($exp['related_dictionaries']) && is_array($exp['related_dictionaries'])) {
                                                $selected_dictionaries = $exp['related_dictionaries'];
                                            } else if (!empty($exp['related_dictionaries'])) {
                                                $selected_dictionaries = explode(',', $exp['related_dictionaries']);
                                                $selected_dictionaries = array_map('trim', $selected_dictionaries);
                                            }
                                            
                                            foreach ($dictionaries as $dictionary): ?>
                                                <option value="<?php echo esc_attr($dictionary->ID); ?>" <?php echo in_array($dictionary->ID, $selected_dictionaries) ? 'selected' : ''; ?>>
                                                    <?php echo esc_html($dictionary->post_title); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <p class="description">选择与此解释相关的词语（可多选）</p>
                                    </p>
                                    
                                    <!-- 关联成语 -->
                                    <p>
                                        <label>关联成语:</label><br>
                                        <input type="text" class="idiom-search-in-structured" placeholder="搜索成语..." style="width: 100%; margin-bottom: 5px;" data-index="<?php echo $index; ?>" />
                                        <select name="structured_explanations[<?php echo $index; ?>][related_idioms][]" multiple style="height: 100px; width: 100%;">
                                            <?php 
                                            $selected_idioms = array();
                                            if (isset($exp['related_idioms']) && is_array($exp['related_idioms'])) {
                                                $selected_idioms = $exp['related_idioms'];
                                            } else if (!empty($exp['related_idioms'])) {
                                                $selected_idioms = explode(',', $exp['related_idioms']);
                                                $selected_idioms = array_map('trim', $selected_idioms);
                                            }
                                            
                                            foreach ($idioms as $idiom): ?>
                                                <option value="<?php echo esc_attr($idiom->ID); ?>" <?php echo in_array($idiom->ID, $selected_idioms) ? 'selected' : ''; ?>>
                                                    <?php echo esc_html($idiom->post_title); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <p class="description">选择与此解释相关的成语（可多选）</p>
                                    </p>
                                    
                                    <!-- 关联内容（汉字、词语、成语） -->
                                    <p>
                                        <label>关联内容:</label><br>
                                        <input type="text" class="related-content-search" placeholder="搜索汉字、词语或成语..." style="width: 100%; margin-bottom: 5px;" data-index="<?php echo $index; ?>" />
                                        <select name="structured_explanations[<?php echo $index; ?>][related_content][]" multiple style="height: 100px; width: 100%;">
                                            <optgroup label="汉字">
                                                <?php 
                                                $selected_content = array();
                                                if (isset($exp['related_content']) && is_array($exp['related_content'])) {
                                                    $selected_content = $exp['related_content'];
                                                } else if (!empty($exp['related_content'])) {
                                                    $selected_content = explode(',', $exp['related_content']);
                                                    $selected_content = array_map('trim', $selected_content);
                                                }
                                                
                                                foreach ($characters as $character): ?>
                                                    <option value="char_<?php echo esc_attr($character->ID); ?>" <?php echo in_array("char_" . $character->ID, $selected_content) ? 'selected' : ''; ?>>
                                                        <?php echo esc_html($character->post_title); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </optgroup>
                                            <optgroup label="词语">
                                                <?php foreach ($dictionaries as $dictionary): ?>
                                                    <option value="dict_<?php echo esc_attr($dictionary->ID); ?>" <?php echo in_array("dict_" . $dictionary->ID, $selected_content) ? 'selected' : ''; ?>>
                                                        <?php echo esc_html($dictionary->post_title); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </optgroup>
                                            <optgroup label="成语">
                                                <?php foreach ($idioms as $idiom): ?>
                                                    <option value="idiom_<?php echo esc_attr($idiom->ID); ?>" <?php echo in_array("idiom_" . $idiom->ID, $selected_content) ? 'selected' : ''; ?>>
                                                        <?php echo esc_html($idiom->post_title); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </optgroup>
                                            <optgroup label="成语">
                                                <?php foreach ($idioms as $idiom): ?>
                                                    <option value="idiom_<?php echo esc_attr($idiom->ID); ?>" <?php echo in_array("idiom_" . $idiom->ID, $selected_content) ? 'selected' : ''; ?>>
                                                        <?php echo esc_html($idiom->post_title); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </optgroup>
                                        </select>
                                        <p class="description">选择与此解释相关的汉字、词语或成语（可多选）</p>
                                    </p>
                                    
                                    <!-- 自定义字段部分 -->
                                    <div class="custom-fields-container" data-index="<?php echo $index; ?>">
                                        <h5>自定义字段 <button type="button" class="button add-custom-field" style="font-size: 12px;">添加字段</button></h5>
                                        <?php if (isset($exp['custom_fields']) && is_array($exp['custom_fields'])): ?>
                                            <?php foreach ($exp['custom_fields'] as $cf_index => $custom_field): ?>
                                                <div class="custom-field-item" style="margin-bottom: 10px; padding: 5px; background: #f5f5f5;">
                                                    <input type="text" name="structured_explanations[<?php echo $index; ?>][custom_fields][<?php echo $cf_index; ?>][label]" value="<?php echo esc_attr($custom_field['label']); ?>" placeholder="字段标签" style="width: 30%;" />
                                                    <input type="text" name="structured_explanations[<?php echo $index; ?>][custom_fields][<?php echo $cf_index; ?>][value]" value="<?php echo esc_attr($custom_field['value']); ?>" placeholder="字段值" style="width: 50%;" />
                                                    <button type="button" class="button remove-custom-field" style="font-size: 12px;">删除</button>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <button type="button" class="button" id="add-structured-explanation">添加结构化解释</button>
                    
                    <script type="text/javascript">
                    jQuery(document).ready(function($) {
                        // 初始化拼音选择器
                        function initializePinyinSelectors() {
                            $('.pinyin-select').each(function() {
                                var $select = $(this);
                                // 清除提示选项的选中状态
                                $select.find('option[value=""]').prop('selected', false);
                                
                                // 检查是否已经初始化
                                if (!$select.hasClass('select2-hidden-accessible')) {
                                    $select.select2({
                                        placeholder: "搜索并选择拼音...",
                                        allowClear: true,
                                        width: '100%',
                                        // 保持搜索结果中已选项目在前面
                                        sorter: function(data) {
                                            var selectedIds = [];
                                            $select.find(':selected').each(function() {
                                                selectedIds.push($(this).val());
                                            });
                                            
                                            return data.sort(function(a, b) {
                                                var aSelected = selectedIds.indexOf(a.id) !== -1;
                                                var bSelected = selectedIds.indexOf(b.id) !== -1;
                                                
                                                if (aSelected && !bSelected) return -1;
                                                if (!aSelected && bSelected) return 1;
                                                return 0;
                                            });
                                        }
                                    }).on("select2:select", function (evt) {
                                        // 移除空选项的selected状态
                                        $select.find('option[value=""]').prop('selected', false);
                                        
                                        // 将新选择的项移到最后
                                        var element = evt.params.data.element;
                                        var $element = $(element);
                                        
                                        $element.detach();
                                        $select.append($element);
                                        $select.trigger("change");
                                    });
                                }
                            });
                        }
                        
                        // 将textarea转换为wp编辑器
                        function convertToEditor(textareaId) {
                            if (typeof tinymce !== 'undefined') {
                                var textarea = $('#' + textareaId);
                                if (textarea.length && textarea.hasClass('large-text')) {
                                    var editorId = textarea.attr('id');
                                    // 检查编辑器是否已经存在
                                    if (tinymce.get(editorId) === null) {
                                        var settings = {
                                            quicktags: true,
                                            toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                                            toolbar2: 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table',
                                            plugins: 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media,insertdatetime,visualblocks',
                                            menubar: true,
                                            statusbar: true
                                        };
                                        // 初始化TinyMCE
                                        tinymce.init({
                                            selector: '#' + editorId,
                                            plugins: settings.plugins,
                                            toolbar1: settings.toolbar1,
                                            toolbar2: settings.toolbar2,
                                            menubar: settings.menubar,
                                            statusbar: settings.statusbar,
                                            relative_urls: false,
                                            remove_script_host: false,
                                            convert_urls: false,
                                            height: 200,
                                            setup: function(editor) {
                                                editor.on('change keyup NodeChange', function() {
                                                    editor.save();
                                                });
                                            }
                                        });
                                    }
                                }
                            }
                        }
                        
                        // 页面加载完成后初始化
                        initializePinyinSelectors();
                        
                        // 初始化已存在的音频控件
                        $('.structured-explanation-item').each(function() {
                            var container = $(this);
                            var audioId = container.find('.audio-id').val();
                            if (audioId) {
                                container.find('.remove-audio-button').show();
                            }
                        });
                        
                        // 监听WordPress后台元框切换事件
                        $(document).on('postbox-toggled', function(event, postbox) {
                            if ($(postbox).attr('id') === 'structured-explanations') {
                                initializeExistingEditors();
                            }
                        });
                        
                        // 页面加载完成后初始化现有编辑器
                        function initializeExistingEditors() {
                            // 遍历所有现有的结构化解释项
                            $('.structured-explanation-item').each(function() {
                                var itemIndex = $(this).find('[data-index]').data('index');
                                if (typeof itemIndex !== 'undefined') {
                                    // 初始化解释编辑器
                                    var explanationId = 'structured_explanation_' + itemIndex + '_explanation';
                                    var explanationContent = $(this).find('textarea[name="structured_explanations[' + itemIndex + '][explanation]"]').val();
                                    if (typeof tinymce !== 'undefined' && $('#' + explanationId).length > 0) {
                                        tinymce.init({
                                            selector: '#' + explanationId,
                                            plugins: 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media,emoticons,insertdatetime,visualblocks',
                                            toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                                            toolbar2: 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table',
                                            menubar: true,
                                            statusbar: true,
                                            height: 200,
                                            setup: function(editor) {
                                                // 设置初始内容
                                                editor.on('init', function() {
                                                    editor.setContent(explanationContent || '');
                                                });
                                                editor.on('change keyup NodeChange', function() {
                                                    var content = editor.getContent();
                                                    $('textarea[name="structured_explanations[' + itemIndex + '][explanation]"]').val(content);
                                                });
                                            }
                                        });
                                    }
                                    
                                    // 初始化例句编辑器
                                    var exampleId = 'structured_explanation_' + itemIndex + '_example_sentences';
                                    var exampleContent = $(this).find('textarea[name="structured_explanations[' + itemIndex + '][example_sentences]"]').val();
                                    if (typeof tinymce !== 'undefined' && $('#' + exampleId).length > 0) {
                                        tinymce.init({
                                            selector: '#' + exampleId,
                                            plugins: 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media,emoticons,insertdatetime,visualblocks',
                                            toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                                            toolbar2: 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table',
                                            menubar: true,
                                            statusbar: true,
                                            height: 200,
                                            setup: function(editor) {
                                                // 设置初始内容
                                                editor.on('init', function() {
                                                    editor.setContent(exampleContent || '');
                                                });
                                                editor.on('change keyup NodeChange', function() {
                                                    var content = editor.getContent();
                                                    $('textarea[name="structured_explanations[' + itemIndex + '][example_sentences]"]').val(content);
                                                });
                                            }
                                        });
                                    }
                                    
                                    // 初始化考据编辑器
                                    var researchId = 'structured_explanation_' + itemIndex + '_research';
                                    var researchContent = $(this).find('textarea[name="structured_explanations[' + itemIndex + '][research]"]').val();
                                    if (typeof tinymce !== 'undefined' && $('#' + researchId).length > 0) {
                                        tinymce.init({
                                            selector: '#' + researchId,
                                            plugins: 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media,emoticons,insertdatetime,visualblocks',
                                            toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                                            toolbar2: 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table',
                                            menubar: true,
                                            statusbar: true,
                                            height: 200,
                                            setup: function(editor) {
                                                // 设置初始内容
                                                editor.on('init', function() {
                                                    editor.setContent(researchContent || '');
                                                });
                                                editor.on('change keyup NodeChange', function() {
                                                    var content = editor.getContent();
                                                    $('textarea[name="structured_explanations[' + itemIndex + '][research]"]').val(content);
                                                });
                                            }
                                        });
                                    }
                                }
                            });
                        }
                        
                        // 页面加载完成后初始化
                        initializePinyinSelectors();
                        
                        // 监听WordPress后台元框切换事件
                        $(document).on('postbox-toggled', function() {
                            setTimeout(function() {
                                initializePinyinSelectors();
                                // 重新初始化可见的编辑器
                                $('[id^=structured_explanations_][id$=_explanation]:visible, [id^=structured_explanations_][id$=_example_sentences]:visible, [id^=structured_explanations_][id$=_research]:visible').each(function() {
                                    var id = $(this).attr('id');
                                    if (typeof tinymce !== 'undefined' && !tinymce.get(id)) {
                                        convertToEditor(id);
                                    }
                                });
                            }, 100);
                        });
                        
                        // 在窗口加载时再次初始化以确保所有元素都已加载
                        $(window).on('load', function() {
                            setTimeout(function() {
                                initializePinyinSelectors();
                                
                                // 确保所有编辑器都正确初始化
                                $('[id^=structured_explanations_][id$=_explanation], [id^=structured_explanations_][id$=_example_sentences], [id^=structured_explanations_][id$=_research]').each(function() {
                                    var id = $(this).attr('id');
                                    if (typeof tinymce !== 'undefined' && !tinymce.get(id)) {
                                        convertToEditor(id);
                                    }
                                });
                            }, 500);
                        });
                        
                        // 音频上传功能
                        var mediaUploader;
                        
                        // 上传音频按钮点击事件
                        $(document).on('click', '.upload-audio-button', function(e) {
                            e.preventDefault();
                            
                            var button = $(this);
                            var container = button.closest('.structured-explanation-item');
                            
                            // 创建或重用媒体上传器
                            if (mediaUploader) {
                                mediaUploader.open();
                                return;
                            }
                            
                            // 扩展默认的wp.media对象以只显示音频文件
                            mediaUploader = wp.media({
                                title: '选择或上传音频',
                                button: {
                                    text: '使用此音频'
                                },
                                library: {
                                    type: 'audio'
                                },
                                multiple: false
                            });
                            
                            // 当选择媒体文件时
                            mediaUploader.on('select', function() {
                                var attachment = mediaUploader.state().get('selection').first().toJSON();
                                
                                // 设置音频ID到隐藏字段
                                container.find('.audio-id').val(attachment.id);
                                
                                // 显示音频预览
                                var audioPreview = container.find('.audio-preview');
                                audioPreview.html('<audio controls style="width: 100%;"><source src="' + attachment.url + '" type="audio/mpeg">您的浏览器不支持音频播放。</audio>');
                                
                                // 显示移除按钮
                                container.find('.remove-audio-button').show();
                            });
                            
                            // 打开媒体上传器
                            mediaUploader.open();
                        });
                        
                        // 移除音频按钮点击事件
                        $(document).on('click', '.remove-audio-button', function(e) {
                            e.preventDefault();
                            
                            var container = $(this).closest('.structured-explanation-item');
                            
                            // 清空音频ID
                            container.find('.audio-id').val('');
                            
                            // 清空音频预览
                            container.find('.audio-preview').empty();
                            
                            // 隐藏移除按钮
                            $(this).hide();
                        });
                        
                        // 初始化已存在的音频控件
                        $('.structured-explanation-item').each(function() {
                            var container = $(this);
                            var audioId = container.find('.audio-id').val();
                            if (audioId) {
                                container.find('.remove-audio-button').show();
                            }
                        });
                        
                        // 监听添加结构化解释项的事件
                        $(document).on('click', '.add-structured-explanation', function() {
                            var index = $('.structured-explanation').length;
                            var template = $('#structured-explanation-template').html();
                            template = template.replace(/__INDEX__/g, index);
                            $('.structured-explanations').append(template);
                            
                            // 获取词语、成语和汉字选项
                            var dictionaryOptions = '';
                            var idiomOptions = '';
                            var characterOptions = '';
                            
                            <?php foreach ($dictionaries as $dictionary): ?>
                                dictionaryOptions += '<option value="<?php echo esc_attr($dictionary->ID); ?>"><?php echo esc_js($dictionary->post_title); ?></option>';
                            <?php endforeach; ?>
                            
                            <?php foreach ($idioms as $idiom): ?>
                                idiomOptions += '<option value="<?php echo esc_attr($idiom->ID); ?>"><?php echo esc_js($idiom->post_title); ?></option>';
                            <?php endforeach; ?>
                            
                            <?php foreach ($characters as $character): ?>
                                characterOptions += '<option value="<?php echo esc_attr($character->ID); ?>"><?php echo esc_js($character->post_title); ?></option>';
                            <?php endforeach; ?>
                            
                            // 为新添加的结构化解释项初始化富文本编辑器
                            setTimeout(function() {
                                // 初始化解释编辑器
                                if (typeof wp !== 'undefined' && wp.editor && wp.editor.initialize) {
                                    wp.editor.initialize('structured_explanations_' + index + '_explanation', {
                                        tinymce: {
                                            plugins: 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media,emoticons,insertdatetime,visualblocks',
                                            toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                                            toolbar2: 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table'
                                        },
                                        quicktags: true,
                                        mediaButtons: true
                                    });
                                }
                                
                                // 初始化例句编辑器
                                if (typeof wp !== 'undefined' && wp.editor && wp.editor.initialize) {
                                    wp.editor.initialize('structured_explanations_' + index + '_example_sentences', {
                                        tinymce: {
                                            plugins: 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media,emoticons,insertdatetime,visualblocks',
                                            toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                                            toolbar2: 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table'
                                        },
                                        quicktags: true,
                                        mediaButtons: true
                                    });
                                }
                                
                                // 初始化考据编辑器
                                if (typeof wp !== 'undefined' && wp.editor && wp.editor.initialize) {
                                    wp.editor.initialize('structured_explanations_' + index + '_research', {
                                        tinymce: {
                                            plugins: 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media,emoticons,insertdatetime,visualblocks',
                                            toolbar1: 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                                            toolbar2: 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table'
                                        },
                                        quicktags: true,
                                        mediaButtons: true
                                    });
                                }
                                
                                // 同时也要初始化quicktags（文本模式）
                                if (typeof QTags !== 'undefined') {
                                    QTags({id: 'structured_explanations_' + index + '_explanation'});
                                    QTags({id: 'structured_explanations_' + index + '_example_sentences'});
                                }
                                
                                // 确保内容同步
                                if (typeof tinymce !== 'undefined') {
                                    // 解释编辑器内容同步
                                    var explanationEditor = tinymce.get('structured_explanations_' + index + '_explanation');
                                    if (explanationEditor) {
                                        explanationEditor.on('change keyup NodeChange', function() {
                                            var content = explanationEditor.getContent();
                                            $('textarea[name="structured_explanations[' + index + '][explanation]"]').val(content).trigger('change');
                                        });
                                    }
                                    
                                    // 例句编辑器内容同步
                                    var exampleEditor = tinymce.get('structured_explanations_' + index + '_example_sentences');
                                    if (exampleEditor) {
                                        exampleEditor.on('change keyup NodeChange', function() {
                                            var content = exampleEditor.getContent();
                                            $('textarea[name="structured_explanations[' + index + '][example_sentences]"]').val(content).trigger('change');
                                        });
                                    }
                                }
                            }, 500);
                            setTimeout(function() {
                                initializePinyinSelectors();
                            }, 100);
                        });
                        
                        // 添加新的结构化解释项
                        $('#add-structured-explanation').on('click', function() {
                            var container = $('#structured-explanations-container');
                            var index = container.find('.structured-explanation-item').length;
                            
                            // 获取词语、成语和汉字选项
                            var dictionaryOptions = '';
                            var idiomOptions = '';
                            var characterOptions = '';
                            
                            <?php foreach ($dictionaries as $dictionary): ?>
                                dictionaryOptions += '<option value="<?php echo esc_attr($dictionary->ID); ?>"><?php echo esc_js($dictionary->post_title); ?></option>';
                            <?php endforeach; ?>
                            
                            <?php foreach ($idioms as $idiom): ?>
                                idiomOptions += '<option value="<?php echo esc_attr($idiom->ID); ?>"><?php echo esc_js($idiom->post_title); ?></option>';
                            <?php endforeach; ?>
                            
                            <?php foreach ($characters as $character): ?>
                                characterOptions += '<option value="<?php echo esc_attr($character->ID); ?>"><?php echo esc_js($character->post_title); ?></option>';
                            <?php endforeach; ?>
                            
                            var newItem = `
                                <div class="structured-explanation-item" style="border: 1px solid #ddd; padding: 10px; margin-bottom: 10px;">
                                    <h4>解释项 #${index + 1} <button type="button" class="button remove-structured-explanation" style="float: right;">删除</button></h4>
                                    <div style="clear: both;">
                                        <p>
                                            <label>拼音:</label><br>
                                            <select name="structured_explanations[${index}][pinyin][]" class="regular-text pinyin-select" multiple size="8">
                                                <option value="">请选择拼音（可多选）</option>
                                                <?php 
                                                foreach ($this->pinyin_list as $p): ?>
                                                    <option value="<?php echo esc_attr($p); ?>"><?php echo esc_html($p); ?></option>
                                                <?php endforeach; ?>
                                                
                                                <?php 
                                                // 添加自定义拼音选项
                                                $custom_pinyin = get_option('chinese_character_custom_pinyin', array());
                                                if (!empty($custom_pinyin)): ?>
                                                    <optgroup label="自定义拼音">
                                                        <?php foreach ($custom_pinyin as $cp): ?>
                                                            <option value="<?php echo esc_attr($cp); ?>"><?php echo esc_html($cp); ?></option>
                                                        <?php endforeach; ?>
                                                    </optgroup>
                                                <?php endif; ?>
                                            </select>
                                            <p class="description">在上方输入框中输入拼音可搜索过滤选项，按住 Ctrl 键可选择多个拼音（Windows）或按住 Cmd 键选择多个拼音（Mac）</p>
                                            
                                            <label for="structured_explanations_${index}_pinyin_custom">或输入自定义拼音</label>
                                            <input type="text" id="structured_explanations_${index}_pinyin_custom" name="structured_explanations[${index}][pinyin_custom]" value="" class="regular-text" />
                                            <p class="description">如果拼音列表中没有，请在此输入完整拼音，例如：yī fān fēng shùn</p>
                                        </p>
                                        <p>
                                            <label>语音:</label><br>
                                            <input type="hidden" class="audio-id" name="structured_explanations[${index}][audio]" value="">
                                            <div class="audio-preview"></div>
                                            <button type="button" class="button upload-audio-button">上传音频</button>
                                            <button type="button" class="button remove-audio-button" style="display:none;">移除音频</button>
                                            <p class="description">为这个解释项上传语音文件</p>
                                        </p>
                                        <p>
                                            <label>词性:</label><br>
                                            <select name="structured_explanations[${index}][part_of_speech]" class="regular-text">
                                                <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>
                                        </p>
                                        <p>
                                            <label>方言类别:</label><br>
                                            <select name="structured_explanations[${index}][dialect_region]" class="regular-text dialect-region-select" data-index="${index}">
                                                <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 name="structured_explanations[${index}][dialect_city]" class="regular-text dialect-city-select" data-index="${index}">
                                                <option value="">请选择方言点</option>
                                            </select>
                                            
                                            <p class="description">选择该解释适用的方言类别</p>
                                        </p>
                                        <p>
                                            <label>省份和城市:</label><br>
                                            <?php
                                            // 中国省份列表
                                            $provinces = array(
                                                '北京市' => '北京',
                                                '天津市' => '天津',
                                                '河北省' => '河北',
                                                '山西省' => '山西',
                                                '内蒙古自治区' => '内蒙古',
                                                '辽宁省' => '辽宁',
                                                '吉林省' => '吉林',
                                                '黑龙江省' => '黑龙江',
                                                '上海市' => '上海',
                                                '江苏省' => '江苏',
                                                '浙江省' => '浙江',
                                                '安徽省' => '安徽',
                                                '福建省' => '福建',
                                                '江西省' => '江西',
                                                '山东省' => '山东',
                                                '河南省' => '河南',
                                                '湖北省' => '湖北',
                                                '湖南省' => '湖南',
                                                '广东省' => '广东',
                                                '广西壮族自治区' => '广西',
                                                '海南省' => '海南',
                                                '重庆市' => '重庆',
                                                '四川省' => '四川',
                                                '贵州省' => '贵州',
                                                '云南省' => '云南',
                                                '西藏自治区' => '西藏',
                                                '陕西省' => '陕西',
                                                '甘肃省' => '甘肃',
                                                '青海省' => '青海',
                                                '宁夏回族自治区' => '宁夏',
                                                '新疆维吾尔自治区' => '新疆',
                                                '台湾省' => '台湾',
                                                '香港特别行政区' => '香港',
                                                '澳门特别行政区' => '澳门'
                                            );
                                            ?>
                                            <select name="structured_explanations[${index}][province]" class="regular-text province-select" data-index="${index}">
                                                <option value="">请选择省份</option>
                                                <?php foreach ($provinces as $province => $abbr): ?>
                                                    <option value="<?php echo esc_attr($province); ?>"><?php echo esc_html($province); ?></option>
                                                <?php endforeach; ?>
                                            </select>
                                            
                                            <select name="structured_explanations[${index}][city]" class="regular-text city-select" data-index="${index}">
                                                <option value="">请选择城市</option>
                                            </select>
                                            
                                            <p class="description">选择该解释适用的具体省份和城市</p>
                                        </p>
                                        <p>
                                            <label>县/区和镇/街道:</label><br>
                                            <input type="text" name="structured_explanations[${index}][county]" class="regular-text" placeholder="请输入县/区名称" />
                                            <input type="text" name="structured_explanations[${index}][town]" class="regular-text" placeholder="请输入镇/街道名称" style="margin-top: 5px;" />
                                            <p class="description">输入该解释适用的具体县/区和镇/街道名称</p>
                                        </p>
                                        
                                        <!-- 关联内容 -->
                                        <p>
                                            <label>关联内容:</label><br>
                                            <input type="text" class="related-content-search" placeholder="搜索汉字、词语或成语..." style="width: 100%; margin-bottom: 5px;" data-index="${index}" />
                                            <select name="structured_explanations[${index}][related_content][]" multiple style="height: 100px; width: 100%;">
                                                <optgroup label="汉字">
                                                    ${characterOptions}
                                                </optgroup>
                                                <optgroup label="词语">
                                                    ${dictionaryOptions}
                                                </optgroup>
                                                <optgroup label="成语">
                                                    ${idiomOptions}
                                                </optgroup>
                                            </select>
                                            <p class="description">选择与此解释相关的汉字、词语或成语（可多选）</p>
                                        </p>
                                        
                                        <p>
                                            <label>解释:</label><br>
                                            <textarea name="structured_explanations[${index}][explanation]" rows="5" cols="50" class="large-text" id="structured_explanations_${index}_explanation"></textarea>
                                        </p>
                                       
                                        <p>
                                            <label>考据:</label><br>
                                            <textarea name="structured_explanations[${index}][research]" rows="5" cols="50" class="large-text" id="structured_explanations_${index}_research"></textarea>
                                        </p>
                                        
                                        <p>
                                            <label>例句:</label><br>
                                            <textarea name="structured_explanations[${index}][example_sentences]" rows="5" cols="50" class="large-text" id="structured_explanations_${index}_example_sentences"></textarea>
                                        </p>
                                        
                                        <p>
                                            <label>同义字词:</label><br>
                                            <input type="text" class="synonymous-characters-search" placeholder="搜索同义字词..." style="width: 100%; margin-bottom: 5px;" data-index="${index}" />
                                            <select name="structured_explanations[${index}][synonymous_characters][]" multiple style="height: 100px; width: 100%;">
                                                ${characterOptions}
                                            </select>
                                            <p class="description">选择与此解释相关的同义字词（可多选）</p>
                                        </p>
                                        
                                        <!-- 近义字词 -->
                                        <p>
                                            <label>近义字词:</label><br>
                                            <input type="text" class="similar-characters-search" placeholder="搜索近义字词..." style="width: 100%; margin-bottom: 5px;" data-index="${index}" />
                                            <select name="structured_explanations[${index}][similar_characters][]" multiple style="height: 100px; width: 100%;">
                                                ${characterOptions}
                                            </select>
                                            <p class="description">选择与此解释相关的近义字词（可多选）</p>
                                        </p>
                                        
                                        <!-- 反义字词 -->
                                        <p>
                                            <label>反义字词:</label><br>
                                            <input type="text" class="antonymous-characters-search" placeholder="搜索反义字词..." style="width: 100%; margin-bottom: 5px;" data-index="${index}" />
                                            <select name="structured_explanations[${index}][antonymous_characters][]" multiple style="height: 100px; width: 100%;">
                                                ${characterOptions}
                                            </select>
                                            <p class="description">选择与此解释相关的反义字词（可多选）</p>
                                        </p>
                                        
                                        <!-- 关联词语 -->
                                        <p>
                                            <label>关联词语:</label><br>
                                            <input type="text" class="dictionary-search-in-structured" placeholder="搜索词语..." style="width: 100%; margin-bottom: 5px;" data-index="${index}" />
                                            <select name="structured_explanations[${index}][related_dictionaries][]" multiple style="height: 100px; width: 100%;">
                                                ${dictionaryOptions}
                                            </select>
                                        </p>
                                            <p class="description">选择与此解释相关的词语（可多选）</p>
                                        </p>
                                        
                                        <!-- 关联成语 -->
                                        <p>
                                            <label>关联成语:</label><br>
                                            <input type="text" class="idiom-search-in-structured" placeholder="搜索成语..." style="width: 100%; margin-bottom: 5px;" data-index="${index}" />
                                            <select name="structured_explanations[${index}][related_idioms][]" multiple style="height: 100px; width: 100%;">
                                                ${idiomOptions}
                                            </select>
                                            <p class="description">选择与此解释相关的成语（可多选）</p>
                                        </p>
                                        
                                        <!-- 自定义字段部分 -->
                                        <div class="custom-fields-container" data-index="${index}">
                                            <h5>自定义字段 <button type="button" class="button add-custom-field" style="font-size: 12px;">添加字段</button></h5>
                                        </div>
                                    </div>
                                </div>
                            `;
                            
                            container.append(newItem);
                            
                            // 初始化新添加的拼音选择框
                            initializePinyinSelectors();
                            
                            // 将新添加的textarea转换为编辑器
                            setTimeout(function() {
                                convertToEditor('structured_explanations_' + index + '_explanation');
                                convertToEditor('structured_explanations_' + index + '_example_sentences');
                                convertToEditor('structured_explanations_' + index + '_research');
                            }, 100);
                        });
                        
                        // 删除结构化解释项
                        $(document).on('click', '.remove-structured-explanation', function() {
                            if (confirm('确定要删除这个解释项吗？')) {
                                $(this).closest('.structured-explanation-item').remove();
                                
                                // 重新编号剩余的项
                                $('.structured-explanation-item').each(function(itemIndex) {
                                    $(this).find('h4').html(`解释项 #${itemIndex + 1} <button type="button" class="button remove-structured-explanation" style="float: right;">删除</button>`);
                                    
                                    // 更新索引
                                    updateFieldIndices($(this), itemIndex);
                                });
                            }
                        });
                        
                        // 添加自定义字段
                        $(document).on('click', '.add-custom-field', function() {
                            var container = $(this).closest('.custom-fields-container');
                            var itemIndex = container.data('index');
                            var customFields = container.find('.custom-field-item');
                            var fieldIndex = customFields.length;
                            
                            var customFieldHtml = `
                                <div class="custom-field-item" style="margin-bottom: 10px; padding: 5px; background: #f5f5f5;">
                                    <input type="text" name="structured_explanations[${itemIndex}][custom_fields][${fieldIndex}][label]" value="" placeholder="字段标签" style="width: 30%;" />
                                    <input type="text" name="structured_explanations[${itemIndex}][custom_fields][${fieldIndex}][value]" value="" placeholder="字段值" style="width: 50%;" />
                                    <button type="button" class="button remove-custom-field" style="font-size: 12px;">删除</button>
                                </div>
                            `;
                            
                            container.append(customFieldHtml);
                        });
                        
                        // 删除自定义字段
                        $(document).on('click', '.remove-custom-field', function() {
                            $(this).closest('.custom-field-item').remove();
                        });
                        
                        // 处理词语搜索功能
                        $(document).on('keyup', '.dictionary-search-in-structured', function() {
                            var searchTerm = $(this).val().toLowerCase();
                            var index = $(this).data('index');
                            $(this).siblings('select').children('option').each(function() {
                                var text = $(this).text().toLowerCase();
                                if (text.indexOf(searchTerm) !== -1) {
                                    $(this).show();
                                    $(this).attr('hidden', false);
                                } else {
                                    $(this).hide();
                                    $(this).attr('hidden', true);
                                }
                            });
                        });
                        
                        // 处理成语搜索功能
                        $(document).on('keyup', '.idiom-search-in-structured', function() {
                            var searchTerm = $(this).val().toLowerCase();
                            var index = $(this).data('index');
                            $(this).siblings('select').children('option').each(function() {
                                var text = $(this).text().toLowerCase();
                                if (text.indexOf(searchTerm) !== -1) {
                                    $(this).show();
                                    $(this).attr('hidden', false);
                                } else {
                                    $(this).hide();
                                    $(this).attr('hidden', true);
                                }
                            });
                        });
                        
                        // 处理同义字词搜索功能
                        $(document).on('keyup', '.synonymous-characters-search', function() {
                            var searchTerm = $(this).val().toLowerCase();
                            var index = $(this).data('index');
                            $(this).siblings('select').children('option').each(function() {
                                var text = $(this).text().toLowerCase();
                                if (text.indexOf(searchTerm) !== -1) {
                                    $(this).show();
                                    $(this).attr('hidden', false);
                                } else {
                                    $(this).hide();
                                    $(this).attr('hidden', true);
                                }
                            });
                        });
                        
                        // 处理近义字词搜索功能
                        $(document).on('keyup', '.similar-characters-search', function() {
                            var searchTerm = $(this).val().toLowerCase();
                            var index = $(this).data('index');
                            $(this).siblings('select').children('option').each(function() {
                                var text = $(this).text().toLowerCase();
                                if (text.indexOf(searchTerm) !== -1) {
                                    $(this).show();
                                    $(this).attr('hidden', false);
                                } else {
                                    $(this).hide();
                                    $(this).attr('hidden', true);
                                }
                            });
                        });
                        
                        // 处理关联内容搜索功能
                        $(document).on('keyup', '.related-content-search', function() {
                            var searchTerm = $(this).val().toLowerCase();
                            var index = $(this).data('index');
                            $(this).siblings('select').find('option').each(function() {
                                var text = $(this).text().toLowerCase();
                                if (text.indexOf(searchTerm) !== -1) {
                                    $(this).show();
                                    $(this).attr('hidden', false);
                                } else {
                                    $(this).hide();
                                    $(this).attr('hidden', true);
                                }
                            });
                        });
                        
                        // 清空搜索框时显示所有选项
                        $(document).on('search', '.dictionary-search-in-structured, .idiom-search-in-structured, .synonymous-characters-search, .similar-characters-search, .related-content-search', function() {
                            if ($(this).val() === '') {
                                $(this).siblings('select').children('option').show().attr('hidden', false);
                            }
                        });
                        
                        // 方言区变化时更新城市选项
                        $(document).on('change', '.dialect-region-select', function() {
                            var region = $(this).val();
                            var index = $(this).data('index');
                            var citySelect = $(this).closest('.structured-explanation-item').find('.dialect-city-select');
                            
                            // 定义中国主要方言区及代表城市
                            var chineseDialects = {
                                '北方方言(官话)': {
                                    '北京话': '北京',
                                    '东北话': '东北',
                                    '冀鲁官话': '河北/山东',
                                    '胶辽官话': '山东/辽宁',
                                    '中原官话': '河南/陕西/山西/甘肃',
                                    '兰银官话': '甘肃/宁夏/青海/新疆',
                                    '江淮官话': '江苏/安徽',
                                    '西南官话': '四川/重庆/云南/贵州/广西/湖北'
                                },
                                '晋语': {
                                    '并州片': '山西太原',
                                    '吕梁片': '山西吕梁',
                                    '上党片': '山西长治',
                                    '五台片': '山西忻州',
                                    '邯新片': '河北邯郸/河南新乡',
                                    '大包片': '内蒙古包头/山西大同'
                                },
                                '吴语': {
                                    '太湖片': '上海/江苏苏州/浙江杭州',
                                    '台州片': '浙江台州',
                                    '瓯江片': '浙江温州',
                                    '婺州片': '浙江金华',
                                    '处衢片': '浙江衢州/丽水',
                                    '宣州片': '安徽宣城'
                                },
                                '徽语': {
                                    '绩歙片': '安徽绩溪/歙县',
                                    '休黟片': '安徽休宁/黟县',
                                    '祁婺片': '安徽祁门/江西婺源',
                                    '旌占片': '安徽旌德/黟县',
                                    '严州片': '浙江建德'
                                },
                                '赣语': {
                                    '昌都片': '江西南昌',
                                    '鹰弋片': '江西鹰潭/弋阳',
                                    '大通片': '江西九江/湖北',
                                    '甬江片': '江西鹰潭/浙江宁波',
                                    '洞绥片': '湖南洞口/绥宁',
                                    '宜浏片': '江西宜春/湖南浏阳',
                                    '吉茶片': '江西吉安/湖南茶陵'
                                },
                                '湘语': {
                                    '长益片': '湖南长沙/益阳',
                                    '娄邵片': '湖南娄底/邵阳',
                                    '辰溆片': '湖南怀化/溆浦',
                                    '衡州片': '湖南衡阳',
                                    '永州片': '湖南永州'
                                },
                                '闽语': {
                                    '闽南语': '福建厦门/泉州/漳州',
                                    '闽东语': '福建福州',
                                    '闽北语': '福建南平',
                                    '闽中语': '福建三明',
                                    '莆仙语': '福建莆田',
                                    '海南话': '海南',
                                    '雷州话': '广东雷州'
                                },
                                '粤语': {
                                    '广府话': '广东广州',
                                    '四邑话': '广东江门',
                                    '高阳话': '广东阳江',
                                    '吴化话': '广东湛江',
                                    '邕浔粤语': '广西南宁/柳州',
                                    '勾漏粤语': '广西玉林/贵港',
                                    '四色话': '广西贺州'
                                },
                                '客家话': {
                                    '粤台片': '广东梅州',
                                    '海陆片': '广东汕尾/台湾',
                                    '客家话': '福建长汀/江西',
                                    '宁龙片': '江西赣州/福建',
                                    '于桂片': '江西于都/广西'
                                },
                                '平话': {
                                    '桂北平话': '广西桂林',
                                    '桂南平话': '广西南宁'
                                }
                            };
                            
                            // 清空城市选项
                            citySelect.empty();
                            citySelect.append('<option value="">请选择方言点</option>');
                            
                            // 根据选择的方言区添加城市选项
                            if (region && chineseDialects[region]) {
                                $.each(chineseDialects[region], function(city, area) {
                                    citySelect.append('<option value="' + city + '">' + city + ' (' + area + ')</option>');
                                });
                            }
                        });
                        
                        // 省份变化时更新城市选项
                        $(document).on('change', '.province-select', function() {
                            var province = $(this).val();
                            var index = $(this).data('index');
                            var citySelect = $(this).closest('.structured-explanation-item').find('.city-select');
                            
                            // 主要城市列表（按省份分组）
                            var cities = {
                                '北京市': ['北京市'],
                                '天津市': ['天津市'],
                                '河北省': ['石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市', '保定市', '张家口市', '承德市', '沧州市', '廊坊市', '衡水市'],
                                '山西省': ['太原市', '大同市', '阳泉市', '长治市', '晋城市', '朔州市', '晋中市', '运城市', '忻州市', '临汾市', '吕梁市'],
                                '内蒙古自治区': ['呼和浩特市', '包头市', '乌海市', '赤峰市', '通辽市', '鄂尔多斯市', '呼伦贝尔市', '巴彦淖尔市', '乌兰察布市'],
                                '辽宁省': ['沈阳市', '大连市', '鞍山市', '抚顺市', '本溪市', '丹东市', '锦州市', '营口市', '阜新市', '辽阳市', '盘锦市', '铁岭市', '朝阳市', '葫芦岛市'],
                                '吉林省': ['长春市', '吉林市', '四平市', '辽源市', '通化市', '白山市', '松原市', '白城市'],
                                '黑龙江省': ['哈尔滨市', '齐齐哈尔市', '鸡西市', '鹤岗市', '双鸭山市', '大庆市', '伊春市', '佳木斯市', '七台河市', '牡丹江市', '黑河市', '绥化市'],
                                '上海市': ['上海市'],
                                '江苏省': ['南京市', '无锡市', '徐州市', '常州市', '苏州市', '南通市', '连云港市', '淮安市', '盐城市', '扬州市', '镇江市', '泰州市', '宿迁市'],
                                '浙江省': ['杭州市', '宁波市', '温州市', '嘉兴市', '湖州市', '绍兴市', '金华市', '衢州市', '舟山市', '台州市', '丽水市'],
                                '安徽省': ['合肥市', '芜湖市', '蚌埠市', '淮南市', '马鞍山市', '淮北市', '铜陵市', '安庆市', '黄山市', '滁州市', '阜阳市', '宿州市', '六安市', '亳州市', '池州市', '宣城市'],
                                '福建省': ['福州市', '厦门市', '莆田市', '三明市', '泉州市', '漳州市', '南平市', '龙岩市', '宁德市'],
                                '江西省': ['南昌市', '景德镇市', '萍乡市', '九江市', '新余市', '鹰潭市', '赣州市', '吉安市', '宜春市', '抚州市', '上饶市'],
                                '山东省': ['济南市', '青岛市', '淄博市', '枣庄市', '东营市', '烟台市', '潍坊市', '济宁市', '泰安市', '威海市', '日照市', '临沂市', '德州市', '聊城市', '滨州市', '菏泽市'],
                                '河南省': ['郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '濮阳市', '许昌市', '漯河市', '三门峡市', '南阳市', '商丘市', '信阳市', '周口市', '驻马店市'],
                                '湖北省': ['武汉市', '黄石市', '十堰市', '宜昌市', '襄阳市', '鄂州市', '荆门市', '孝感市', '荆州市', '黄冈市', '咸宁市', '随州市'],
                                '湖南省': ['长沙市', '株洲市', '湘潭市', '衡阳市', '邵阳市', '岳阳市', '常德市', '张家界市', '益阳市', '郴州市', '永州市', '怀化市', '娄底市'],
                                '广东省': ['广州市', '韶关市', '深圳市', '珠海市', '汕头市', '佛山市', '江门市', '湛江市', '茂名市', '肇庆市', '惠州市', '梅州市', '汕尾市', '河源市', '阳江市', '清远市', '东莞市', '中山市', '潮州市', '揭阳市', '云浮市'],
                                '广西壮族自治区': ['南宁市', '柳州市', '桂林市', '梧州市', '北海市', '防城港市', '钦州市', '贵港市', '玉林市', '百色市', '贺州市', '河池市', '来宾市', '崇左市'],
                                '海南省': ['海口市', '三亚市', '三沙市', '儋州市'],
                                '重庆市': ['重庆市'],
                                '四川省': ['成都市', '自贡市', '攀枝花市', '泸州市', '德阳市', '绵阳市', '广元市', '遂宁市', '内江市', '乐山市', '南充市', '眉山市', '宜宾市', '广安市', '达州市', '雅安市', '巴中市', '资阳市'],
                                '贵州省': ['贵阳市', '六盘水市', '遵义市', '安顺市', '毕节市', '铜仁市'],
                                '云南省': ['昆明市', '曲靖市', '玉溪市', '保山市', '昭通市', '丽江市', '普洱市', '临沧市'],
                                '西藏自治区': ['拉萨市', '日喀则市', '昌都市', '林芝市', '山南市', '那曲市', '阿里地区'],
                                '陕西省': ['西安市', '铜川市', '宝鸡市', '咸阳市', '渭南市', '延安市', '汉中市', '榆林市', '安康市', '商洛市'],
                                '甘肃省': ['兰州市', '嘉峪关市', '金昌市', '白银市', '天水市', '武威市', '张掖市', '平凉市', '酒泉市', '庆阳市', '定西市', '陇南市'],
                                '青海省': ['西宁市', '海东市'],
                                '宁夏回族自治区': ['银川市', '石嘴山市', '吴忠市', '固原市', '中卫市'],
                                '新疆维吾尔自治区': ['乌鲁木齐市', '克拉玛依市', '吐鲁番市', '哈密市'],
                                '台湾省': ['台北市', '新北市', '桃园市', '台中市', '台南市', '高雄市'],
                                '香港特别行政区': ['香港岛', '九龙', '新界'],
                                '澳门特别行政区': ['澳门半岛', '氹仔岛', '路环岛']
                            };
                            
                            // 清空城市选项
                            citySelect.empty();
                            citySelect.append('<option value="">请选择城市</option>');
                            
                            // 根据选择的省份添加城市选项
                            if (province && cities[province]) {
                                $.each(cities[province], function(index, city) {
                                    citySelect.append('<option value="' + city + '">' + city + '</option>');
                                });
                            }
                        });
                        
                        // 当页面加载时，为已有项初始化城市选项
                        $('.province-select').each(function() {
                            var province = $(this).val();
                            var index = $(this).data('index');
                            var citySelect = $(this).closest('.structured-explanation-item').find('.city-select');
                            var selectedCity = citySelect.attr('data-selected'); // 获取已保存的城市值
                            
                            if (province) {
                                // 触发change事件来加载城市选项
                                $(this).trigger('change');
                                
                                // 确保已选择的城市被选中
                                if (selectedCity) {
                                    // 等待选项加载完成后再设置选中值
                                    setTimeout(function() {
                                        citySelect.val(selectedCity);
                                    }, 150);
                                }
                            }
                        });
                        
                        // 在动态添加新解释项时，确保省份选择框的change事件被正确绑定
                        $(document).on('DOMNodeInserted', function(e) {
                            var element = $(e.target);
                            if (element.hasClass('structured-explanation-item')) {
                                // 为新添加的项绑定事件
                                element.find('.province-select').on('change', function() {
                                    var province = $(this).val();
                                    var index = $(this).data('index');
                                    var citySelect = $(this).closest('.structured-explanation-item').find('.city-select');
                                    
                                    // 主要城市列表（按省份分组）
                                    var cities = {
                                        '北京市': ['北京市'],
                                        '天津市': ['天津市'],
                                        '河北省': ['石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市', '保定市', '张家口市', '承德市', '沧州市', '廊坊市', '衡水市'],
                                        '山西省': ['太原市', '大同市', '阳泉市', '长治市', '晋城市', '朔州市', '晋中市', '运城市', '忻州市', '临汾市', '吕梁市'],
                                        '内蒙古自治区': ['呼和浩特市', '包头市', '乌海市', '赤峰市', '通辽市', '鄂尔多斯市', '呼伦贝尔市', '巴彦淖尔市', '乌兰察布市'],
                                        '辽宁省': ['沈阳市', '大连市', '鞍山市', '抚顺市', '本溪市', '丹东市', '锦州市', '营口市', '阜新市', '辽阳市', '盘锦市', '铁岭市', '朝阳市', '葫芦岛市'],
                                        '吉林省': ['长春市', '吉林市', '四平市', '辽源市', '通化市', '白山市', '松原市', '白城市'],
                                        '黑龙江省': ['哈尔滨市', '齐齐哈尔市', '鸡西市', '鹤岗市', '双鸭山市', '大庆市', '伊春市', '佳木斯市', '七台河市', '牡丹江市', '黑河市', '绥化市'],
                                        '上海市': ['上海市'],
                                        '江苏省': ['南京市', '无锡市', '徐州市', '常州市', '苏州市', '南通市', '连云港市', '淮安市', '盐城市', '扬州市', '镇江市', '泰州市', '宿迁市'],
                                        '浙江省': ['杭州市', '宁波市', '温州市', '嘉兴市', '湖州市', '绍兴市', '金华市', '衢州市', '舟山市', '台州市', '丽水市'],
                                        '安徽省': ['合肥市', '芜湖市', '蚌埠市', '淮南市', '马鞍山市', '淮北市', '铜陵市', '安庆市', '黄山市', '滁州市', '阜阳市', '宿州市', '六安市', '亳州市', '池州市', '宣城市'],
                                        '福建省': ['福州市', '厦门市', '莆田市', '三明市', '泉州市', '漳州市', '南平市', '龙岩市', '宁德市'],
                                        '江西省': ['南昌市', '景德镇市', '萍乡市', '九江市', '新余市', '鹰潭市', '赣州市', '吉安市', '宜春市', '抚州市', '上饶市'],
                                        '山东省': ['济南市', '青岛市', '淄博市', '枣庄市', '东营市', '烟台市', '潍坊市', '济宁市', '泰安市', '威海市', '日照市', '临沂市', '德州市', '聊城市', '滨州市', '菏泽市'],
                                        '河南省': ['郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '濮阳市', '许昌市', '漯河市', '三门峡市', '南阳市', '商丘市', '信阳市', '周口市', '驻马店市'],
                                        '湖北省': ['武汉市', '黄石市', '十堰市', '宜昌市', '襄阳市', '鄂州市', '荆门市', '孝感市', '荆州市', '黄冈市', '咸宁市', '随州市'],
                                        '湖南省': ['长沙市', '株洲市', '湘潭市', '衡阳市', '邵阳市', '岳阳市', '常德市', '张家界市', '益阳市', '郴州市', '永州市', '怀化市', '娄底市'],
                                        '广东省': ['广州市', '韶关市', '深圳市', '珠海市', '汕头市', '佛山市', '江门市', '湛江市', '茂名市', '肇庆市', '惠州市', '梅州市', '汕尾市', '河源市', '阳江市', '清远市', '东莞市', '中山市', '潮州市', '揭阳市', '云浮市'],
                                        '广西壮族自治区': ['南宁市', '柳州市', '桂林市', '梧州市', '北海市', '防城港市', '钦州市', '贵港市', '玉林市', '百色市', '贺州市', '河池市', '来宾市', '崇左市'],
                                        '海南省': ['海口市', '三亚市', '三沙市', '儋州市'],
                                        '重庆市': ['重庆市'],
                                        '四川省': ['成都市', '自贡市', '攀枝花市', '泸州市', '德阳市', '绵阳市', '广元市', '遂宁市', '内江市', '乐山市', '南充市', '眉山市', '宜宾市', '广安市', '达州市', '雅安市', '巴中市', '资阳市'],
                                        '贵州省': ['贵阳市', '六盘水市', '遵义市', '安顺市', '毕节市', '铜仁市'],
                                        '云南省': ['昆明市', '曲靖市', '玉溪市', '保山市', '昭通市', '丽江市', '普洱市', '临沧市'],
                                        '西藏自治区': ['拉萨市', '日喀则市', '昌都市', '林芝市', '山南市', '那曲市', '阿里地区'],
                                        '陕西省': ['西安市', '铜川市', '宝鸡市', '咸阳市', '渭南市', '延安市', '汉中市', '榆林市', '安康市', '商洛市'],
                                        '甘肃省': ['兰州市', '嘉峪关市', '金昌市', '白银市', '天水市', '武威市', '张掖市', '平凉市', '酒泉市', '庆阳市', '定西市', '陇南市'],
                                        '青海省': ['西宁市', '海东市'],
                                        '宁夏回族自治区': ['银川市', '石嘴山市', '吴忠市', '固原市', '中卫市'],
                                        '新疆维吾尔自治区': ['乌鲁木齐市', '克拉玛依市', '吐鲁番市', '哈密市'],
                                        '台湾省': ['台北市', '新北市', '桃园市', '台中市', '台南市', '高雄市'],
                                        '香港特别行政区': ['香港岛', '九龙', '新界'],
                                        '澳门特别行政区': ['澳门半岛', '氹仔岛', '路环岛']
                                    };
                                    
                                    // 清空城市选项
                                    citySelect.empty();
                                    citySelect.append('<option value="">请选择城市</option>');
                                    
                                    // 根据选择的省份添加城市选项
                                    if (province && cities[province]) {
                                        $.each(cities[province], function(index, city) {
                                            citySelect.append('<option value="' + city + '">' + city + '</option>');
                                        });
                                    }
                                });
                            }
                        });
                        
                        // 清空搜索框时显示所有选项
                        $(document).on('search', '.dictionary-search-in-structured, .idiom-search-in-structured', function() {
                            if ($(this).val() === '') {
                                $(this).siblings('select').children('option').show().attr('hidden', false);
                            }
                        });
                        
                        // 添加同义字词和近义字词搜索功能
                        $(document).on('keyup', '.synonymous-characters-search, .similar-characters-search', function() {
                            // 当前搜索框的值
                            var searchTerm = $(this).val();
                            
                            // 查找对应的输入框
                            var targetInput = $(this).siblings('input[type="text"]').filter(function() {
                                return $(this).attr('name').indexOf('[synonymous_characters]') !== -1 || 
                                       $(this).attr('name').indexOf('[similar_characters]') !== -1;
                            });
                            
                            // 如果搜索框中有值且目标输入框存在
                            if (searchTerm && targetInput.length) {
                                var currentVal = targetInput.val();
                                // 如果当前值不为空，在末尾添加逗号和空格
                                if (currentVal && currentVal.trim() !== '') {
                                    // 检查是否已经添加了该词
                                    if (currentVal.indexOf(searchTerm) === -1) {
                                        targetInput.val(currentVal + ', ' + searchTerm);
                                    }
                                } else {
                                    // 如果当前值为空，直接设置为搜索词
                                    targetInput.val(searchTerm);
                                }
                                
                                // 清空搜索框
                                $(this).val('');
                            }
                        });
                        
                        // 重新编号函数
                        function updateFieldIndices(itemElement, newIndex) {
                            // 更新标题
                            itemElement.find('h4').html(`解释项 #${newIndex + 1} <button type="button" class="button remove-structured-explanation" style="float: right;">删除</button>`);
                            
                            // 更新所有字段的name和id属性
                            itemElement.find('[name]').each(function() {
                                var oldName = $(this).attr('name');
                                var newName = oldName.replace(/\[\d+\]/g, '[' + newIndex + ']');
                                $(this).attr('name', newName);
                            });
                            
                            itemElement.find('[id]').each(function() {
                                var oldId = $(this).attr('id');
                                var newId = oldId.replace(/_\d+_/g, '_' + newIndex + '_');
                                $(this).attr('id', newId);
                            });
                            
                            // 更新data-index属性
                            itemElement.find('[data-index]').attr('data-index', newIndex);
                        }
                    });
                    </script>
                </td>
            </tr>
            
            <tr>
                <th><label for="character_detailed_explanation">详细解释</label></th>
                <td>
        <?php
        wp_editor($detailed_explanation, 'character_detailed_explanation', array(
            'textarea_name' => 'character_detailed_explanation',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false, // 改为false以支持更多功能
            'quicktags' => true,
            'tinymce' => array(
                'plugins' => 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media',
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table'
            ),
        ));
        ?>
                </td>
            </tr>
        </table>
    
        
        <?php
    }
    
    /**
     * 国语辞典元框
     */
    public function render_guoyu_dictionary_meta_box($post) {
        $guoyu_dictionary = get_post_meta($post->ID, '_character_guoyu_dictionary', true);
        wp_editor($guoyu_dictionary, 'character_guoyu_dictionary', array(
            'textarea_name' => 'character_guoyu_dictionary',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false, // 改为false以支持更多功能
            'quicktags' => true,
            'tinymce' => array(
                'plugins' => 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media',
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table'
            ),
        ));
    }
    
    /**
     * 康熙字典元框
     */
    public function render_kangxi_dictionary_meta_box($post) {
        $kangxi_dictionary = get_post_meta($post->ID, '_character_kangxi_dictionary', true);
        wp_editor($kangxi_dictionary, 'character_kangxi_dictionary', array(
            'textarea_name' => 'character_kangxi_dictionary',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false, // 改为false以支持更多功能
            'quicktags' => true,
            'tinymce' => array(
                'plugins' => 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media',
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table'
            ),
        ));
    }
    
    /**
     * 说文解字元框
     */
    public function render_shuowen_jiezi_meta_box($post) {
        $shuowen_jiezi = get_post_meta($post->ID, '_character_shuowen_jiezi', true);
        wp_editor($shuowen_jiezi, 'character_shuowen_jiezi', array(
            'textarea_name' => 'character_shuowen_jiezi',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false, // 改为false以支持更多功能
            'quicktags' => true,
            'tinymce' => array(
                'plugins' => 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media',
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table'
            ),
        ));
    }
    
    /**
     * 音韵方言元框
     */
    public function render_dialects_meta_box($post) {
        $dialects = get_post_meta($post->ID, '_character_dialects', true);
        wp_editor($dialects, 'character_dialects', array(
            'textarea_name' => 'character_dialects',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false, // 改为false以支持更多功能
            'quicktags' => true,
            'tinymce' => array(
                'plugins' => 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media',
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table'
            ),
        ));
    }
    
    /**
     * 字源字形元框
     */
    public function render_etymology_meta_box($post) {
        $etymology = get_post_meta($post->ID, '_character_etymology', true);
        wp_editor($etymology, 'character_etymology', array(
            'textarea_name' => 'character_etymology',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false, // 改为false以支持更多功能
            'quicktags' => true,
            'tinymce' => array(
                'plugins' => 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media',
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table'
            ),
        ));
    }
    
    /**
     * 其他释义元框
     */
    public function render_other_meanings_meta_box($post) {
        $other_meanings = get_post_meta($post->ID, '_character_other_meanings', true);
        wp_editor($other_meanings, 'character_other_meanings', array(
            'textarea_name' => 'character_other_meanings',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false, // 改为false以支持更多功能
            'quicktags' => true,
            'tinymce' => array(
                'plugins' => 'lists,link,hr,fullscreen,wordpress,textcolor,paste,charmap,table,code,media',
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,table'
            ),
        ));
    }
    
    /**
     * 汉字发音含义对元框
     */
    public function render_character_pronunciations_meta_box($post) {
        // 检查发音含义对功能是否已启用
        if (!class_exists('PronunciationMeaningPairs')) {
            echo '<p>发音含义对功能未启用。</p>';
            return;
        }
        
        // 获取与当前汉字关联的所有发音含义对
        $pronunciations = get_posts(array(
            'post_type' => 'pronunciation_pair',
            'post_status' => 'any',
            'numberposts' => -1,
            'meta_query' => array(
                array(
                    'key' => '_pronunciation_related_character',
                    'value' => $post->ID,
                    'compare' => '='
                )
            )
        ));
        
        echo '<p>此汉字的所有发音和含义：</p>';
        
        if (!empty($pronunciations)) {
            echo '<ul>';
            foreach ($pronunciations as $pronunciation) {
                echo '<li>';
                echo '<a href="' . get_edit_post_link($pronunciation->ID) . '">' . $pronunciation->post_title . '</a>';
                $pinyin = get_post_meta($pronunciation->ID, '_pronunciation_pinyin', true);
                if ($pinyin) {
                    echo ' (' . esc_html($pinyin) . ')';
                }
                echo '</li>';
            }
            echo '</ul>';
        } else {
            echo '<p>暂无发音含义对。</p>';
        }
        
        // 添加一个按钮，可以直接创建并关联到当前汉字的发音含义对
        echo '<p><a class="button button-primary" href="' . admin_url('post-new.php?post_type=pronunciation_pair&related_character=' . $post->ID) . '">添加发音含义对</a></p>';
    }

    /**
     * 词语国语辞典元框
     */
    public function render_dictionary_guoyu_dictionary_meta_box($post) {
        $guoyu_dictionary = get_post_meta($post->ID, '_dictionary_guoyu_dictionary', true);
        wp_editor($guoyu_dictionary, 'dictionary_guoyu_dictionary', array(
            'textarea_name' => 'dictionary_guoyu_dictionary',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false,
            'quicktags' => true,
            'tinymce' => array(
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo'
            ),
        ));
    }
    
    /**
     * 词语音韵方言元框
     */
    public function render_dictionary_dialects_meta_box($post) {
        $dialects = get_post_meta($post->ID, '_dictionary_dialects', true);
        wp_editor($dialects, 'dictionary_dialects', array(
            'textarea_name' => 'dictionary_dialects',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false,
            'quicktags' => true,
            'tinymce' => array(
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo'
            ),
        ));
    }
    
    /**
     * 词语其他释义元框
     */
    public function render_dictionary_other_meanings_meta_box($post) {
        $other_meanings = get_post_meta($post->ID, '_dictionary_other_meanings', true);
        wp_editor($other_meanings, 'dictionary_other_meanings', array(
            'textarea_name' => 'dictionary_other_meanings',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false,
            'quicktags' => true,
            'tinymce' => array(
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo'
            ),
        ));
    }
    
    /**
     * 成语国语辞典元框
     */
    public function render_idiom_guoyu_dictionary_meta_box($post) {
        $guoyu_dictionary = get_post_meta($post->ID, '_idiom_guoyu_dictionary', true);
        wp_editor($guoyu_dictionary, 'idiom_guoyu_dictionary', array(
            'textarea_name' => 'idiom_guoyu_dictionary',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false,
            'quicktags' => true,
            'tinymce' => array(
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo'
            ),
        ));
    }
    
    /**
     * 成语音韵方言元框
     */
    public function render_idiom_dialects_meta_box($post) {
        $dialects = get_post_meta($post->ID, '_idiom_dialects', true);
        wp_editor($dialects, 'idiom_dialects', array(
            'textarea_name' => 'idiom_dialects',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false,
            'quicktags' => true,
            'tinymce' => array(
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo'
            ),
        ));
    }
    
    /**
     * 成语其他释义元框
     */
    public function render_idiom_other_meanings_meta_box($post) {
        $other_meanings = get_post_meta($post->ID, '_idiom_other_meanings', true);
        wp_editor($other_meanings, 'idiom_other_meanings', array(
            'textarea_name' => 'idiom_other_meanings',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false,
            'quicktags' => true,
            'tinymce' => array(
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo'
            ),
        ));
    }
    
    /**
     * 保存汉字元数据
     */
    public function save_character_meta($post_id) {
        // 检查是否是自动保存
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // 检查nonce
        if (!isset($_POST['character_meta_nonce']) || !wp_verify_nonce($_POST['character_meta_nonce'], 'save_character_meta')) {
            return;
        }
        
        // 检查用户权限
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // 检查文章类型
        if (get_post_type($post_id) !== 'chinese_character') {
            return;
        }
        
        // 处理拼音字段
        $pinyin = '';
        if (!empty($_POST['character_pinyin']) && is_array($_POST['character_pinyin'])) {
            // 过滤空值并合并拼音，使用空格分隔
            $selected_pinyins = array_filter($_POST['character_pinyin']);
            $pinyin = implode(' ', $selected_pinyins);
        } elseif (!empty($_POST['character_pinyin_custom'])) {
            $pinyin = sanitize_text_field($_POST['character_pinyin_custom']);
        }
        
        // 保存字段
        update_post_meta($post_id, '_character_pinyin', $pinyin);
        update_post_meta($post_id, '_character_radical', sanitize_text_field($_POST['character_radical']));
        update_post_meta($post_id, '_character_stroke_count', sanitize_text_field($_POST['character_stroke_count']));
        update_post_meta($post_id, '_character_traditional_form', sanitize_text_field($_POST['character_traditional_form']));
        update_post_meta($post_id, '_character_variants', sanitize_text_field($_POST['character_variants']));
        update_post_meta($post_id, '_character_related_ancient_text', sanitize_text_field($_POST['character_related_ancient_text']));
        
        // 保存关联词语
        if (isset($_POST['character_related_dictionaries'])) {
            $related_dictionaries = array_map('intval', $_POST['character_related_dictionaries']);
            update_post_meta($post_id, '_character_related_dictionaries', $related_dictionaries);
        } else {
            update_post_meta($post_id, '_character_related_dictionaries', array());
        }
        
        // 保存关联成语
        if (isset($_POST['character_related_idioms'])) {
            $related_idioms = array_map('intval', $_POST['character_related_idioms']);
            update_post_meta($post_id, '_character_related_idioms', $related_idioms);
        } else {
            update_post_meta($post_id, '_character_related_idioms', array());
        }
        
        // 保存详细解释
        if (isset($_POST['character_detailed_explanation'])) {
            // 使用wp_kses_post处理富文本内容，而不是sanitize_textarea_field
            update_post_meta($post_id, '_character_detailed_explanation', wp_kses_post($_POST['character_detailed_explanation']));
        }
        
        // 保存使用示例
        if (isset($_POST['character_example_usage'])) {
            update_post_meta($post_id, '_character_example_usage', sanitize_textarea_field($_POST['character_example_usage']));
        }
        
        // 保存结构化解释
        if (isset($_POST['structured_explanations']) && is_array($_POST['structured_explanations'])) {
            $structured_explanations = array();
            
            foreach ($_POST['structured_explanations'] as $exp_data) {
                // 处理拼音字段
                $pinyin = array();
                if (isset($exp_data['pinyin']) && is_array($exp_data['pinyin'])) {
                    // 过滤空值并合并拼音
                    $pinyin = array_filter($exp_data['pinyin']);
                } elseif (!empty($exp_data['pinyin_custom'])) {
                    // 如果有自定义拼音，则使用自定义拼音，按空格分割
                    $pinyin = preg_split('/\s+/', $exp_data['pinyin_custom'], -1, PREG_SPLIT_NO_EMPTY);
                }
                
                // 将拼音数组转换为字符串存储
                $pinyin_string = '';
                if (!empty($pinyin)) {
                    $pinyin_string = implode(' ', $pinyin);
                }
                
                // 处理自定义字段
                $custom_fields = array();
                if (isset($exp_data['custom_fields']) && is_array($exp_data['custom_fields'])) {
                    foreach ($exp_data['custom_fields'] as $cf_data) {
                        if (!empty($cf_data['label']) || !empty($cf_data['value'])) {
                            $custom_fields[] = array(
                                'label' => sanitize_text_field($cf_data['label']),
                                'value' => sanitize_textarea_field($cf_data['value'])
                            );
                        }
                    }
                }
                
                // 处理关联词语
                $related_dictionaries = array();
                if (isset($exp_data['related_dictionaries']) && is_array($exp_data['related_dictionaries'])) {
                    $related_dictionaries = array_map('intval', $exp_data['related_dictionaries']);
                }
                
                // 处理关联成语
                $related_idioms = array();
                if (isset($exp_data['related_idioms']) && is_array($exp_data['related_idioms'])) {
                    $related_idioms = array_map('intval', $exp_data['related_idioms']);
                }
                
                // 处理同义字词
                $synonymous_characters = array();
                if (isset($exp_data['synonymous_characters']) && is_array($exp_data['synonymous_characters'])) {
                    $synonymous_characters = array_map('intval', $exp_data['synonymous_characters']);
                }
                
                // 处理近义字词
                $similar_characters = array();
                if (isset($exp_data['similar_characters']) && is_array($exp_data['similar_characters'])) {
                    $similar_characters = array_map('intval', $exp_data['similar_characters']);
                }
                
                // 处理反义字词
                $antonymous_characters = array();
                if (isset($exp_data['antonymous_characters']) && is_array($exp_data['antonymous_characters'])) {
                    $antonymous_characters = array_map('intval', $exp_data['antonymous_characters']);
                }
                
                // 处理关联内容
                $related_content = array();
                if (isset($exp_data['related_content']) && is_array($exp_data['related_content'])) {
                    $related_content = array_map('sanitize_text_field', $exp_data['related_content']);
                }
                
                // 只保存非空的解释项
                if (!empty($exp_data['explanation']) || 
                    !empty($exp_data['part_of_speech']) || 
                    !empty($pinyin_string)) {
                    
                    // 处理音频文件
                    $audio_id = '';
                    if (isset($exp_data['audio']) && !empty($exp_data['audio'])) {
                        $audio_id = sanitize_text_field($exp_data['audio']);
                    }
                    
                    $structured_explanations[] = array(
                        'part_of_speech' => isset($exp_data['part_of_speech']) ? sanitize_text_field($exp_data['part_of_speech']) : '',
                        'pinyin' => $pinyin_string,
                        'audio' => $audio_id,
                        'dialect_region' => isset($exp_data['dialect_region']) ? sanitize_text_field($exp_data['dialect_region']) : '',
                        'dialect_city' => isset($exp_data['dialect_city']) ? sanitize_text_field($exp_data['dialect_city']) : '',
                        'province' => isset($exp_data['province']) ? sanitize_text_field($exp_data['province']) : '',
                        'city' => isset($exp_data['city']) ? sanitize_text_field($exp_data['city']) : '',
                        'county' => isset($exp_data['county']) ? sanitize_text_field($exp_data['county']) : '',
                        'town' => isset($exp_data['town']) ? sanitize_text_field($exp_data['town']) : '',
                        'explanation' => isset($exp_data['explanation']) ? wp_kses_post($exp_data['explanation']) : '', // 使用wp_kses_post处理富文本
                        'example_sentences' => isset($exp_data['example_sentences']) ? wp_kses_post($exp_data['example_sentences']) : '', // 使用wp_kses_post处理富文本
                        'research' => isset($exp_data['research']) ? wp_kses_post($exp_data['research']) : '', // 使用wp_kses_post处理富文本
                        'related_dictionaries' => $related_dictionaries,
                        'related_idioms' => $related_idioms,
                        'synonymous_characters' => $synonymous_characters,
                        'similar_characters' => $similar_characters,
                        'antonymous_characters' => $antonymous_characters,
                        'related_content' => $related_content,
                        'custom_fields' => $custom_fields
                    );
                }
            }
            
            update_post_meta($post_id, '_character_structured_explanations', $structured_explanations);
        }
        
        // 保存额外字段
        $fields = array(
            'character_guoyu_dictionary',
            'character_kangxi_dictionary',
            'character_shuowen_jiezi',
            'character_dialects',
            'character_etymology',
            'character_other_meanings'
        );
        
        foreach ($fields as $field) {
            if (isset($_POST[$field])) {
                // 使用wp_kses_post处理富文本内容，而不是sanitize_textarea_field
                update_post_meta($post_id, '_' . $field, wp_kses_post($_POST[$field]));
            }
        }
    }
    
    /**
     * 词语基本信息元框
     */
    public function render_dictionary_basic_info_meta_box($post) {
        $pinyin = get_post_meta($post->ID, '_dictionary_pinyin', true);
        $abbreviation = get_post_meta($post->ID, '_dictionary_abbreviation', true);
        $synonyms = get_post_meta($post->ID, '_dictionary_synonyms', true);
        $antonyms = get_post_meta($post->ID, '_dictionary_antonyms', true);
        $related_ancient_text = get_post_meta($post->ID, '_dictionary_related_ancient_text', true);
        
        // 获取所有古籍文章
        $ancient_texts = get_posts(array(
            'post_type' => 'chinese_ancient_text',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        wp_nonce_field('save_dictionary_meta', 'dictionary_meta_nonce');
        ?>
        <table class="form-table">
            <tr>
                <th><label for="dictionary_pinyin">拼音</label></th>
                <td>
                    <select id="dictionary_pinyin" name="dictionary_pinyin[]" class="regular-text pinyin-select" multiple size="10">
                        <option value="">请选择拼音（可多选）</option>
                        <?php 
                        // 将存储的拼音字符串转换为数组，支持空格分隔
                        $selected_pinyins = !empty($pinyin) ? preg_split('/\s+/', $pinyin, -1, PREG_SPLIT_NO_EMPTY) : array();
                        foreach ($this->pinyin_list as $p): ?>
                            <option value="<?php echo esc_attr($p); ?>" <?php echo in_array($p, $selected_pinyins) ? 'selected' : ''; ?>><?php echo esc_html($p); ?></option>
                        <?php endforeach; ?>
                        <?php 
                        // 添加自定义拼音选项
                        $custom_pinyin = get_option('chinese_character_custom_pinyin', array());
                        if (!empty($custom_pinyin)): ?>
                            <optgroup label="自定义拼音">
                                <?php foreach ($custom_pinyin as $cp): ?>
                                    <option value="<?php echo esc_attr($cp); ?>" <?php echo in_array($cp, $selected_pinyins) ? 'selected' : ''; ?>><?php echo esc_html($cp); ?></option>
                                <?php endforeach; ?>
                            </optgroup>
                        <?php endif; ?>
                    </select>
                    <p class="description">在上方输入框中输入拼音可搜索过滤选项，按住 Ctrl 键可选择多个拼音（Windows）或按住 Cmd 键选择多个拼音（Mac）</p>
                    <p class="description">选择词语的拼音，支持带声调符号的拼音（可多选）</p>
                </td>
            </tr>
            <tr>
                <th><label for="dictionary_pinyin_custom">或输入自定义拼音</label></th>
                <td>
                    <input type="text" id="dictionary_pinyin_custom" name="dictionary_pinyin_custom" value="<?php echo esc_attr($pinyin); ?>" class="regular-text" />
                    <p class="description">如果拼音列表中没有，请在此输入完整拼音，例如：xiǎo míng</p>
                    <p class="description">
                        声调符号：<br>
                        第一声：ā ē ī ō ū ǖ<br>
                        第二声：á é í ó ú ǘ<br>
                        第三声：ǎ ě ǐ ǒ ǔ ǚ<br>
                        第四声：à è ì ò ù ǜ
                    </p>
                </td>
            </tr>
            <tr>
                <th><label for="dictionary_abbreviation">缩写</label></th>
                <td><input type="text" id="dictionary_abbreviation" name="dictionary_abbreviation" value="<?php echo esc_attr($abbreviation); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="dictionary_synonyms">近义词</label></th>
                <td><input type="text" id="dictionary_synonyms" name="dictionary_synonyms" value="<?php echo esc_attr($synonyms); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="dictionary_antonyms">反义词</label></th>
                <td><input type="text" id="dictionary_antonyms" name="dictionary_antonyms" value="<?php echo esc_attr($antonyms); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="dictionary_related_ancient_text">关联古籍</label></th>
                <td>
                    <select id="dictionary_related_ancient_text" name="dictionary_related_ancient_text" class="regular-text">
                        <option value="">无关联古籍</option>
                        <?php foreach ($ancient_texts as $ancient_text): ?>
                            <option value="<?php echo esc_attr($ancient_text->ID); ?>" <?php selected($ancient_text->ID, $related_ancient_text); ?>>
                                <?php echo esc_html($ancient_text->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">选择与此词语相关的古籍</p>
                </td>
            </tr>
        </table>
        <?php
    }
    /**
     * 词语详细解释元框
     */
    public function render_dictionary_detailed_explanation_meta_box($post) {
        $detailed_explanation = get_post_meta($post->ID, '_dictionary_detailed_explanation', true);
        wp_editor($detailed_explanation, 'dictionary_detailed_explanation', array(
            'textarea_name' => 'dictionary_detailed_explanation',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false,
            'quicktags' => true,
            'tinymce' => array(
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo'
            ),
        ));
    }
    
    /**
     * 成语基本信息元框
     */
    public function render_idiom_basic_info_meta_box($post) {
        $pinyin = get_post_meta($post->ID, '_idiom_pinyin', true);
        $abbreviation = get_post_meta($post->ID, '_idiom_abbreviation', true);
        $synonyms = get_post_meta($post->ID, '_idiom_synonyms', true);
        $antonyms = get_post_meta($post->ID, '_idiom_antonyms', true);
        $related_ancient_text = get_post_meta($post->ID, '_idiom_related_ancient_text', true);
        $structured_explanations = get_post_meta($post->ID, '_idiom_structured_explanations', true);
        
    
        // 获取所有古籍文章
        $ancient_texts = get_posts(array(
            'post_type' => 'chinese_ancient_text',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));
        
        wp_nonce_field('save_idiom_meta', 'idiom_meta_nonce');
        ?>
        <table class="form-table">
            <tr>
                <th><label for="idiom_pinyin">拼音</label></th>
                <td>
                    <select id="idiom_pinyin" name="idiom_pinyin[]" class="regular-text pinyin-select" multiple size="10">
                        <option value="">请选择拼音（可多选）</option>
                        <?php 
                        // 将存储的拼音字符串转换为数组，支持空格分隔
                        $selected_pinyins = !empty($pinyin) ? preg_split('/\s+/', $pinyin, -1, PREG_SPLIT_NO_EMPTY) : array();
                        foreach ($this->pinyin_list as $p): ?>
                            <option value="<?php echo esc_attr($p); ?>" <?php echo in_array($p, $selected_pinyins) ? 'selected' : ''; ?>><?php echo esc_html($p); ?></option>
                        <?php endforeach; ?>
                        <?php 
                        // 添加自定义拼音选项
                        $custom_pinyin = get_option('chinese_character_custom_pinyin', array());
                        if (!empty($custom_pinyin)): ?>
                            <optgroup label="自定义拼音">
                                <?php foreach ($custom_pinyin as $cp): ?>
                                    <option value="<?php echo esc_attr($cp); ?>" <?php echo in_array($cp, $selected_pinyins) ? 'selected' : ''; ?>><?php echo esc_html($cp); ?></option>
                                <?php endforeach; ?>
                            </optgroup>
                        <?php endif; ?>
                    </select>
                    <p class="description">在上方输入框中输入拼音可搜索过滤选项，按住 Ctrl 键可选择多个拼音（Windows）或按住 Cmd 键选择多个拼音（Mac）</p>
                    <p class="description">选择成语的拼音，支持带声调符号的拼音（可多选）</p>
                </td>
            </tr>
            <tr>
                <th><label for="idiom_pinyin_custom">或输入自定义拼音</label></th>
                <td>
                    <input type="text" id="idiom_pinyin_custom" name="idiom_pinyin_custom" value="<?php echo esc_attr($pinyin); ?>" class="regular-text" />
                    <p class="description">如果拼音列表中没有，请在此输入完整拼音，例如：yī fān fēng shùn</p>
                    <p class="description">
                        声调符号：<br>
                        第一声：ā ē ī ō ū ǖ<br>
                        第二声：á é í ó ú ǘ<br>
                        第三声：ǎ ě ǐ ǒ ǔ ǚ<br>
                        第四声：à è ì ò ù ǜ
                    </p>
                </td>
            </tr>
            <tr>
                <th><label for="idiom_abbreviation">缩写</label></th>
                <td><input type="text" id="idiom_abbreviation" name="idiom_abbreviation" value="<?php echo esc_attr($abbreviation); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="idiom_synonyms">近义词</label></th>
                <td><input type="text" id="idiom_synonyms" name="idiom_synonyms" value="<?php echo esc_attr($synonyms); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="idiom_antonyms">反义词</label></th>
                <td><input type="text" id="idiom_antonyms" name="idiom_antonyms" value="<?php echo esc_attr($antonyms); ?>" class="regular-text" /></td>
            </tr>
            <tr>
                <th><label for="idiom_related_ancient_text">关联古籍</label></th>
                <td>
                    <select id="idiom_related_ancient_text" name="idiom_related_ancient_text" class="regular-text">
                        <option value="">无关联古籍</option>
                        <?php foreach ($ancient_texts as $ancient_text): ?>
                            <option value="<?php echo esc_attr($ancient_text->ID); ?>" <?php selected($ancient_text->ID, $related_ancient_text); ?>>
                                <?php echo esc_html($ancient_text->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">选择与此成语相关的古籍</p>
                </td>
            </tr>
           
        </table>
        <?php
    }
    
    /**
     * 成语详细解释元框
     */
    public function render_idiom_detailed_explanation_meta_box($post) {
        $detailed_explanation = get_post_meta($post->ID, '_idiom_detailed_explanation', true);
        wp_editor($detailed_explanation, 'idiom_detailed_explanation', array(
            'textarea_name' => 'idiom_detailed_explanation',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false,
            'quicktags' => true,
            'tinymce' => array(
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo'
            ),
        ));
    }
    
    /**
     * 成语典故元框
     */
    public function render_idiom_derivation_meta_box($post) {
        $derivation = get_post_meta($post->ID, '_idiom_derivation', true);
        wp_editor($derivation, 'idiom_derivation', array(
            'textarea_name' => 'idiom_derivation',
            'textarea_rows' => 10,
            'media_buttons' => false,
            'teeny' => false,
            'quicktags' => true,
            'tinymce' => array(
                'toolbar1' => 'formatselect,bold,italic,bullist,numlist,blockquote,alignleft,aligncenter,alignright,link,unlink,fullscreen',
                'toolbar2' => 'strikethrough,hr,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo'
            ),
        ));
    }
    
    /**
     * 保存词典元数据
     */
    public function save_dictionary_meta($post_id) {
        // 检查是否是自动保存
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // 检查nonce
        if (!isset($_POST['dictionary_meta_nonce']) || !wp_verify_nonce($_POST['dictionary_meta_nonce'], 'save_dictionary_meta')) {
            return;
        }
        
        // 检查用户权限
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // 检查文章类型
        if (get_post_type($post_id) !== 'chinese_dictionary') {
            return;
        }
        
        // 处理拼音字段
        $pinyin = '';
        if (!empty($_POST['dictionary_pinyin']) && is_array($_POST['dictionary_pinyin'])) {
            // 过滤空值并合并拼音，使用空格分隔
            $selected_pinyins = array_filter($_POST['dictionary_pinyin']);
            $pinyin = implode(' ', $selected_pinyins);
        } elseif (!empty($_POST['dictionary_pinyin_custom'])) {
            $pinyin = sanitize_text_field($_POST['dictionary_pinyin_custom']);
        }
        
        // 保存字段
        update_post_meta($post_id, '_dictionary_pinyin', $pinyin);
        update_post_meta($post_id, '_dictionary_abbreviation', sanitize_text_field($_POST['dictionary_abbreviation']));
        update_post_meta($post_id, '_dictionary_synonyms', sanitize_text_field($_POST['dictionary_synonyms']));
        update_post_meta($post_id, '_dictionary_antonyms', sanitize_text_field($_POST['dictionary_antonyms']));
        update_post_meta($post_id, '_dictionary_related_ancient_text', sanitize_text_field($_POST['dictionary_related_ancient_text']));
        
        // 保存详细解释
        if (isset($_POST['dictionary_detailed_explanation'])) {
            // 使用wp_kses_post处理富文本内容，而不是sanitize_textarea_field
            update_post_meta($post_id, '_dictionary_detailed_explanation', wp_kses_post($_POST['dictionary_detailed_explanation']));
        }
        
        // 保存额外字段
        $fields = array(
            'dictionary_guoyu_dictionary',
            'dictionary_dialects',
            'dictionary_other_meanings'
        );
        
        foreach ($fields as $field) {
            if (isset($_POST[$field])) {
                // 使用wp_kses_post处理富文本内容，而不是sanitize_textarea_field
                update_post_meta($post_id, '_' . $field, wp_kses_post($_POST[$field]));
            }
        }
    }
    
    /**
     * 保存成语元数据
     */
    public function save_idiom_meta($post_id) {
        // 检查是否是自动保存
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // 检查nonce
        if (!isset($_POST['idiom_meta_nonce']) || !wp_verify_nonce($_POST['idiom_meta_nonce'], 'save_idiom_meta')) {
            return;
        }
        
        // 检查用户权限
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // 检查文章类型
        if (get_post_type($post_id) !== 'chinese_idiom') {
            return;
        }
        
        // 处理拼音字段
        $pinyin = '';
        if (!empty($_POST['idiom_pinyin']) && is_array($_POST['idiom_pinyin'])) {
            // 过滤空值并合并拼音，使用空格分隔
            $selected_pinyins = array_filter($_POST['idiom_pinyin']);
            $pinyin = implode(' ', $selected_pinyins);
        } elseif (!empty($_POST['idiom_pinyin_custom'])) {
            $pinyin = sanitize_text_field($_POST['idiom_pinyin_custom']);
        }
        
        // 保存字段
        update_post_meta($post_id, '_idiom_pinyin', $pinyin);
        update_post_meta($post_id, '_idiom_abbreviation', sanitize_text_field($_POST['idiom_abbreviation']));
        update_post_meta($post_id, '_idiom_synonyms', sanitize_text_field($_POST['idiom_synonyms']));
        update_post_meta($post_id, '_idiom_antonyms', sanitize_text_field($_POST['idiom_antonyms']));
        update_post_meta($post_id, '_idiom_related_ancient_text', sanitize_text_field($_POST['idiom_related_ancient_text']));
        
        // 保存详细解释
        if (isset($_POST['idiom_detailed_explanation'])) {
            // 使用wp_kses_post处理富文本内容，而不是sanitize_textarea_field
            update_post_meta($post_id, '_idiom_detailed_explanation', wp_kses_post($_POST['idiom_detailed_explanation']));
        }
        
        // 保存成语典故
        if (isset($_POST['idiom_derivation'])) {
            // 使用wp_kses_post处理富文本内容，而不是sanitize_textarea_field
            update_post_meta($post_id, '_idiom_derivation', wp_kses_post($_POST['idiom_derivation']));
        }
        
        // 保存额外字段
        $fields = array(
            'idiom_guoyu_dictionary',
            'idiom_dialects',
            'idiom_other_meanings'
        );
        
        foreach ($fields as $field) {
            if (isset($_POST[$field])) {
                // 使用wp_kses_post处理富文本内容，而不是sanitize_textarea_field
                update_post_meta($post_id, '_' . $field, wp_kses_post($_POST[$field]));
            }
        }
    }
    
    /**
     * 书法作品汉字信息元框
     */
    public function render_calligraphy_character_meta_box($post) {
        $calligraphy_character = get_post_meta($post->ID, '_calligraphy_character', true);
        ?>
        <table class="form-table">
            <tr>
                <th><label for="calligraphy_character">汉字</label></th>
                <td>
                    <select id="calligraphy_character" name="calligraphy_character" class="chinese-character-select" style="width: 100%;">
                        <option value="">请选择汉字</option>
                        <?php 
                        // 获取所有汉字文章
                        $characters = get_posts(array(
                            'post_type' => 'chinese_character',
                            'post_status' => 'publish',
                            'posts_per_page' => -1,
                            'orderby' => 'title',
                            'order' => 'ASC'
                        ));
                        
                        foreach ($characters as $character): ?>
                            <option value="<?php echo esc_attr($character->post_title); ?>" <?php selected($calligraphy_character, $character->post_title); ?>>
                                <?php echo esc_html($character->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">选择或搜索此书法作品对应的汉字</p>
                </td>
            </tr>
        </table>
        
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#calligraphy_character').select2({
                placeholder: "搜索并选择汉字",
                allowClear: true,
                width: '100%'
            });
        });
        </script>
        <?php
    }
    
    /**
     * 书法作品书法家信息元框
     */
    public function render_calligraphy_artist_meta_box($post) {
        $calligraphy_artist = get_post_meta($post->ID, '_calligraphy_artist', true);
        $calligraphy_dynasty = get_post_meta($post->ID, '_calligraphy_dynasty', true);
        $calligraphy_year = get_post_meta($post->ID, '_calligraphy_year', true);
        $calligraphy_style = get_post_meta($post->ID, '_calligraphy_style', true);
        $calligraphy_provenance = get_post_meta($post->ID, '_calligraphy_provenance', true);
        $calligraphy_collection = get_post_meta($post->ID, '_calligraphy_collection', true);
        $calligraphy_full_work = get_post_meta($post->ID, '_calligraphy_full_work', true);
        $calligraphy_character_images = get_post_meta($post->ID, '_calligraphy_character_images', true);
        
        // 获取所有博物馆文章
        $museums = $this->get_museums_list();
        ?>
        <table class="form-table">
            <tr>
                <th><label for="calligraphy_artist">书法家</label></th>
                <td>
                    <input type="text" id="calligraphy_artist" name="calligraphy_artist" value="<?php echo esc_attr($calligraphy_artist); ?>" class="regular-text" />
                    <p class="description">输入书法家姓名</p>
                </td>
            </tr>
            <tr>
                <th><label for="calligraphy_dynasty">朝代</label></th>
                <td>
                    <input type="text" id="calligraphy_dynasty" name="calligraphy_dynasty" value="<?php echo esc_attr($calligraphy_dynasty); ?>" class="regular-text" />
                    <p class="description">输入书法家所处朝代</p>
                </td>
            </tr>
            <tr>
                <th><label for="calligraphy_year">年代</label></th>
                <td>
                    <input type="text" id="calligraphy_year" name="calligraphy_year" value="<?php echo esc_attr($calligraphy_year); ?>" class="regular-text" />
                    <p class="description">输入作品创作年代</p>
                </td>
            </tr>
            <tr>
                <th><label for="calligraphy_style">书体</label></th>
                <td>
                    <select id="calligraphy_style" name="calligraphy_style" class="regular-text">
                        <option value="">请选择书体</option>
                        <option value="楷书" <?php selected($calligraphy_style, '楷书'); ?>>楷书</option>
                        <option value="行书" <?php selected($calligraphy_style, '行书'); ?>>行书</option>
                        <option value="草书" <?php selected($calligraphy_style, '草书'); ?>>草书</option>
                        <option value="隶书" <?php selected($calligraphy_style, '隶书'); ?>>隶书</option>
                        <option value="篆书" <?php selected($calligraphy_style, '篆书'); ?>>篆书</option>
                        <option value="魏碑" <?php selected($calligraphy_style, '魏碑'); ?>>魏碑</option>
                    </select>
                    <p class="description">选择书法作品的书体</p>
                </td>
            </tr>
            <tr>
                <th><label for="calligraphy_provenance">作品出处</label></th>
                <td>
                    <input type="text" id="calligraphy_provenance" name="calligraphy_provenance" value="<?php echo esc_attr($calligraphy_provenance); ?>" class="regular-text" />
                    <p class="description">输入作品的出处信息（如碑刻、法帖等）</p>
                </td>
            </tr>
            <tr>
                <th><label for="calligraphy_collection">现在馆藏</label></th>
                <td>
                    <select id="calligraphy_collection" name="calligraphy_collection" class="regular-text chinese-museum-select">
                        <option value="">请选择馆藏位置</option>
                        <option value="私人收藏" <?php selected($calligraphy_collection, '私人收藏'); ?>>私人收藏</option>
                        <option value="未知" <?php selected($calligraphy_collection, '未知'); ?>>未知</option>
                        <?php foreach ($museums as $museum): ?>
                            <option value="<?php echo esc_attr($museum->post_title); ?>" <?php selected($calligraphy_collection, $museum->post_title); ?>>
                                <?php echo esc_html($museum->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">选择作品现在馆藏位置</p>
                </td>
            </tr>
            <tr>
                <th><label for="calligraphy_character_images">单字字形图片</label></th>
                <td>
                    <input type="hidden" name="calligraphy_character_images_nonce" value="<?php echo wp_create_nonce('calligraphy_character_images_nonce'); ?>" />
                    <input type="file" id="calligraphy_character_images" name="calligraphy_character_images[]" accept="image/*" multiple />
                    <button type="button" class="button" id="calligraphy_character_images_media_button">从媒体库选择</button>
                    <?php if ($calligraphy_character_images && is_array($calligraphy_character_images)): ?>
                        <div class="character-images-preview">
                            <p>当前单字字形图片:</p>
                            <div class="image-preview-container">
                                <?php foreach ($calligraphy_character_images as $image_id): ?>
                                    <div class="image-preview-item">
                                        <img src="<?php echo esc_url(wp_get_attachment_url($image_id)); ?>" style="max-width: 100px; height: auto;" />
                                        <label>
                                            <input type="checkbox" name="calligraphy_remove_character_images[]" value="<?php echo esc_attr($image_id); ?>" /> 删除
                                        </label>
                                        <?php 
                                        // 获取图片说明文字
                                        $image_captions = get_post_meta($post->ID, '_calligraphy_character_image_captions', true);
                                        $caption = isset($image_captions[$image_id]) ? $image_captions[$image_id] : '';
                                        ?>
                                        <div class="image-caption-field">
                                            <label>说明文字:
                                                <input type="text" name="calligraphy_character_image_captions[<?php echo esc_attr($image_id); ?>]" value="<?php echo esc_attr($caption); ?>" style="width: 100%;" />
                                            </label>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                    <p class="description">上传单字字形的书法作品图片（可多张）</p>
                </td>
            </tr>
            <tr>
                <th><label for="calligraphy_full_work">完整作品</label></th>
                <td>
                    <input type="hidden" name="calligraphy_full_work_nonce" value="<?php echo wp_create_nonce('calligraphy_full_work_nonce'); ?>" />
                    <input type="file" id="calligraphy_full_work" name="calligraphy_full_work[]" accept="image/*" multiple />
                    <button type="button" class="button" id="calligraphy_full_work_media_button">从媒体库选择</button>
                    <?php if ($calligraphy_full_work && is_array($calligraphy_full_work)): ?>
                        <div class="full-work-preview">
                            <p>当前完整作品:</p>
                            <div class="image-preview-container">
                                <?php foreach ($calligraphy_full_work as $image_id): ?>
                                    <div class="image-preview-item">
                                        <img src="<?php echo esc_url(wp_get_attachment_url($image_id)); ?>" style="max-width: 100px; height: auto;" />
                                        <label>
                                            <input type="checkbox" name="calligraphy_remove_full_work[]" value="<?php echo esc_attr($image_id); ?>" /> 删除
                                        </label>
                                        <?php 
                                        // 获取图片说明文字
                                        $image_captions = get_post_meta($post->ID, '_calligraphy_full_work_captions', true);
                                        $caption = isset($image_captions[$image_id]) ? $image_captions[$image_id] : '';
                                        ?>
                                        <div class="image-caption-field">
                                            <label>说明文字:
                                                <input type="text" name="calligraphy_full_work_captions[<?php echo esc_attr($image_id); ?>]" value="<?php echo esc_attr($caption); ?>" style="width: 100%;" />
                                            </label>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                    <p class="description">上传完整的书法作品图片（可多张）</p>
                </td>
            </tr>
        </table>
        
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('.chinese-museum-select').select2({
                placeholder: "搜索并选择馆藏位置",
                allowClear: true,
                width: '100%'
            });
            
            // 单字字形图片媒体库选择按钮
            $('#calligraphy_character_images_media_button').on('click', function(e) {
                e.preventDefault();
                
                // 创建媒体框架
                var characterImageFrame = wp.media({
                    title: '选择单字字形图片',
                    multiple: true,
                    library: {
                        type: 'image'
                    },
                    button: {
                        text: '使用选中的图片'
                    }
                });
                
                // 当选择图片时的处理
                characterImageFrame.on('select', function() {
                    var selection = characterImageFrame.state().get('selection');
                    selection.map(function(attachment) {
                        attachment = attachment.toJSON();
                        // 创建隐藏的input元素来存储选中的图片ID
                        var input = $('<input type="hidden" name="calligraphy_selected_character_images[]" value="' + attachment.id + '">');
                        $('#calligraphy_character_images_media_button').after(input);
                    });
                    
                    // 提交表单以保存选中的图片
                    $('#post').submit();
                });
                
                // 打开媒体框架
                characterImageFrame.open();
            });
            
            // 完整作品图片媒体库选择按钮
            $('#calligraphy_full_work_media_button').on('click', function(e) {
                e.preventDefault();
                
                // 创建媒体框架
                var fullWorkFrame = wp.media({
                    title: '选择完整作品图片',
                    multiple: true,
                    library: {
                        type: 'image'
                    },
                    button: {
                        text: '使用选中的图片'
                    }
                });
                
                // 当选择图片时的处理
                fullWorkFrame.on('select', function() {
                    var selection = fullWorkFrame.state().get('selection');
                    selection.map(function(attachment) {
                        attachment = attachment.toJSON();
                        // 创建隐藏的input元素来存储选中的图片ID
                        var input = $('<input type="hidden" name="calligraphy_selected_full_work[]" value="' + attachment.id + '">');
                        $('#calligraphy_full_work_media_button').after(input);
                    });
                    
                    // 提交表单以保存选中的图片
                    $('#post').submit();
                });
                
                // 打开媒体框架
                fullWorkFrame.open();
            });
        });
        </script>
        <?php
    }
    
    /**
     * 保存书法作品元数据
     */
    public function save_calligraphy_meta($post_id) {
        // 检查是否是自动保存
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // 检查用户权限
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // 检查文章类型
        if (get_post_type($post_id) !== 'chinese_calligraphy') {
            return;
        }
        
        // 保存汉字信息
        if (isset($_POST['calligraphy_character'])) {
            update_post_meta($post_id, '_calligraphy_character', sanitize_text_field($_POST['calligraphy_character']));
        }
        
        // 保存书法家信息
        if (isset($_POST['calligraphy_artist'])) {
            update_post_meta($post_id, '_calligraphy_artist', sanitize_text_field($_POST['calligraphy_artist']));
        }
        
        // 保存朝代信息
        if (isset($_POST['calligraphy_dynasty'])) {
            update_post_meta($post_id, '_calligraphy_dynasty', sanitize_text_field($_POST['calligraphy_dynasty']));
        }
        
        // 保存年代信息
        if (isset($_POST['calligraphy_year'])) {
            update_post_meta($post_id, '_calligraphy_year', sanitize_text_field($_POST['calligraphy_year']));
        }
        
        // 保存书体信息
        if (isset($_POST['calligraphy_style'])) {
            update_post_meta($post_id, '_calligraphy_style', sanitize_text_field($_POST['calligraphy_style']));
        }
        
        // 保存作品出处信息
        if (isset($_POST['calligraphy_provenance'])) {
            update_post_meta($post_id, '_calligraphy_provenance', sanitize_text_field($_POST['calligraphy_provenance']));
        }
        
        // 保存现在馆藏信息
        if (isset($_POST['calligraphy_collection'])) {
            update_post_meta($post_id, '_calligraphy_collection', sanitize_text_field($_POST['calligraphy_collection']));
        }
        
        // 处理单字字形图片上传
        if (isset($_POST['calligraphy_character_images_nonce']) && wp_verify_nonce($_POST['calligraphy_character_images_nonce'], 'calligraphy_character_images_nonce')) {
            // 获取现有的单字字形图片
            $existing_character_images = get_post_meta($post_id, '_calligraphy_character_images', true);
            if (!$existing_character_images || !is_array($existing_character_images)) {
                $existing_character_images = array();
            }
            
            // 处理从媒体库选择的单字字形图片
            if (isset($_POST['calligraphy_selected_character_images']) && is_array($_POST['calligraphy_selected_character_images'])) {
                foreach ($_POST['calligraphy_selected_character_images'] as $image_id) {
                    $image_id = intval($image_id);
                    // 检查图片ID是否已存在，避免重复添加
                    if (!in_array($image_id, $existing_character_images)) {
                        $existing_character_images[] = $image_id;
                    }
                }
            }
            
            // 处理删除的单字字形图片
            if (isset($_POST['calligraphy_remove_character_images']) && is_array($_POST['calligraphy_remove_character_images'])) {
                foreach ($_POST['calligraphy_remove_character_images'] as $image_id) {
                    $image_id = intval($image_id);
                    $existing_character_images = array_diff($existing_character_images, array($image_id));
                }
            }
            
            // 上传新的单字字形图片
            if (isset($_FILES['calligraphy_character_images']) && !empty($_FILES['calligraphy_character_images']['name'][0])) {
                $files = $_FILES['calligraphy_character_images'];
                $file_count = count($files['name']);
                
                for ($i = 0; $i < $file_count; $i++) {
                    if (!empty($files['name'][$i])) {
                        $file = array(
                            'name'     => $files['name'][$i],
                            'type'     => $files['type'][$i],
                            'tmp_name' => $files['tmp_name'][$i],
                            'error'    => $files['error'][$i],
                            'size'     => $files['size'][$i]
                        );
                        
                        // 设置上传参数
                        $upload_overrides = array('test_form' => false);
                        
                        // 执行上传
                        $movefile = wp_handle_upload($file, $upload_overrides);
                        
                        if ($movefile && !isset($movefile['error'])) {
                            // 创建附件
                            $attachment = array(
                                'guid'           => $movefile['url'],
                                'post_mime_type' => $movefile['type'],
                                'post_title'     => preg_replace('/\.[^.]+$/', '', basename($file['name'])),
                                'post_content'   => '',
                                'post_status'    => 'inherit'
                            );
                            
                            $attach_id = wp_insert_attachment($attachment, $movefile['file'], $post_id);
                            
                            // 生成附件元数据
                            require_once(ABSPATH . 'wp-admin/includes/image.php');
                            $attach_data = wp_generate_attachment_metadata($attach_id, $movefile['file']);
                            wp_update_attachment_metadata($attach_id, $attach_data);
                            
                            // 添加附件ID到数组
                            $existing_character_images[] = $attach_id;
                        }
                    }
                }
            }
            
            // 保存单字字形图片数组
            if (!empty($existing_character_images)) {
                update_post_meta($post_id, '_calligraphy_character_images', $existing_character_images);
                
                // 保存单字字形图片说明文字
                if (isset($_POST['calligraphy_character_image_captions'])) {
                    $captions = array();
                    foreach ($_POST['calligraphy_character_image_captions'] as $image_id => $caption) {
                        $captions[sanitize_text_field($image_id)] = sanitize_textarea_field($caption);
                    }
                    update_post_meta($post_id, '_calligraphy_character_image_captions', $captions);
                }
            } else {
                delete_post_meta($post_id, '_calligraphy_character_images');
                delete_post_meta($post_id, '_calligraphy_character_image_captions');
            }
        }
        
        // 处理完整作品上传
        if (isset($_POST['calligraphy_full_work_nonce']) && wp_verify_nonce($_POST['calligraphy_full_work_nonce'], 'calligraphy_full_work_nonce')) {
            // 获取现有的完整作品
            $existing_full_work = get_post_meta($post_id, '_calligraphy_full_work', true);
            if (!$existing_full_work || !is_array($existing_full_work)) {
                $existing_full_work = array();
            }
            
            // 处理从媒体库选择的完整作品
            if (isset($_POST['calligraphy_selected_full_work']) && is_array($_POST['calligraphy_selected_full_work'])) {
                foreach ($_POST['calligraphy_selected_full_work'] as $image_id) {
                    $image_id = intval($image_id);
                    // 检查图片ID是否已存在，避免重复添加
                    if (!in_array($image_id, $existing_full_work)) {
                        $existing_full_work[] = $image_id;
                    }
                }
            }
            
            // 处理删除的完整作品
            if (isset($_POST['calligraphy_remove_full_work']) && is_array($_POST['calligraphy_remove_full_work'])) {
                foreach ($_POST['calligraphy_remove_full_work'] as $image_id) {
                    $image_id = intval($image_id);
                    $existing_full_work = array_diff($existing_full_work, array($image_id));
                }
            }
            
            // 上传新的完整作品
            if (isset($_FILES['calligraphy_full_work']) && !empty($_FILES['calligraphy_full_work']['name'][0])) {
                $files = $_FILES['calligraphy_full_work'];
                $file_count = count($files['name']);
                
                for ($i = 0; $i < $file_count; $i++) {
                    if (!empty($files['name'][$i])) {
                        $file = array(
                            'name'     => $files['name'][$i],
                            'type'     => $files['type'][$i],
                            'tmp_name' => $files['tmp_name'][$i],
                            'error'    => $files['error'][$i],
                            'size'     => $files['size'][$i]
                        );
                        
                        // 设置上传参数
                        $upload_overrides = array('test_form' => false);
                        
                        // 执行上传
                        $movefile = wp_handle_upload($file, $upload_overrides);
                        
                        if ($movefile && !isset($movefile['error'])) {
                            // 创建附件
                            $attachment = array(
                                'guid'           => $movefile['url'],
                                'post_mime_type' => $movefile['type'],
                                'post_title'     => preg_replace('/\.[^.]+$/', '', basename($file['name'])),
                                'post_content'   => '',
                                'post_status'    => 'inherit'
                            );
                            
                            $attach_id = wp_insert_attachment($attachment, $movefile['file'], $post_id);
                            
                            // 生成附件元数据
                            require_once(ABSPATH . 'wp-admin/includes/image.php');
                            $attach_data = wp_generate_attachment_metadata($attach_id, $movefile['file']);
                            wp_update_attachment_metadata($attach_id, $attach_data);
                            
                            // 添加附件ID到数组
                            $existing_full_work[] = $attach_id;
                        }
                    }
                }
            }
            
            // 保存完整作品数组
            if (!empty($existing_full_work)) {
                update_post_meta($post_id, '_calligraphy_full_work', $existing_full_work);
                
                // 保存完整作品图片说明文字
                if (isset($_POST['calligraphy_full_work_captions'])) {
                    $captions = array();
                    foreach ($_POST['calligraphy_full_work_captions'] as $image_id => $caption) {
                        $captions[sanitize_text_field($image_id)] = sanitize_textarea_field($caption);
                    }
                    update_post_meta($post_id, '_calligraphy_full_work_captions', $captions);
                }
            } else {
                delete_post_meta($post_id, '_calligraphy_full_work');
                delete_post_meta($post_id, '_calligraphy_full_work_captions');
            }
        }
    }
    
    /**
     * 保存古籍元数据
     */
    public function save_ancient_text_meta($post_id) {
        // 验证nonce
        if (!isset($_POST['ancient_text_meta_nonce']) || !wp_verify_nonce($_POST['ancient_text_meta_nonce'], 'save_ancient_text_meta')) {
            return;
        }
        
        // 检查是否是自动保存
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // 检查用户权限
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // 检查文章类型
        if (get_post_type($post_id) !== 'chinese_ancient_text') {
            return;
        }
        
        // 保存古籍基本信息
        if (isset($_POST['ancient_text_dynasty'])) {
            update_post_meta($post_id, '_ancient_text_dynasty', sanitize_text_field($_POST['ancient_text_dynasty']));
        }
        
        if (isset($_POST['ancient_text_author'])) {
            update_post_meta($post_id, '_ancient_text_author', sanitize_text_field($_POST['ancient_text_author']));
        }
        
        if (isset($_POST['ancient_text_publisher'])) {
            update_post_meta($post_id, '_ancient_text_publisher', sanitize_text_field($_POST['ancient_text_publisher']));
        }
        
        if (isset($_POST['ancient_text_publication_year'])) {
            update_post_meta($post_id, '_ancient_text_publication_year', sanitize_text_field($_POST['ancient_text_publication_year']));
        }
        
        if (isset($_POST['ancient_text_volume'])) {
            update_post_meta($post_id, '_ancient_text_volume', sanitize_text_field($_POST['ancient_text_volume']));
        }
        
        if (isset($_POST['ancient_text_chapter'])) {
            update_post_meta($post_id, '_ancient_text_chapter', sanitize_text_field($_POST['ancient_text_chapter']));
        }
        
        // 保存经史子集分类
        if (isset($_POST['ancient_text_category'])) {
            update_post_meta($post_id, '_ancient_text_category', sanitize_text_field($_POST['ancient_text_category']));
        }
        
        // 保存古籍内容
        if (isset($_POST['ancient_text_content'])) {
            update_post_meta($post_id, '_ancient_text_content', wp_kses_post($_POST['ancient_text_content']));
        }
        
        // 保存章节内容
        if (isset($_POST['ancient_text_chapters'])) {
            $chapters = array();
            foreach ($_POST['ancient_text_chapters'] as $chapter_data) {
                if (!empty($chapter_data['volume']) || !empty($chapter_data['chapter']) || !empty($chapter_data['content'])) {
                    $chapters[] = array(
                        'volume' => sanitize_text_field($chapter_data['volume']),
                        'chapter' => sanitize_text_field($chapter_data['chapter']),
                        'content' => wp_kses_post($chapter_data['content'])
                    );
                }
            }
            update_post_meta($post_id, '_ancient_text_chapters', $chapters);
        } else {
            delete_post_meta($post_id, '_ancient_text_chapters');
        }
        
        // 保存关联汉字
        if (isset($_POST['ancient_text_related_characters'])) {
            $related_characters = array_map('intval', $_POST['ancient_text_related_characters']);
            update_post_meta($post_id, '_ancient_text_related_characters', $related_characters);
        } else {
            // 如果没有选择任何汉字，则清空关联数据
            update_post_meta($post_id, '_ancient_text_related_characters', array());
        }
    }
    
    /**
     * 保存博物馆元数据
     */
    public function save_museum_meta($post_id) {
        // 检查是否是自动保存
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // 检查用户权限
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // 检查nonce
        if (!isset($_POST['museum_meta_nonce']) || !wp_verify_nonce($_POST['museum_meta_nonce'], 'save_museum_meta')) {
            return;
        }
        
        // 保存博物馆基本信息
        if (isset($_POST['museum_location'])) {
            update_post_meta($post_id, '_museum_location', sanitize_text_field($_POST['museum_location']));
        }
        
        if (isset($_POST['museum_founded_year'])) {
            update_post_meta($post_id, '_museum_founded_year', sanitize_text_field($_POST['museum_founded_year']));
        }
        
        if (isset($_POST['museum_director'])) {
            update_post_meta($post_id, '_museum_director', sanitize_text_field($_POST['museum_director']));
        }
        
        if (isset($_POST['museum_website'])) {
            update_post_meta($post_id, '_museum_website', esc_url_raw($_POST['museum_website']));
        }
    }
    
    /**
     * 保存藏品元数据
     */
    public function save_collection_meta($post_id) {
        // 检查是否是自动保存
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        // 检查用户权限
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }
        
        // 检查nonce
        if (!isset($_POST['collection_meta_nonce']) || !wp_verify_nonce($_POST['collection_meta_nonce'], 'save_collection_meta')) {
            return;
        }
        
        // 保存藏品基本信息
        if (isset($_POST['collection_dynasty'])) {
            update_post_meta($post_id, '_collection_dynasty', sanitize_text_field($_POST['collection_dynasty']));
        }
        
        if (isset($_POST['collection_category'])) {
            update_post_meta($post_id, '_collection_category', sanitize_text_field($_POST['collection_category']));
        }
        
        if (isset($_POST['collection_material'])) {
            update_post_meta($post_id, '_collection_material', sanitize_text_field($_POST['collection_material']));
        }
        
        if (isset($_POST['collection_dimensions'])) {
            update_post_meta($post_id, '_collection_dimensions', sanitize_text_field($_POST['collection_dimensions']));
        }
        
        if (isset($_POST['collection_acquisition_date'])) {
            update_post_meta($post_id, '_collection_acquisition_date', sanitize_text_field($_POST['collection_acquisition_date']));
        }
        
        // 保存藏品类别
        if (isset($_POST['collection_type'])) {
            update_post_meta($post_id, '_collection_type', sanitize_text_field($_POST['collection_type']));
        }
        
        // 保存关联博物馆
        if (isset($_POST['collection_related_museum'])) {
            update_post_meta($post_id, '_collection_related_museum', intval($_POST['collection_related_museum']));
        }
        
        // 保存藏品介绍文字
        if (isset($_POST['collection_description'])) {
            update_post_meta($post_id, '_collection_description', wp_kses_post($_POST['collection_description']));
        }
    }
    
    /**
     * 加载后台脚本
     */
    public function admin_scripts($hook) {
        global $post_type;
        
        // 为书法作品编辑页面添加文件上传支持
        if (($hook == 'post-new.php' || $hook == 'post.php') && $post_type === 'chinese_calligraphy') {
            add_action('post_edit_form_tag', array($this, 'add_enctype_to_form'));
        }
        
        if ($hook == 'post-new.php' || $hook == 'post.php') {
            if ($post_type === 'chinese_character' || $post_type === 'chinese_dictionary' || $post_type === 'chinese_idiom' || $post_type === 'chinese_calligraphy' || $post_type === 'chinese_ancient_text') {
                // 加载Select2 CSS
                wp_enqueue_style(
                    'chinese-character-select2-css',
                    'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css'
                );
                
                // 加载Select2 JS
                wp_enqueue_script(
                    'chinese-character-select2-js',
                    'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js',
                    array('jquery'),
                    '4.0.13',
                    true
                );
                
                // 加载自定义JS
                wp_enqueue_script(
                    'chinese-character-admin-js', 
                    plugin_dir_url(__FILE__) . 'assets/admin.js', 
                    array('jquery', 'chinese-character-select2-js'), 
                    '1.0.0', 
                    true
                );
            }
        }
    }
    
    /**
     * 为书法作品编辑表单添加enctype属性以支持文件上传
     */
    public function add_enctype_to_form() {
        echo ' enctype="multipart/form-data"';
    }
    
    /**
     * 加载前端脚本
     */
    public function frontend_scripts() {
        wp_enqueue_style('character-frontend-css', plugin_dir_url(__FILE__) . 'assets/frontend.css');
        wp_enqueue_script('character-frontend-js', plugin_dir_url(__FILE__) . 'assets/frontend.js', array('jquery'), '1.0.0', true);
        wp_localize_script('character-frontend-js', 'character_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'site_url' => home_url()
        ));
        
        // 在搜索结果页面也加载脚本
        if (is_search()) {
            wp_enqueue_script('character-frontend-js');
            wp_enqueue_style('character-frontend-css');
        }
    }
    
    /**
     * 短代码显示字典
     */
    public function character_dictionary_shortcode($atts) {
        ob_start();
        include(plugin_dir_path(__FILE__) . 'templates/dictionary-template.php');
        return ob_get_clean();
    }
    
    /**
     * 自定义搜索模板
     */
    public function custom_search_template($template) {
        // 检查是否是搜索结果页面且搜索的是汉字
        if (is_search() && get_query_var('post_type') === 'chinese_character') {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/search-chinese_character.php') && 
                !file_exists(get_template_directory() . '/search-chinese_character.php')) {
                
                return plugin_dir_path(__FILE__) . 'templates/search-character-template.php';
            }
        }
        
        return $template;
    }
    
    /**
     * 搜索汉字回调函数 - 增强版
     */
    public function search_character_callback() {
        $character = isset($_POST['character']) ? sanitize_text_field($_POST['character']) : '';
        
        if (empty($character)) {
            wp_send_json_error('请输入要查询的汉字');
        }
        
        // 直接查询数据库查找匹配的汉字文章
        global $wpdb;
        $post_id = $wpdb->get_var($wpdb->prepare(
            "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'chinese_character' AND post_status = 'publish' LIMIT 1",
            $character
        ));
        
        if ($post_id) {
            // 获取文章对象
            $post = get_post($post_id);
            
            if ($post) {
                $data = array(
                    'ID' => $post->ID,
                    'title' => $post->post_title,
                    'content' => $post->post_content,
                    'pinyin' => get_post_meta($post->ID, '_character_pinyin', true),
                    'radical' => get_post_meta($post->ID, '_character_radical', true),
                    'stroke_count' => get_post_meta($post->ID, '_character_stroke_count', true),
                    'traditional_form' => get_post_meta($post->ID, '_character_traditional_form', true),
                    'variants' => get_post_meta($post->ID, '_character_variants', true),
                    'detailed_explanation' => get_post_meta($post->ID, '_character_detailed_explanation', true),
                    'guoyu_dictionary' => get_post_meta($post->ID, '_character_guoyu_dictionary', true),
                    'kangxi_dictionary' => get_post_meta($post->ID, '_character_kangxi_dictionary', true),
                    'shuowen_jiezi' => get_post_meta($post->ID, '_character_shuowen_jiezi', true),
                    'dialects' => get_post_meta($post->ID, '_character_dialects', true),
                    'etymology' => get_post_meta($post->ID, '_character_etymology', true),
                    'other_meanings' => get_post_meta($post->ID, '_character_other_meanings', true)
                );
                
                wp_send_json_success($data);
            }
        }
        
        wp_send_json_error('未找到相关汉字');
    }

    /**
     * 获取相关词语列表（AJAX回调）
     */
    public function get_related_dictionaries_callback() {
        $character = sanitize_text_field($_POST['character']);
        
        // 查询包含该汉字的词语
        $args = array(
            'post_type' => 'chinese_dictionary',
            'post_status' => 'publish',
            'posts_per_page' => 20,
            's' => $character
        );
        
        $dictionary_query = new WP_Query($args);
        $dictionaries = array();
        
        if ($dictionary_query->have_posts()) {
            while ($dictionary_query->have_posts()) {
                $dictionary_query->the_post();
                $dictionaries[] = array(
                    'id' => get_the_ID(),
                    'title' => get_the_title(),
                    'permalink' => get_permalink(),
                    'pinyin' => get_post_meta(get_the_ID(), '_dictionary_pinyin', true)
                );
            }
            wp_reset_postdata();
        }
        
        wp_send_json_success($dictionaries);
    }
    
    /**
     * 获取相关成语列表（AJAX回调）
     */
    public function get_related_idioms_callback() {
        $character = sanitize_text_field($_POST['character']);
        
        // 查询包含该汉字的成语
        $args = array(
            'post_type' => 'chinese_idiom',
            'post_status' => 'publish',
            'posts_per_page' => 20,
            's' => $character
        );
        
        $idiom_query = new WP_Query($args);
        $idioms = array();
        
        if ($idiom_query->have_posts()) {
            while ($idiom_query->have_posts()) {
                $idiom_query->the_post();
                $idioms[] = array(
                    'id' => get_the_ID(),
                    'title' => get_the_title(),
                    'permalink' => get_permalink(),
                    'pinyin' => get_post_meta(get_the_ID(), '_idiom_pinyin', true)
                );
            }
            wp_reset_postdata();
        }
        
        wp_send_json_success($idioms);
    }

    /**
     * 获取指定汉字的书法作品（AJAX回调）
     */
    public function get_calligraphy_by_character_callback() {
        $character = sanitize_text_field($_POST['character']);
        
        if (empty($character)) {
            wp_send_json_error('汉字参数不能为空');
        }
        
        // 查询包含指定汉字的书法作品
        $args = array(
            'post_type' => 'chinese_calligraphy',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'meta_query' => array(
                array(
                    'key' => '_calligraphy_character',
                    'value' => $character,
                    'compare' => '='
                )
            )
        );
        
        $calligraphy_query = new WP_Query($args);
        $calligraphies = array();
        
        if ($calligraphy_query->have_posts()) {
            while ($calligraphy_query->have_posts()) {
                $calligraphy_query->the_post();
                
                // 获取单字字形图片
                $character_images = get_post_meta(get_the_ID(), '_calligraphy_character_images', true);
                $character_images_data = array();
                
                if ($character_images && is_array($character_images)) {
                    foreach ($character_images as $image_id) {
                        $image_url = wp_get_attachment_url($image_id);
                        if ($image_url) {
                            $character_images_data[] = array(
                                'id' => $image_id,
                                'url' => $image_url,
                                'thumbnail' => wp_get_attachment_image_src($image_id, 'thumbnail')[0]
                            );
                        }
                    }
                }
                
                $calligraphies[] = array(
                    'id' => get_the_ID(),
                    'title' => get_the_title(),
                    'permalink' => get_permalink(),
                    'thumbnail' => get_the_post_thumbnail_url(get_the_ID(), 'medium'),
                    'character' => get_post_meta(get_the_ID(), '_calligraphy_character', true),
                    'style' => get_post_meta(get_the_ID(), '_calligraphy_style', true),
                    'artist' => get_post_meta(get_the_ID(), '_calligraphy_artist', true),
                    'dynasty' => get_post_meta(get_the_ID(), '_calligraphy_dynasty', true),
                    'year' => get_post_meta(get_the_ID(), '_calligraphy_year', true),
                    'character_images' => $character_images_data
                );
            }
            wp_reset_postdata();
        }
        
        wp_send_json_success($calligraphies);
    }
    
    /**
     * 筛选书法作品（AJAX回调）
     */
    public function filter_calligraphy_callback() {
        $meta_query = array('relation' => 'AND');
        
        // 按汉字筛选
        if (!empty($_POST['character'])) {
            $meta_query[] = array(
                'key' => '_calligraphy_character',
                'value' => sanitize_text_field($_POST['character']),
                'compare' => '='
            );
        }
        
        // 按书体筛选
        if (!empty($_POST['style'])) {
            $meta_query[] = array(
                'key' => '_calligraphy_style',
                'value' => sanitize_text_field($_POST['style']),
                'compare' => '='
            );
        }
        
        // 按书法家筛选
        if (!empty($_POST['artist'])) {
            $meta_query[] = array(
                'key' => '_calligraphy_artist',
                'value' => sanitize_text_field($_POST['artist']),
                'compare' => 'LIKE'
            );
        }
        
        // 按朝代筛选
        if (!empty($_POST['dynasty'])) {
            $meta_query[] = array(
                'key' => '_calligraphy_dynasty',
                'value' => sanitize_text_field($_POST['dynasty']),
                'compare' => 'LIKE'
            );
        }
        
        $args = array(
            'post_type' => 'chinese_calligraphy',
            'post_status' => 'publish',
            'posts_per_page' => -1,
        );
        
        if (count($meta_query) > 1) {
            $args['meta_query'] = $meta_query;
        }
        
        $calligraphy_query = new WP_Query($args);
        $calligraphies = array();
        
        if ($calligraphy_query->have_posts()) {
            while ($calligraphy_query->have_posts()) {
                $calligraphy_query->the_post();
                
                $calligraphies[] = array(
                    'id' => get_the_ID(),
                    'title' => get_the_title(),
                    'permalink' => get_permalink(),
                    'thumbnail' => get_the_post_thumbnail_url(get_the_ID(), 'medium'),
                    'character' => get_post_meta(get_the_ID(), '_calligraphy_character', true),
                    'style' => get_post_meta(get_the_ID(), '_calligraphy_style', true),
                    'artist' => get_post_meta(get_the_ID(), '_calligraphy_artist', true),
                    'dynasty' => get_post_meta(get_the_ID(), '_calligraphy_dynasty', true),
                    'year' => get_post_meta(get_the_ID(), '_calligraphy_year', true)
                );
            }
            wp_reset_postdata();
        }
        
        wp_send_json_success($calligraphies);
    }
    
    /**
     * 获取书法家列表（AJAX回调）
     */
    public function get_calligraphy_artists_callback() {
        global $wpdb;
        
        // 获取所有书法家及其作品数量
        $artists = $wpdb->get_results("
            SELECT meta_value as name, COUNT(*) as count
            FROM {$wpdb->postmeta}
            WHERE meta_key = '_calligraphy_artist' AND meta_value != ''
            GROUP BY meta_value
            ORDER BY count DESC
        ");
        
        wp_send_json_success($artists);
    }
    
    /**
     * 获取朝代列表（AJAX回调）
     */
    public function get_calligraphy_dynasties_callback() {
        global $wpdb;
        
        // 获取所有朝代及其作品数量
        $dynasties = $wpdb->get_results("
            SELECT meta_value as name, COUNT(*) as count
            FROM {$wpdb->postmeta}
            WHERE meta_key = '_calligraphy_dynasty' AND meta_value != ''
            GROUP BY meta_value
            ORDER BY count DESC
        ");
        
        wp_send_json_success($dynasties);
    }
    
    /**
     * 获取书体列表（AJAX回调）
     */
    public function get_calligraphy_styles_callback() {
        global $wpdb;
        
        // 获取所有书体及其作品数量
        $styles = $wpdb->get_results("
            SELECT meta_value as name, COUNT(*) as count
            FROM {$wpdb->postmeta}
            WHERE meta_key = '_calligraphy_style' AND meta_value != ''
            GROUP BY meta_value
            ORDER BY count DESC
        ");
        
        wp_send_json_success($styles);
    }
    
    /**
     * 添加自定义查询变量
     */
    public function add_query_vars($vars) {
        $vars[] = 'pinyin_index';
        $vars[] = 'radical_index';
        $vars[] = 'professional_search';
        $vars[] = 'dialect_research';
        $vars[] = 'subcategory';
        $vars[] = 'category_search';
        return $vars;
    }

    /**
     * 在WordPress初始化时添加重写规则
     */
    public function add_rewrite_rules() {
        add_rewrite_rule(
            'character/([^/]+)/?$',
            'index.php?post_type=chinese_character&name=$matches[1]',
            'top'
        );
        
        // 添加拼音索引页面规则
        add_rewrite_rule(
            'pinyin-index/?$',
            'index.php?pinyin_index=1',
            'top'
        );
        
        // 添加部首索引页面规则
        add_rewrite_rule(
            'radical-index/?$',
            'index.php?radical_index=1',
            'top'
        );
        
        // 添加专业搜索页面规则
        add_rewrite_rule(
            'professional-search/?$',
            'index.php?professional_search=1',
            'top'
        );
        
        // 添加方言研究页面规则
        add_rewrite_rule(
            'dialect-research/?$',
            'index.php?dialect_research=1',
            'top'
        );
        
        // 添加博物馆归档页面规则
        add_rewrite_rule(
            'museums/?$',
            'index.php?post_type=chinese_museum',
            'top'
        );
        
        // 添加藏品归档页面规则
        add_rewrite_rule(
            'collections/?$',
            'index.php?post_type=chinese_collection',
            'top'
        );
    }
    
    /**
     * 处理模板重定向
     */
    public function character_template_redirect() {
        global $wp_query;
        
        // 检查是否是汉字文章类型
        if (is_singular('chinese_character')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/single-chinese_character.php') && 
                !file_exists(get_template_directory() . '/single-chinese_character.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/single-character-template.php');
                exit;
            }
        }
        
        // 检查是否是汉字归档页面
        if (is_post_type_archive('chinese_character')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/archive-chinese_character.php') && 
                !file_exists(get_template_directory() . '/archive-chinese_character.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/archive-character-template.php');
                exit;
            }
        }
        
        // 检查是否是词典文章类型
        if (is_singular('chinese_dictionary')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/single-chinese_dictionary.php') && 
                !file_exists(get_template_directory() . '/single-chinese_dictionary.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/single-dictionary-template.php');
                exit;
            }
        }
        
        // 检查是否是词典归档页面
        if (is_post_type_archive('chinese_dictionary')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/archive-chinese_dictionary.php') && 
                !file_exists(get_template_directory() . '/archive-dictionary-template.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/archive-dictionary-template.php');
                exit;
            }
        }
        
        // 检查是否是古籍文章类型
        if (is_singular('chinese_ancient_text')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/single-chinese_ancient_text.php') && 
                !file_exists(get_template_directory() . '/single-chinese_ancient_text.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/single-ancient-text-template.php');
                exit;
            }
        }
        
        // 检查是否是古籍归档页面
        if (is_post_type_archive('chinese_ancient_text')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/archive-chinese_ancient_text.php') && 
                !file_exists(get_template_directory() . '/archive-ancient-text-template.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/archive-ancient-text-template.php');
                exit;
            }
        }
        
        // 检查是否是书法文章类型
        if (is_singular('chinese_calligraphy')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/single-chinese_calligraphy.php') && 
                !file_exists(get_template_directory() . '/single-chinese_calligraphy.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/single-calligraphy-template.php');
                exit;
            }
        }
        
        // 检查是否是书法归档页面
        if (is_post_type_archive('chinese_calligraphy')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/archive-chinese_calligraphy.php') && 
                !file_exists(get_template_directory() . '/archive-calligraphy-template.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/archive-calligraphy-template.php');
                exit;
            }
        }
        
        // 检查是否是博物馆文章类型
        if (is_singular('chinese_museum')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/single-museum-template.php') && 
                !file_exists(get_template_directory() . '/single-museum-template.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/single-museum-template.php');
                exit;
            }
        }
        
        // 检查是否是藏品文章类型
        if (is_singular('chinese_collection')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/single-collection-template.php') && 
                !file_exists(get_template_directory() . '/single-collection-template.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/single-collection-template.php');
                exit;
            }
        }
        
        // 检查是否是博物馆归档页面
        if (is_post_type_archive('chinese_museum')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/archive-chinese_museum.php') && 
                !file_exists(get_template_directory() . '/archive-chinese_museum.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/archive-museum-template.php');
                exit;
            }
        }
        
        // 检查是否是藏品归档页面
        if (is_post_type_archive('chinese_collection')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/archive-chinese_collection.php') && 
                !file_exists(get_template_directory() . '/archive-chinese_collection.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/archive-collection-template.php');
                exit;
            }
        }
        
        // 检查是否是古籍章节文章类型
        if (is_singular('ancient_text_chapter')) {
            // 检查是否有阅读模式参数
            if (isset($_GET['mode']) && $_GET['mode'] === 'reading') {
                // 加载专业阅读模式模板
                if (!file_exists(get_stylesheet_directory() . '/single-ancient-text-chapter-reading-mode.php') && 
                    !file_exists(get_template_directory() . '/single-ancient-text-chapter-reading-mode.php')) {
                    
                    include(plugin_dir_path(__FILE__) . 'templates/single-ancient-text-chapter-reading-mode.php');
                    exit;
                }
            } else {
                // 加载普通章节模板
                if (!file_exists(get_stylesheet_directory() . '/single-ancient-text-chapter-template.php') && 
                    !file_exists(get_template_directory() . '/single-ancient-text-chapter-template.php')) {
                    
                    include(plugin_dir_path(__FILE__) . 'templates/single-ancient-text-chapter-template.php');
                    exit;
                }
            }
        }
        
        // 检查是否是成语文章类型
        if (is_singular('chinese_idiom')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/single-chinese_idiom.php') && 
                !file_exists(get_template_directory() . '/single-chinese_idiom.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/single-idiom-template.php');
                exit;
            }
        }
        
        // 检查是否是成语归档页面
        if (is_post_type_archive('chinese_idiom')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/archive-chinese_idiom.php') && 
                !file_exists(get_template_directory() . '/archive-idiom-template.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/archive-idiom-template.php');
                exit;
            }
        }
        
        // 检查是否是拼音索引页面
        if (get_query_var('pinyin_index')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/pinyin-index-template.php') && 
                !file_exists(get_template_directory() . '/pinyin-index-template.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/pinyin-index-template.php');
                exit;
            }
        }
        
        // 检查是否是部首索引页面
        if (get_query_var('radical_index')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/radical-index-template.php') && 
                !file_exists(get_template_directory() . '/radical-index-template.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/radical-index-template.php');
                exit;
            }
        }
        
        // 检查是否是专业搜索页面
        if (get_query_var('professional_search')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/professional-search-page.php') && 
                !file_exists(get_template_directory() . '/professional-search-page.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/professional-search-page.php');
                exit;
            }
        }
        
        // 检查是否是方言研究页面
        if (get_query_var('dialect_research')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/dialect-research-template.php') && 
                !file_exists(get_template_directory() . '/dialect-research-template.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/dialect-research-template.php');
                exit;
            }
        }
    }
    
    
    
    /**
     * 在WordPress初始化时添加重写规则
     */
    // public function add_rewrite_rules() {
    //     add_rewrite_rule(
    //         'character/([^/]+)/?$',
    //         'index.php?post_type=chinese_character&name=$matches[1]',
    //         'top'
    //     );
    //     
    //     // 添加拼音索引页面规则
    //     add_rewrite_rule(
    //         'pinyin-index/?$',
    //         'index.php?pinyin_index=1',
    //         'top'
    //     );
    //     
    //     // 添加部首索引页面规则
    //     add_rewrite_rule(
    //         'radical-index/?$',
    //         'index.php?radical_index=1',
    //         'top'
    //     );
    //     
    //     // 添加专业搜索页面规则
    //     add_rewrite_rule(
    //         'professional-search/?$',
    //         'index.php?professional_search=1',
    //         'top'
    //     );
    // }
    
    /**
     * 处理模板重定向
     */
    public function maybe_redirect_search() {
        // 只在前端搜索页面执行
        if (!is_admin() && is_search()) {
            $search_query = get_search_query();
            
            // 获取搜索的post_type
            $post_type = isset($_GET['post_type']) ? $_GET['post_type'] : '';
            
            // 如果指定了post_type，则按指定类型搜索
            if (!empty($post_type)) {
                // 检查搜索词是否为单个汉字且post_type为chinese_character
                if ($post_type === 'chinese_character' && $search_query && strlen($search_query) === 3 && preg_match('/^[\x{4e00}-\x{9fa5}]$/u', $search_query)) {
                    // 直接查询数据库查找匹配的汉字文章
                    global $wpdb;
                    $post_id = $wpdb->get_var($wpdb->prepare(
                        "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'chinese_character' AND post_status = 'publish' LIMIT 1",
                        $search_query
                    ));
                    
                    // 如果找到了匹配的文章，则重定向到该文章页面
                    if ($post_id) {
                        wp_redirect(get_permalink($post_id));
                        exit;
                    }
                }
                
                // 检查搜索词是否匹配词语（chinese_dictionary）
                if ($post_type === 'chinese_dictionary' && $search_query) {
                    global $wpdb;
                    $post_id = $wpdb->get_var($wpdb->prepare(
                        "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'chinese_dictionary' AND post_status = 'publish' LIMIT 1",
                        $search_query
                    ));
                    
                    // 如果找到了匹配的文章，则重定向到该文章页面
                    if ($post_id) {
                        wp_redirect(get_permalink($post_id));
                        exit;
                    }
                }
                
                // 检查搜索词是否匹配成语（chinese_idiom）
                if ($post_type === 'chinese_idiom' && $search_query) {
                    global $wpdb;
                    $post_id = $wpdb->get_var($wpdb->prepare(
                        "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'chinese_idiom' AND post_status = 'publish' LIMIT 1",
                        $search_query
                    ));
                    
                    // 如果找到了匹配的文章，则重定向到该文章页面
                    if ($post_id) {
                        wp_redirect(get_permalink($post_id));
                        exit;
                    }
                }
            } else {
                // 如果没有指定post_type，则自动识别搜索内容类型
                if ($search_query) {
                    global $wpdb;
                    
                    // 如果是单个汉字，优先查找汉字
                    if (strlen($search_query) === 3 && preg_match('/^[\x{4e00}-\x{9fa5}]$/u', $search_query)) {
                        $post_id = $wpdb->get_var($wpdb->prepare(
                            "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'chinese_character' AND post_status = 'publish' LIMIT 1",
                            $search_query
                        ));
                        
                        if ($post_id) {
                            wp_redirect(get_permalink($post_id));
                            exit;
                        }
                    }
                    
                    // 如果不是单个汉字或汉字未找到，尝试查找词语
                    if (!$post_id) {
                        $post_id = $wpdb->get_var($wpdb->prepare(
                            "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'chinese_dictionary' AND post_status = 'publish' LIMIT 1",
                            $search_query
                        ));
                        
                        if ($post_id) {
                            wp_redirect(get_permalink($post_id));
                            exit;
                        }
                    }
                    
                    // 如果词语未找到，尝试查找成语
                    if (!$post_id) {
                        $post_id = $wpdb->get_var($wpdb->prepare(
                            "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'chinese_idiom' AND post_status = 'publish' LIMIT 1",
                            $search_query
                        ));
                        
                        if ($post_id) {
                            wp_redirect(get_permalink($post_id));
                            exit;
                        }
                    }
                }
            }
        }
        
        // 处理拼音索引页面请求
        if (get_query_var('pinyin_index')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/pinyin-index-template.php') && 
                !file_exists(get_template_directory() . '/pinyin-index-template.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/pinyin-index-template.php');
                exit;
            }
        }
        
        // 处理部首索引页面请求
        if (get_query_var('radical_index')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/radical-index-template.php') && 
                !file_exists(get_template_directory() . '/radical-index-template.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/radical-index-template.php');
                exit;
            }
        }
        
        // 处理专业搜索页面请求
        if (get_query_var('professional_search')) {
            // 如果主题没有提供模板，则使用插件自带的模板
            if (!file_exists(get_stylesheet_directory() . '/professional-search-page.php') && 
                !file_exists(get_template_directory() . '/professional-search-page.php')) {
                
                include(plugin_dir_path(__FILE__) . 'templates/professional-search-page.php');
                exit;
            }
        }
    }
    
    /**
     * 添加管理菜单
     */
    public function add_admin_menu() {
        add_submenu_page(
            'edit.php?post_type=chinese_character',
            '汉字字典设置',
            '汉字字典设置',
            'manage_options',
            'character-settings',
            array($this, 'admin_page_callback')
        );
        
        // 添加博物馆管理菜单
        /*
        add_menu_page(
            '博物馆管理',
            '博物馆',
            'edit_posts',
            'edit.php?post_type=chinese_museum',
            '',
            'dashicons-building',
            26 // 放在古籍菜单后面的位置
        );
        */
        
         // 添加博物馆管理菜单
        add_menu_page(
            '博物馆管理',
            '博物馆',
            'edit_posts',
            'edit.php?post_type=chinese_museum',
            '',
            'dashicons-building',
            8 // 放在古籍菜单后面的位置
        );
        
        add_submenu_page(
            'edit.php?post_type=chinese_museum',
            '所有博物馆',
            '所有博物馆',
            'edit_posts',
            'edit.php?post_type=chinese_museum'
        );
        
        add_submenu_page(
            'edit.php?post_type=chinese_museum',
            '新增博物馆',
            '新增博物馆',
            'edit_posts',
            'post-new.php?post_type=chinese_museum'
        );
        
        add_submenu_page(
            'edit.php?post_type=chinese_museum',
            '所有藏品',
            '所有藏品',
            'edit_posts',
            'edit.php?post_type=chinese_collection'
        );
        
        add_submenu_page(
            'edit.php?post_type=chinese_museum',
            '新增藏品',
            '新增藏品',
            'edit_posts',
            'post-new.php?post_type=chinese_collection'
        );
    }
    
    /**
     * 管理页面回调
     */
    public function admin_page_callback() {
        // 获取当前的自定义拼音列表
        $custom_pinyin = get_option('chinese_character_custom_pinyin', array());
        $pinyin_text = implode("\n", $custom_pinyin);
        
        // 获取当前的自定义部首列表
        $custom_radical = get_option('chinese_character_custom_radical', array());
        $radical_text = implode("\n", $custom_radical);
        
        // 获取推荐内容列表
        $recommended_content = get_option('chinese_character_recommended_content', array(
            'characters' => array(),
            'words' => array(),
            'idioms' => array(),
            'ancient_texts' => array(),
            'calligraphies' => array(),
            'posts' => array(),
            'pages' => array()
        ));
        
        // 获取各类别ID列表
        $characters_ids = implode(",", $recommended_content['characters']);
        $words_ids = implode(",", $recommended_content['words']);
        $idioms_ids = implode(",", $recommended_content['idioms']);
        $ancient_texts_ids = implode(",", $recommended_content['ancient_texts']);
        $calligraphies_ids = implode(",", $recommended_content['calligraphies']);
        $posts_ids = implode(",", $recommended_content['posts']);
        $pages_ids = implode(",", $recommended_content['pages']);
        
        // 获取各类内容的文章列表
        $characters_list = $this->get_characters_list();
        $words_list = $this->get_words_list();
        $idioms_list = $this->get_idioms_list();
        $ancient_texts_list = $this->get_ancient_texts_list();
        $calligraphies_list = $this->get_calligraphies_list();
        $posts_list = $this->get_default_posts_list();
        $pages_list = $this->get_default_pages_list();
        
        // 获取当前激活的标签页
        $active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'settings';
        
        ?>
        <div class="wrap">
            <h1>汉字字典设置</h1>
            
            <h2 class="nav-tab-wrapper">
                <a href="?post_type=chinese_character&page=character-settings&tab=settings" class="nav-tab <?php echo $active_tab == 'settings' ? 'nav-tab-active' : ''; ?>">拼音部首设置</a>
                <a href="?post_type=chinese_character&page=character-settings&tab=recommended" class="nav-tab <?php echo $active_tab == 'recommended' ? 'nav-tab-active' : ''; ?>">推荐内容设置</a>
                <a href="?post_type=chinese_character&page=character-settings&tab=usage" class="nav-tab <?php echo $active_tab == 'usage' ? 'nav-tab-active' : ''; ?>">使用说明</a>
            </h2>
            
            <?php if ($active_tab == 'settings'): ?>
            <form method="post" action="">
                <?php wp_nonce_field('chinese_character_settings', 'chinese_character_settings_nonce'); ?>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="pinyin_list">自定义拼音列表</label>
                        </th>
                        <td>
                            <textarea 
                                id="pinyin_list" 
                                name="pinyin_list" 
                                rows="20" 
                                cols="50" 
                                class="large-text code"
                                placeholder="每行输入一个拼音，例如：&#10;a&#10;ā&#10;á&#10;ǎ&#10;à"><?php echo esc_textarea($pinyin_text); ?></textarea>
                            <p class="description">每行输入一个拼音，支持带声调符号的拼音。这些拼音将添加到现有的拼音列表中。</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="radical_list">自定义部首列表</label>
                        </th>
                        <td>
                            <textarea 
                                id="radical_list" 
                                name="radical_list" 
                                rows="20" 
                                cols="50" 
                                class="large-text code"
                                placeholder="每行输入一个部首，例如：&#10;一&#10;丨&#10;丶"><?php echo esc_textarea($radical_text); ?></textarea>
                            <p class="description">每行输入一个部首。这些部首将添加到现有的部首列表中。</p>
                        </td>
                    </tr>
                </table>
                
                <?php submit_button('保存设置'); ?>
            </form>
            <?php endif; ?>
            
            <?php if ($active_tab == 'recommended'): ?>
            <form method="post" action="">
                <?php wp_nonce_field('chinese_character_recommended', 'chinese_character_recommended_nonce'); ?>
                
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="recommended_characters">推荐汉字</label>
                        </th>
                        <td>
                            <!-- 搜索框 -->
                            <input type="text" id="search_characters" placeholder="搜索汉字..." style="width: 100%; margin-bottom: 10px;">
                            <!-- 下拉选择框 -->
                            <select multiple size="10" style="width: 100%; margin-bottom: 10px;" id="characters_select" name="characters_select[]">
                                <?php foreach ($characters_list as $character): ?>
                                    <option value="<?php echo $character->ID; ?>" <?php echo in_array($character->ID, $recommended_content['characters']) ? 'selected' : ''; ?>>
                                        <?php echo esc_html($character->post_title); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input 
                                type="text" 
                                id="recommended_characters" 
                                name="recommended_characters" 
                                class="large-text"
                                value="<?php echo esc_attr($characters_ids); ?>"
                                placeholder="输入汉字文章ID，多个ID用英文逗号分隔，例如：123,456,789">
                            <p class="description">从上面的下拉列表中选择推荐的汉字，或者直接输入汉字文章ID（多个ID用英文逗号分隔）。</p>
                            <p class="description">要找到汉字的文章ID，可以前往"汉字"列表页面，将鼠标悬停在汉字标题上，地址栏中会出现ID参数。</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="recommended_words">推荐词语</label>
                        </th>
                        <td>
                            <!-- 搜索框 -->
                            <input type="text" id="search_words" placeholder="搜索词语..." style="width: 100%; margin-bottom: 10px;">
                            <!-- 下拉选择框 -->
                            <select multiple size="10" style="width: 100%; margin-bottom: 10px;" id="words_select" name="words_select[]">
                                <?php foreach ($words_list as $word): ?>
                                    <option value="<?php echo $word->ID; ?>" <?php echo in_array($word->ID, $recommended_content['words']) ? 'selected' : ''; ?>>
                                        <?php echo esc_html($word->post_title); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input 
                                type="text" 
                                id="recommended_words" 
                                name="recommended_words" 
                                class="large-text"
                                value="<?php echo esc_attr($words_ids); ?>"
                                placeholder="输入词语文章ID，多个ID用英文逗号分隔，例如：123,456,789">
                            <p class="description">从上面的下拉列表中选择推荐的词语，或者直接输入词语文章ID（多个ID用英文逗号分隔）。</p>
                            <p class="description">要找到词语的文章ID，可以前往"词语"列表页面，将鼠标悬停在词语标题上，地址栏中会出现ID参数。</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="recommended_idioms">推荐成语</label>
                        </th>
                        <td>
                            <!-- 搜索框 -->
                            <input type="text" id="search_idioms" placeholder="搜索成语..." style="width: 100%; margin-bottom: 10px;">
                            <!-- 下拉选择框 -->
                            <select multiple size="10" style="width: 100%; margin-bottom: 10px;" id="idioms_select" name="idioms_select[]">
                                <?php foreach ($idioms_list as $idiom): ?>
                                    <option value="<?php echo $idiom->ID; ?>" <?php echo in_array($idiom->ID, $recommended_content['idioms']) ? 'selected' : ''; ?>>
                                        <?php echo esc_html($idiom->post_title); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input 
                                type="text" 
                                id="recommended_idioms" 
                                name="recommended_idioms" 
                                class="large-text"
                                value="<?php echo esc_attr($idioms_ids); ?>"
                                placeholder="输入成语文章ID，多个ID用英文逗号分隔，例如：123,456,789">
                            <p class="description">从上面的下拉列表中选择推荐的成语，或者直接输入成语文章ID（多个ID用英文逗号分隔）。</p>
                            <p class="description">要找到成语的文章ID，可以前往"成语"列表页面，将鼠标悬停在成语标题上，地址栏中会出现ID参数。</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="recommended_ancient_texts">推荐古籍</label>
                        </th>
                        <td>
                            <!-- 搜索框 -->
                            <input type="text" id="search_ancient_texts" placeholder="搜索古籍..." style="width: 100%; margin-bottom: 10px;">
                            <!-- 下拉选择框 -->
                            <select multiple size="10" style="width: 100%; margin-bottom: 10px;" id="ancient_texts_select" name="ancient_texts_select[]">
                                <?php foreach ($ancient_texts_list as $ancient_text): ?>
                                    <option value="<?php echo $ancient_text->ID; ?>" <?php echo in_array($ancient_text->ID, $recommended_content['ancient_texts']) ? 'selected' : ''; ?>>
                                        <?php echo esc_html($ancient_text->post_title); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input 
                                type="text" 
                                id="recommended_ancient_texts" 
                                name="recommended_ancient_texts" 
                                class="large-text"
                                value="<?php echo esc_attr($ancient_texts_ids); ?>"
                                placeholder="输入古籍文章ID，多个ID用英文逗号分隔，例如：123,456,789">
                            <p class="description">从上面的下拉列表中选择推荐的古籍，或者直接输入古籍文章ID（多个ID用英文逗号分隔）。</p>
                            <p class="description">要找到古籍的文章ID，可以前往"古籍"列表页面，将鼠标悬停在古籍标题上，地址栏中会出现ID参数。</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="recommended_calligraphies">推荐书法作品</label>
                        </th>
                        <td>
                            <!-- 搜索框 -->
                            <input type="text" id="search_calligraphies" placeholder="搜索书法作品..." style="width: 100%; margin-bottom: 10px;">
                            <!-- 下拉选择框 -->
                            <select multiple size="10" style="width: 100%; margin-bottom: 10px;" id="calligraphies_select" name="calligraphies_select[]">
                                <?php foreach ($calligraphies_list as $calligraphy): ?>
                                    <option value="<?php echo $calligraphy->ID; ?>" <?php echo in_array($calligraphy->ID, $recommended_content['calligraphies']) ? 'selected' : ''; ?>>
                                        <?php echo esc_html($calligraphy->post_title); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input 
                                type="text" 
                                id="recommended_calligraphies" 
                                name="recommended_calligraphies" 
                                class="large-text"
                                value="<?php echo esc_attr($calligraphies_ids); ?>"
                                placeholder="输入书法作品文章ID，多个ID用英文逗号分隔，例如：123,456,789">
                            <p class="description">从上面的下拉列表中选择推荐的书法作品，或者直接输入书法作品文章ID（多个ID用英文逗号分隔）。</p>
                            <p class="description">要找到书法作品的文章ID，可以前往"书法作品"列表页面，将鼠标悬停在作品标题上，地址栏中会出现ID参数。</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="recommended_posts">推荐文章</label>
                        </th>
                        <td>
                            <!-- 搜索框 -->
                            <input type="text" id="search_posts" placeholder="搜索文章..." style="width: 100%; margin-bottom: 10px;">
                            <!-- 下拉选择框 -->
                            <select multiple size="10" style="width: 100%; margin-bottom: 10px;" id="posts_select" name="posts_select[]">
                                <?php foreach ($posts_list as $post): ?>
                                    <option value="<?php echo $post->ID; ?>" <?php echo in_array($post->ID, $recommended_content['posts']) ? 'selected' : ''; ?>>
                                        <?php echo esc_html($post->post_title); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input 
                                type="text" 
                                id="recommended_posts" 
                                name="recommended_posts" 
                                class="large-text"
                                value="<?php echo esc_attr($posts_ids); ?>"
                                placeholder="输入文章ID，多个ID用英文逗号分隔，例如：123,456,789">
                            <p class="description">从上面的下拉列表中选择推荐的文章，或者直接输入文章ID（多个ID用英文逗号分隔）。</p>
                            <p class="description">要找到文章的ID，可以前往"文章"列表页面，将鼠标悬停在文章标题上，地址栏中会出现ID参数。</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="recommended_pages">推荐页面</label>
                        </th>
                        <td>
                            <!-- 搜索框 -->
                            <input type="text" id="search_pages" placeholder="搜索页面..." style="width: 100%; margin-bottom: 10px;">
                            <!-- 下拉选择框 -->
                            <select multiple size="10" style="width: 100%; margin-bottom: 10px;" id="pages_select" name="pages_select[]">
                                <?php foreach ($pages_list as $page): ?>
                                    <option value="<?php echo $page->ID; ?>" <?php echo in_array($page->ID, $recommended_content['pages']) ? 'selected' : ''; ?>>
                                        <?php echo esc_html($page->post_title); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input 
                                type="text" 
                                id="recommended_pages" 
                                name="recommended_pages" 
                                class="large-text"
                                value="<?php echo esc_attr($pages_ids); ?>"
                                placeholder="输入页面ID，多个ID用英文逗号分隔，例如：123,456,789">
                            <p class="description">从上面的下拉列表中选择推荐的页面，或者直接输入页面ID（多个ID用英文逗号分隔）。</p>
                            <p class="description">要找到页面的ID，可以前往"页面"列表页面，将鼠标悬停在页面标题上，地址栏中会出现ID参数。</p>
                        </td>
                    </tr>
                </table>
                
                <?php submit_button('保存推荐内容'); ?>
            </form>
            
            <script>
                // 同步下拉选择框和文本框
                document.addEventListener('DOMContentLoaded', function() {
                    // 汉字同步
                    const charactersSelect = document.getElementById('characters_select');
                    const charactersInput = document.getElementById('recommended_characters');
                    const searchCharacters = document.getElementById('search_characters');
                    
                    if (searchCharacters) {
                        searchCharacters.addEventListener('input', function() {
                            const searchTerm = this.value.toLowerCase();
                            const options = charactersSelect.querySelectorAll('option');
                            options.forEach(option => {
                                const text = option.textContent.toLowerCase();
                                option.style.display = text.includes(searchTerm) ? '' : 'none';
                            });
                        });
                    }
                    
                    // 实现点击选项即可添加/取消选择，无需按住Ctrl键
                    if (charactersSelect) {
                        charactersSelect.addEventListener('mousedown', function(e) {
                            e.preventDefault();
                            const option = e.target;
                            if (option.tagName === 'OPTION') {
                                option.selected = !option.selected;
                                // 触发change事件以更新文本框
                                const event = new Event('change', { bubbles: true });
                                charactersSelect.dispatchEvent(event);
                                return false;
                            }
                        });
                    }
                    
                    charactersSelect.addEventListener('change', function() {
                        const selectedOptions = Array.from(charactersSelect.selectedOptions);
                        const selectedIds = selectedOptions.map(option => option.value);
                        charactersInput.value = selectedIds.join(',');
                    });
                    
                    // 词语同步
                    const wordsSelect = document.getElementById('words_select');
                    const wordsInput = document.getElementById('recommended_words');
                    const searchWords = document.getElementById('search_words');
                    
                    if (searchWords) {
                        searchWords.addEventListener('input', function() {
                            const searchTerm = this.value.toLowerCase();
                            const options = wordsSelect.querySelectorAll('option');
                            options.forEach(option => {
                                const text = option.textContent.toLowerCase();
                                option.style.display = text.includes(searchTerm) ? '' : 'none';
                            });
                        });
                    }
                    
                    // 实现点击选项即可添加/取消选择，无需按住Ctrl键
                    if (wordsSelect) {
                        wordsSelect.addEventListener('mousedown', function(e) {
                            e.preventDefault();
                            const option = e.target;
                            if (option.tagName === 'OPTION') {
                                option.selected = !option.selected;
                                // 触发change事件以更新文本框
                                const event = new Event('change', { bubbles: true });
                                wordsSelect.dispatchEvent(event);
                                return false;
                            }
                        });
                    }
                    
                    wordsSelect.addEventListener('change', function() {
                        const selectedOptions = Array.from(wordsSelect.selectedOptions);
                        const selectedIds = selectedOptions.map(option => option.value);
                        wordsInput.value = selectedIds.join(',');
                    });
                    
                    // 成语同步
                    const idiomsSelect = document.getElementById('idioms_select');
                    const idiomsInput = document.getElementById('recommended_idioms');
                    const searchIdioms = document.getElementById('search_idioms');
                    
                    if (searchIdioms) {
                        searchIdioms.addEventListener('input', function() {
                            const searchTerm = this.value.toLowerCase();
                            const options = idiomsSelect.querySelectorAll('option');
                            options.forEach(option => {
                                const text = option.textContent.toLowerCase();
                                option.style.display = text.includes(searchTerm) ? '' : 'none';
                            });
                        });
                    }
                    
                    // 实现点击选项即可添加/取消选择，无需按住Ctrl键
                    if (idiomsSelect) {
                        idiomsSelect.addEventListener('mousedown', function(e) {
                            e.preventDefault();
                            const option = e.target;
                            if (option.tagName === 'OPTION') {
                                option.selected = !option.selected;
                                // 触发change事件以更新文本框
                                const event = new Event('change', { bubbles: true });
                                idiomsSelect.dispatchEvent(event);
                                return false;
                            }
                        });
                    }
                    
                    idiomsSelect.addEventListener('change', function() {
                        const selectedOptions = Array.from(idiomsSelect.selectedOptions);
                        const selectedIds = selectedOptions.map(option => option.value);
                        idiomsInput.value = selectedIds.join(',');
                    });
                    
                    // 古籍同步
                    const ancientTextsSelect = document.getElementById('ancient_texts_select');
                    const ancientTextsInput = document.getElementById('recommended_ancient_texts');
                    const searchAncientTexts = document.getElementById('search_ancient_texts');
                    
                    if (searchAncientTexts) {
                        searchAncientTexts.addEventListener('input', function() {
                            const searchTerm = this.value.toLowerCase();
                            const options = ancientTextsSelect.querySelectorAll('option');
                            options.forEach(option => {
                                const text = option.textContent.toLowerCase();
                                option.style.display = text.includes(searchTerm) ? '' : 'none';
                            });
                        });
                    }
                    
                    // 实现点击选项即可添加/取消选择，无需按住Ctrl键
                    if (ancientTextsSelect) {
                        ancientTextsSelect.addEventListener('mousedown', function(e) {
                            e.preventDefault();
                            const option = e.target;
                            if (option.tagName === 'OPTION') {
                                option.selected = !option.selected;
                                // 触发change事件以更新文本框
                                const event = new Event('change', { bubbles: true });
                                ancientTextsSelect.dispatchEvent(event);
                                return false;
                            }
                        });
                    }
                    
                    ancientTextsSelect.addEventListener('change', function() {
                        const selectedOptions = Array.from(ancientTextsSelect.selectedOptions);
                        const selectedIds = selectedOptions.map(option => option.value);
                        ancientTextsInput.value = selectedIds.join(',');
                    });
                    
                    // 书法作品同步
                    const calligraphiesSelect = document.getElementById('calligraphies_select');
                    const calligraphiesInput = document.getElementById('recommended_calligraphies');
                    const searchCalligraphies = document.getElementById('search_calligraphies');
                    
                    if (searchCalligraphies) {
                        searchCalligraphies.addEventListener('input', function() {
                            const searchTerm = this.value.toLowerCase();
                            const options = calligraphiesSelect.querySelectorAll('option');
                            options.forEach(option => {
                                const text = option.textContent.toLowerCase();
                                option.style.display = text.includes(searchTerm) ? '' : 'none';
                            });
                        });
                    }
                    
                    // 实现点击选项即可添加/取消选择，无需按住Ctrl键
                    if (calligraphiesSelect) {
                        calligraphiesSelect.addEventListener('mousedown', function(e) {
                            e.preventDefault();
                            const option = e.target;
                            if (option.tagName === 'OPTION') {
                                option.selected = !option.selected;
                                // 触发change事件以更新文本框
                                const event = new Event('change', { bubbles: true });
                                calligraphiesSelect.dispatchEvent(event);
                                return false;
                            }
                        });
                    }
                    
                    calligraphiesSelect.addEventListener('change', function() {
                        const selectedOptions = Array.from(calligraphiesSelect.selectedOptions);
                        const selectedIds = selectedOptions.map(option => option.value);
                        calligraphiesInput.value = selectedIds.join(',');
                    });
                    
                    // 文章同步
                    const postsSelect = document.getElementById('posts_select');
                    const postsInput = document.getElementById('recommended_posts');
                    const searchPosts = document.getElementById('search_posts');
                    
                    if (searchPosts) {
                        searchPosts.addEventListener('input', function() {
                            const searchTerm = this.value.toLowerCase();
                            const options = postsSelect.querySelectorAll('option');
                            options.forEach(option => {
                                const text = option.textContent.toLowerCase();
                                option.style.display = text.includes(searchTerm) ? '' : 'none';
                            });
                        });
                    }
                    
                    // 实现点击选项即可添加/取消选择，无需按住Ctrl键
                    if (postsSelect) {
                        postsSelect.addEventListener('mousedown', function(e) {
                            e.preventDefault();
                            const option = e.target;
                            if (option.tagName === 'OPTION') {
                                option.selected = !option.selected;
                                // 触发change事件以更新文本框
                                const event = new Event('change', { bubbles: true });
                                postsSelect.dispatchEvent(event);
                                return false;
                            }
                        });
                    }
                    
                    postsSelect.addEventListener('change', function() {
                        const selectedOptions = Array.from(postsSelect.selectedOptions);
                        const selectedIds = selectedOptions.map(option => option.value);
                        postsInput.value = selectedIds.join(',');
                    });
                    
                    // 页面同步
                    const pagesSelect = document.getElementById('pages_select');
                    const pagesInput = document.getElementById('recommended_pages');
                    const searchPages = document.getElementById('search_pages');
                    
                    if (searchPages) {
                        searchPages.addEventListener('input', function() {
                            const searchTerm = this.value.toLowerCase();
                            const options = pagesSelect.querySelectorAll('option');
                            options.forEach(option => {
                                const text = option.textContent.toLowerCase();
                                option.style.display = text.includes(searchTerm) ? '' : 'none';
                            });
                        });
                    }
                    
                    // 实现点击选项即可添加/取消选择，无需按住Ctrl键
                    if (pagesSelect) {
                        pagesSelect.addEventListener('mousedown', function(e) {
                            e.preventDefault();
                            const option = e.target;
                            if (option.tagName === 'OPTION') {
                                option.selected = !option.selected;
                                // 触发change事件以更新文本框
                                const event = new Event('change', { bubbles: true });
                                pagesSelect.dispatchEvent(event);
                                return false;
                            }
                        });
                    }
                    
                    pagesSelect.addEventListener('change', function() {
                        const selectedOptions = Array.from(pagesSelect.selectedOptions);
                        const selectedIds = selectedOptions.map(option => option.value);
                        pagesInput.value = selectedIds.join(',');
                    });
                });
            </script>
            <?php endif; ?>
            
            <?php if ($active_tab == 'usage'): ?>
            <div class="usage-instructions">
                <h2>拼音部首设置说明</h2>
                <p>在此页面中，您可以自定义拼音和部首列表。您添加的项目将与系统默认列表合并，显示在汉字编辑页面的下拉选择框中。</p>
                
                <h3>拼音列表</h3>
                <p>每行输入一个拼音，支持带声调符号的拼音。例如：</p>
                <pre>
a
ā
á
ǎ
à
ai
āi
ái
ǎi
ài
                </pre>
                
                <h3>部首列表</h3>
                <p>每行输入一个部首。部首按照笔画数排列，从1画到17画，共214个部首（按照新华字典标准）：</p>
                <pre>
一 丨 丶 丿 乙 亅
二 亠 人 儿 入 八 冂 冖 冫 几 凵 刀 力 勹 匕 匚 医 十 卜 卍 厂 厶 又
口 囗 土 士 夂 复 夕 大 女 子 宀 寸 小 尢 尸 屮 山 巜 工 己 巾 干 幺 广 廴 廾 弋 弓 彐 彡 彳
心 戈 戸 手 支 攴 文 斗 斤 方 无 日 曰 月 木 欠 止 歹 殳 毋 比 毛 氏 气 水 火 爪 父 爻 爿 片 牙 牛 犬 玄
玉 瓜 瓦 甘 生 用 田 疋 疒 癶 白 皮 皿 目 矛 矢 石 示 禸 禾 穴 立 竹 米 糸 缅 网 羊 羽
老 而 耒 耳 聿 肉 臣 自 至 臼 舌 舛 舟 艮 色 艸 虍 虫 血 行 衣 襮 見 角 言 谷 豆 豕 豸 買 赤
走 足 身 車 辛 辰 辵 邑 酉 釆 里 金 长 門 阜 隶 隹 雨 青 非 面 革 韦
韭 音 頁 風 飛 食 首 香 馬 骨 高
髟 鬥 鬯 鬲 鬼 魚 鳥
鹵 鹿 麥 麻 黃 黍
黑 黹 黽 鼎
鼓 鼠 鼻
齊 齒
龍
龜
龠
                </pre>
                
                <h2>拼音索引页面使用说明</h2>
                <p>插件提供了一个拼音索引页面，用户可以通过该页面按拼音查找汉字。该页面包含多种索引方式：</p>
                
                <h3>1. 英文字母索引</h3>
                <p>按照拼音首字母A-Z进行索引，用户可以快速定位到以特定字母开头的汉字。</p>
                
                <h3>2. 声母索引</h3>
                <p>按照汉语拼音的声母进行分类，包括b, p, m, f, d, t, n, l, g, k, h, j, q, x, zh, ch, sh, r, z, c, s, y, w等。</p>
                
                <h3>3. 韵母索引</h3>
                <p>按照汉语拼音的韵母进行分类，分为以下几类：</p>
                <ul>
                    <li><strong>单韵母</strong>：a, o, e, i, u, ü</li>
                    <li><strong>复韵母</strong>：ai, ei, ao, ou, ia, ie, iao, iou, ua, uo, uai, uei</li>
                    <li><strong>鼻韵母</strong>：an, en, ang, eng, ong, ian, in, iang, ing, iong, uan, uen, uang, ueng, üan, ün, üe</li>
                    <li><strong>儿化韵</strong>：er</li>
                </ul>
                
                <p>访问方式：在浏览器中访问 <code><?php echo home_url('/pinyin-index'); ?></code> 即可查看拼音索引页面。</p>
                
                <h2>部首检索页面使用说明</h2>
                <p>插件提供了一个专业的部首检索页面，用户可以通过该页面按部首和笔画数查找汉字，类似于传统字典的检字法。</p>
                
                <h3>页面功能</h3>
                <ul>
                    <li><strong>部首分类</strong>：按笔画数将部首分为17组（1-17画），共214个部首（按照新华字典标准）</li>
                    <li><strong>汉字展示</strong>：点击部首后，页面右侧会显示包含该部首的所有汉字</li>
                    <li><strong>排序方式</strong>：汉字按笔画数升序排列</li>
                    <li><strong>详细信息</strong>：每个汉字显示其拼音和总笔画数</li>
                    <li><strong>快速跳转</strong>：点击汉字可直接进入该汉字的详细解释页面</li>
                </ul>
                
                <h3>使用方法</h3>
                <ol>
                    <li>在页面左侧选择一个部首</li>
                    <li>页面右侧将自动显示包含该部首的所有汉字</li>
                    <li>点击感兴趣的汉字查看详细解释</li>
                </ol>
                
                <h3>页面访问</h3>
                <p>访问方式：在浏览器中访问 <code><?php echo home_url('/radical-index'); ?></code> 即可查看部首检索页面。</p>
                
                <h3>页面特点</h3>
                <ul>
                    <li><strong>专业设计</strong>：界面模仿传统字典的部首检字法布局</li>
                    <li><strong>响应式布局</strong>：适配各种设备屏幕尺寸</li>
                    <li><strong>交互友好</strong>：点击部首即可实时查看相关汉字</li>
                    <li><strong>快速检索</strong>：无需刷新页面，通过AJAX动态加载数据</li>
                    <li><strong>完整部首</strong>：包含新华字典标准的全部214个部首，按1-17画分类</li>
                </ul>
                
                <h2>书法作品展示页面使用说明</h2>
                <p>插件提供了一个专业的书法作品展示页面，用户可以通过该页面浏览、筛选和查找书法作品。</p>
                
                <h3>页面功能</h3>
                <ul>
                    <li><strong>分类展示</strong>：按书法家、朝代和书体三个维度对书法作品进行分类展示</li>
                    <li><strong>筛选功能</strong>：支持按汉字、书法家、朝代和书体进行精确筛选</li>
                    <li><strong>交互式导航</strong>：点击分类项可直接筛选相关作品</li>
                    <li><strong>作品详情</strong>：每个作品展示缩略图、汉字、书法家、书体和年代信息</li>
                    <li><strong>快速跳转</strong>：点击作品可查看完整作品详情</li>
                </ul>
                
                <h3>使用方法</h3>
                <ol>
                    <li>通过书法作品归档页面访问，或在菜单中直接点击"书法作品"进入展示页面</li>
                    <li>浏览按书法家、朝代和书体分类的作品展示区域</li>
                    <li>点击任意分类项（如特定书法家）可筛选出相关作品</li>
                    <li>使用顶部筛选表单进行更精确的筛选</li>
                    <li>点击作品图片或标题查看完整作品详情</li>
                </ol>
                
                <h3>页面访问</h3>
                <p>访问方式：</p>
                <ul>
                    <li>在WordPress后台，进入"书法作品"菜单下的"所有书法作品"页面，点击"书法作品"标题可访问归档页面</li>
                    <li>或者在浏览器中访问 <code><?php echo get_post_type_archive_link('chinese_calligraphy'); ?></code></li>
                </ul>
                
                <h3>页面特点</h3>
                <ul>
                    <li><strong>专业设计</strong>：界面布局清晰，符合专业书法作品展示需求</li>
                    <li><strong>多维度分类</strong>：支持按书法家、朝代和书体三种维度分类展示</li>
                    <li><strong>响应式布局</strong>：适配各种设备屏幕尺寸</li>
                    <li><strong>交互友好</strong>：分类展示和筛选表单联动，操作流畅</li>
                    <li><strong>快速检索</strong>：通过AJAX动态加载数据，提升用户体验</li>
                </ul>
                
                 <h2>古籍阅读展示页面使用说明</h2>
                <p>插件提供了一个专业的古籍阅读展示页面，用户可以通过该页面浏览和阅读古籍文献。</p>
                
                <h3>页面功能</h3>
                <ul>
                    <li><strong>古籍分类</strong>：按朝代、作者等维度对古籍进行分类展示</li>
                    <li><strong>详细信息</strong>：展示古籍的朝代、作者、出版信息、卷数等详细信息</li>
                    <li><strong>内容阅读</strong>：提供古籍内容的在线阅读功能</li>
                    <li><strong>快速检索</strong>：支持通过关键词快速查找古籍</li>
                </ul>
                
                <h3>使用方法</h3>
                <ol>
                    <li>通过古籍归档页面访问，或在菜单中直接点击"古籍"进入展示页面</li>
                    <li>浏览按朝代、作者分类的古籍展示区域</li>
                    <li>点击感兴趣的古籍查看详细信息和内容</li>
                </ol>
                
                <h3>页面访问</h3>
                <p>访问方式：</p>
                <ul>
                    <li>在WordPress后台，进入"古籍"菜单下的"所有古籍"页面，点击"古籍"标题可访问归档页面</li>
                    <li>或者在浏览器中访问 <code><?php echo get_post_type_archive_link('chinese_ancient_text'); ?></code></li>
                </ul>
                
                <h3>页面特点</h3>
                <ul>
                    <li><strong>专业设计</strong>：界面布局清晰，符合古籍阅读需求</li>
                    <li><strong>信息完整</strong>：提供古籍的详细信息和内容展示</li>
                    <li><strong>响应式布局</strong>：适配各种设备屏幕尺寸</li>
                    <li><strong>易于阅读</strong>：优化的排版和字体，提升阅读体验</li>
                </ul>
        
                <h2>专业搜索页面使用说明</h2>
                <p>插件提供了一个专业的搜索页面，用户可以通过该页面搜索汉字、词语或成语。</p>
                
                <h3>页面功能</h3>
                <ul>
                    <li><strong>智能识别</strong>：自动识别输入内容是汉字、词语还是成语</li>
                    <li><strong>多类型搜索</strong>：支持汉字、词语、成语搜索</li>
                    <li><strong>智能跳转</strong>：输入汉字、词语或成语可直接跳转到详细解释页面</li>
                    <li><strong>响应式设计</strong>：适配各种设备屏幕尺寸</li>
                    <li><strong>现代化界面</strong>：采用现代化的UI设计，提供更好的用户体验</li>
                </ul>
                
                <h3>使用方法</h3>
                <ol>
                    <li>在浏览器中访问 <code><?php echo home_url('/professional-search'); ?></code> 进入专业搜索页面</li>
                    <li>在搜索框中输入要查询的汉字、词语或成语</li>
                    <li>系统会自动识别输入内容的类型并显示相应解释</li>
                </ol>
                
                <h3>页面访问</h3>
                <p>访问方式：在浏览器中访问 <code><?php echo home_url('/professional-search'); ?></code> 即可查看专业搜索页面。</p>
                
                <h3>页面特点</h3>
                <ul>
                    <li><strong>智能识别</strong>：无需选择搜索类型，系统自动识别并跳转</li>
                    <li><strong>专业设计</strong>：界面美观，符合现代网页设计趋势</li>
                    <li><strong>交互友好</strong>：提供清晰的搜索指引和反馈</li>
                    <li><strong>响应式布局</strong>：在各种设备上都能良好显示</li>
                    <li><strong>快速检索</strong>：支持智能跳转，提升用户体验</li>
                </ul>
                
                <h3>设置为首页（可选）</h3>
                <p>您可以将专业搜索页面设置为网站的首页：</p>
                <ol>
                    <li>进入WordPress后台"设置" > "阅读"</li>
                    <li>选择"一个静态页面"</li>
                    <li>在"首页"下拉菜单中选择包含搜索功能的页面</li>
                    <li>保存更改</li>
                </ol>
                
                <h2>增强评论功能使用说明</h2>
                <p>插件为特定分类下的文章提供了增强的评论功能，包括富文本编辑器和论坛样式显示。</p>
                
                <h3>功能特点</h3>
                <ul>
                    <li><strong>富文本编辑器</strong>：评论框支持格式化文本、列表、链接等</li>
                    <li><strong>格式化显示</strong>：评论内容以格式化方式展示</li>
                    <li><strong>论坛样式</strong>：评论区域采用类似论坛的布局设计</li>
                    <li><strong>分类控制</strong>：可选择特定分类启用此功能</li>
                </ul>
                
                <h3>配置方法</h3>
                <ol>
                    <li>进入WordPress后台"设置" > "讨论"</li>
                    <li>找到"增强评论功能分类"选项</li>
                    <li>选择需要启用增强评论功能的主分类</li>
                    <li>保存更改</li>
                </ol>
                
                <h3>使用方法</h3>
                <ol>
                    <li>访问属于已配置分类的文章页面</li>
                    <li>在评论区域会看到富文本编辑器</li>
                    <li>使用编辑器撰写格式化评论</li>
                    <li>提交评论后，评论将以格式化方式显示</li>
                </ol>
                
                <h3>功能优势</h3>
                <ul>
                    <li><strong>增强互动</strong>：提供更丰富的评论撰写体验</li>
                    <li><strong>灵活配置</strong>：可按分类控制功能启用</li>
                    <li><strong>界面友好</strong>：论坛样式设计提升阅读体验</li>
                    <li><strong>兼容性好</strong>：不影响未启用功能的文章</li>
                </ul>
                
                <h2>多音字管理功能使用说明</h2>
                <p>插件提供了专业的多音字管理功能，可以精确处理汉字的多音多义特性。</p>
                
                <h3>功能特点</h3>
                <ul>
                    <li><strong>结构化管理</strong>：为每个发音和含义创建独立的内容实体</li>
                    <li><strong>精细化控制</strong>：可以为每个发音指定拼音、词性、解释和使用示例</li>
                    <li><strong>关联管理</strong>：通过元数据将发音含义对与汉字主条目关联</li>
                    <li><strong>专业展示</strong>：前端按发音分组展示不同含义和示例</li>
                </ul>
                
                <h3>使用方法</h3>
                <ol>
                    <li>在汉字字典后台，编辑需要添加多音字信息的汉字条目</li>
                    <li>在"汉字发音含义对"元框中，点击"添加新的发音含义对"按钮</li>
                    <li>在新打开的页面中填写拼音、词性、详细解释和使用示例等信息</li>
                    <li>保存发音含义对，并确保关联到正确的汉字</li>
                    <li>在前台查看汉字详情时，切换到"多音字详解"标签页即可查看所有发音含义</li>
                </ol>
                
                <h3>功能优势</h3>
                <ul>
                    <li><strong>专业性强</strong>：满足语言学专业对多音字处理的精确要求</li>
                    <li><strong>易于管理</strong>：通过独立的文章类型管理发音含义对</li>
                    <li><strong>展示清晰</strong>：前端按发音分组展示，用户可以轻松区分不同读音</li>
                    <li><strong>扩展性好</strong>：可以为每个发音添加丰富的解释和示例内容</li>
                </ul>
                
                <h2>方言字词句考证页面使用说明</h2>
                <p>插件提供了一个专业的方言字词句考证页面，用户可以通过该页面查看和研究各种方言中的特殊字词句。</p>
                
                <h3>页面功能</h3>
                <ul>
                    <li><strong>方言分类</strong>：按方言区（官话、晋语、吴语、徽语、赣语、湘语、闽语、粤语、平话、客家话）分类展示</li>
                    <li><strong>次方言细分</strong>：支持查看各大方言区下的次方言片区</li>
                    <li><strong>详细信息</strong>：展示方言字词的字形、读音、释义、考据和使用示例</li>
                    <li><strong>交互友好</strong>：提供清晰的筛选和展示界面，操作流畅</li>
                </ul>
                
                <h3>页面访问</h3>
                <p>访问方式：在浏览器中访问 <code><?php echo home_url('/dialect-research'); ?></code> 即可查看方言字词句考证页面。</p>
                
                <h3>页面特点</h3>
                <ul>
                    <li><strong>专业设计</strong>：界面清晰，符合学术研究需求</li>
                    <li><strong>响应式布局</strong>：适配各种设备屏幕尺寸</li>
                    <li><strong>交互友好</strong>：方言区和次方言选择联动，操作流畅</li>
                    <li><strong>快速检索</strong>：通过筛选快速定位目标方言条目</li>
                </ul>
                
                
                 <h2>搜索页短代码使用使用说明</h2>
                <p>插件提供了一个专业的方言字词句考证页面，用户可以通过该页面查看和研究各种方言中的特殊字词句。</p>
                
                <h3>页面功能</h3>
                <ul>
                	
                    <li><strong>您可以在任何页面或文章中使用以下短代码来显示完整的搜索功能（包括推荐内容）</strong>：[character_search_form]</li>
                    <li><strong>如果您想要自定义显示选项，可以使用参数</strong>：[character_search_form placeholder="请输入要搜索的内容..." button_text="查找" show_options="true" show_recommendations="true"]</li>
                    <li><strong>如果您只想显示搜索表单而不显示推荐内容，可以这样使用</strong>：[character_search_form show_recommendations="false"]</li>
                    <li><strong>这个实现与原有的专业搜索页面功能完全一致，包括推荐内容区域，同时保持了短代码的灵活性和可定制性。</strong></li>
                    <li><strong>这个实现支持搜索汉字、词语、成语以及其他内容类型，并提供了拼音检索和部首检索的链接选项。样式已经包含在示例模板中，您可以根据需要进一步自定义外观。</strong></li>
                </ul>
                
                <h3>页面访问</h3>
                <p>访问方式：在浏览器中访问 <code><?php echo home_url('/professional-search'); ?></code> 即可查看方言字词句考证页面。</p>
                
                <h3>页面特点</h3>
                <ul>
                    <li><strong>专业设计</strong>：界面清晰，符合学术研究需求</li>
                    <li><strong>响应式布局</strong>：适配各种设备屏幕尺寸</li>
                    <li><strong>交互友好</strong>：方言区和次方言选择联动，操作流畅</li>
                </ul>
                
                  <h2>博物馆聚合页面访问方法</h2>
                <p>博物馆聚合页面已经创建并可以访问了。要访问所有博物馆的聚合页面，您有以下几种方式：</p>
                
                <h3>通过固定链接访问：</h3>
                <p>访问方式：在浏览器中访问 <code><?php echo home_url('/museum'); ?></code> 即可查看所有博物馆的聚合页面。</p>
                <ul>
                    <li><strong>这个URL是基于我们为博物馆文章类型设置的重写规则生成的</strong></li>
                    
	                <li><strong>通过WordPress后台菜单访问：</strong></li>
	                <li><strong>登录WordPress后台</strong></li>
	                <li><strong>在左侧菜单中找到"博物馆"选项</strong></li>
	                <li><strong>点击"所有博物馆"可以看到管理界面，而前端页面就是聚合展示页面</strong></li>
	                <li><strong>通过网站首页访问：</strong></li>
	                <li><strong>博物馆页面也可能会在网站的主菜单或相关链接中出现</strong></li>
	                
                </ul>
                <h3>页面功能特点</h3>
                <ul>
                    <li><strong>专业设计</strong>：按地区对博物馆进行分组显示。展示博物馆的基本信息，如建立年份和馆长。显示每个博物馆的缩略图（如果有设置）。提供指向每个博物馆详细页面的链接。</li>
                    <li><strong>响应式布局</strong>：响应式设计，适配各种设备屏幕。页面会自动获取所有已发布的博物馆内容，并按照地区进行分类展示，方便用户浏览和查找感兴趣的博物馆。</li>
                    <li><strong></strong>如果您想要进一步自定义页面样式或功能，可以修改 templates/archive-museum-template.php 文件。</li>
                </ul>
            
                
            </div>
            <?php endif; ?>
        </div>
        
        <style>
        .form-table textarea {
            font-family: monospace;
            background: #f9f9f9;
        }
        .description {
            color: #666;
        }
        pre {
            background: #f9f9f9;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
        .nav-tab-wrapper {
            margin-bottom: 20px;
        }
        .usage-instructions h2, .usage-instructions h3 {
            margin-top: 25px;
        }
        .usage-instructions h2:first-child {
            margin-top: 10px;
        }
        </style>
        <?php
    }
    
    /**
     * 处理管理页面表单提交
     */
    public function handle_admin_form_submission() {
        // 处理拼音和部首设置
        $this->handle_settings_submission();
        
        // 处理推荐内容设置
        $this->handle_recommended_submission();
    }
    
    /**
     * 处理管理页面表单提交（拼音和部首设置）
     */
    public function handle_settings_submission() {
        // 检查是否是我们的表单提交
        if (!isset($_POST['chinese_character_settings_nonce']) || 
            !wp_verify_nonce($_POST['chinese_character_settings_nonce'], 'chinese_character_settings')) {
            return;
        }
        
        // 检查权限
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // 处理拼音列表更新
        if (isset($_POST['pinyin_list'])) {
            $pinyin_list = sanitize_textarea_field($_POST['pinyin_list']);
            $pinyin_array = array_filter(array_map('trim', explode("\n", $pinyin_list)));
            update_option('chinese_character_custom_pinyin', $pinyin_array);
        }
        
        // 处理部首列表更新
        if (isset($_POST['radical_list'])) {
            $radical_list = sanitize_textarea_field($_POST['radical_list']);
            $radical_array = array_filter(array_map('trim', explode("\n", $radical_list)));
            update_option('chinese_character_custom_radical', $radical_array);
        }
        
        // 添加管理员通知
        add_action('admin_notices', function() {
            echo '<div class="notice notice-success"><p>设置已保存。</p></div>';
        });
    }
    
    /**
     * 处理管理页面表单提交（推荐内容）
     */
    public function handle_recommended_submission() {
        // 检查是否是我们的表单提交
        if (!isset($_POST['chinese_character_recommended_nonce']) || 
            !wp_verify_nonce($_POST['chinese_character_recommended_nonce'], 'chinese_character_recommended')) {
            return;
        }
        
        // 检查权限
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // 处理推荐内容更新
        $recommended_content = array(
            'characters' => array(),
            'words' => array(),
            'idioms' => array(),
            'ancient_texts' => array(),
            'calligraphies' => array(),
            'posts' => array(),
            'pages' => array()
        );
        
        // 处理推荐汉字更新（支持下拉选择和手动输入）
        if (isset($_POST['characters_select']) && is_array($_POST['characters_select'])) {
            $recommended_content['characters'] = array_map('intval', $_POST['characters_select']);
        } else if (isset($_POST['recommended_characters'])) {
            $characters = sanitize_text_field($_POST['recommended_characters']);
            $recommended_content['characters'] = array_filter(array_map('intval', explode(',', $characters)));
        }
        
        // 处理推荐词语更新（支持下拉选择和手动输入）
        if (isset($_POST['words_select']) && is_array($_POST['words_select'])) {
            $recommended_content['words'] = array_map('intval', $_POST['words_select']);
        } else if (isset($_POST['recommended_words'])) {
            $words = sanitize_text_field($_POST['recommended_words']);
            $recommended_content['words'] = array_filter(array_map('intval', explode(',', $words)));
        }
        
        // 处理推荐成语更新（支持下拉选择和手动输入）
        if (isset($_POST['idioms_select']) && is_array($_POST['idioms_select'])) {
            $recommended_content['idioms'] = array_map('intval', $_POST['idioms_select']);
        } else if (isset($_POST['recommended_idioms'])) {
            $idioms = sanitize_text_field($_POST['recommended_idioms']);
            $recommended_content['idioms'] = array_filter(array_map('intval', explode(',', $idioms)));
        }
        
        // 处理推荐古籍更新（支持下拉选择和手动输入）
        if (isset($_POST['ancient_texts_select']) && is_array($_POST['ancient_texts_select'])) {
            $recommended_content['ancient_texts'] = array_map('intval', $_POST['ancient_texts_select']);
        } else if (isset($_POST['recommended_ancient_texts'])) {
            $ancient_texts = sanitize_text_field($_POST['recommended_ancient_texts']);
            $recommended_content['ancient_texts'] = array_filter(array_map('intval', explode(',', $ancient_texts)));
        }
        
        // 处理推荐书法作品更新（支持下拉选择和手动输入）
        if (isset($_POST['calligraphies_select']) && is_array($_POST['calligraphies_select'])) {
            $recommended_content['calligraphies'] = array_map('intval', $_POST['calligraphies_select']);
        } else if (isset($_POST['recommended_calligraphies'])) {
            $calligraphies = sanitize_text_field($_POST['recommended_calligraphies']);
            $recommended_content['calligraphies'] = array_filter(array_map('intval', explode(',', $calligraphies)));
        }
        
        // 处理推荐文章更新（支持下拉选择和手动输入）
        if (isset($_POST['posts_select']) && is_array($_POST['posts_select'])) {
            $recommended_content['posts'] = array_map('intval', $_POST['posts_select']);
        } else if (isset($_POST['recommended_posts'])) {
            $posts = sanitize_text_field($_POST['recommended_posts']);
            $recommended_content['posts'] = array_filter(array_map('intval', explode(',', $posts)));
        }
        
        // 处理推荐页面更新（支持下拉选择和手动输入）
        if (isset($_POST['pages_select']) && is_array($_POST['pages_select'])) {
            $recommended_content['pages'] = array_map('intval', $_POST['pages_select']);
        } else if (isset($_POST['recommended_pages'])) {
            $pages = sanitize_text_field($_POST['recommended_pages']);
            $recommended_content['pages'] = array_filter(array_map('intval', explode(',', $pages)));
        }
        
        update_option('chinese_character_recommended_content', $recommended_content);
        
        // 添加管理员通知
        add_action('admin_notices', function() {
            echo '<div class="notice notice-success"><p>推荐内容设置已保存。</p></div>';
        });
    }
    
    /**
     * 获取指定部首的汉字列表（AJAX回调）
     */
    public function get_characters_by_radical_callback() {
        // 验证nonce
        if (!wp_verify_nonce($_POST['nonce'], 'radical_nonce')) {
            wp_die('安全验证失败');
        }
        
        $radical = sanitize_text_field($_POST['radical']);
        
        if (empty($radical)) {
            wp_send_json_error('部首参数不能为空');
        }
        
        // 查询包含指定部首的汉字
        $args = array(
            'post_type' => 'chinese_character',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'meta_query' => array(
                array(
                    'key' => '_character_radical',
                    'value' => $radical,
                    'compare' => '='
                )
            ),
            'meta_key' => '_character_stroke_count',
            'orderby' => 'meta_value_num',
            'order' => 'ASC'
        );
        
        $characters_query = new WP_Query($args);
        $characters = array();
        
        if ($characters_query->have_posts()) {
            while ($characters_query->have_posts()) {
                $characters_query->the_post();
                
                $characters[] = array(
                    'id' => get_the_ID(),
                    'title' => get_the_title(),
                    'permalink' => get_permalink(),
                    'pinyin' => get_post_meta(get_the_ID(), '_character_pinyin', true),
                    'stroke_count' => get_post_meta(get_the_ID(), '_character_stroke_count', true)
                );
            }
            wp_reset_postdata();
        }
        
        wp_send_json_success($characters);
    }
    
    /**
     * 获取方言条目列表（AJAX回调）
     */
    public function get_dialect_entries_callback() {
        // 构建查询参数
        $meta_query = array(
            'relation' => 'OR',
            array(
                'key' => '_character_structured_explanations',
                'compare' => 'EXISTS'
            )
        );
        
        // 根据筛选条件添加查询条件
        if (!empty($_POST['dialect_region'])) {
            $meta_query[] = array(
                'key' => '_character_structured_explanations_%_dialect_region',
                'value' => sanitize_text_field($_POST['dialect_region']),
                'compare' => 'LIKE'
            );
        }
        
        if (!empty($_POST['dialect_city'])) {
            $meta_query[] = array(
                'key' => '_character_structured_explanations_%_dialect_city',
                'value' => sanitize_text_field($_POST['dialect_city']),
                'compare' => 'LIKE'
            );
        }
        
        if (!empty($_POST['province'])) {
            $meta_query[] = array(
                'key' => '_character_structured_explanations_%_province',
                'value' => sanitize_text_field($_POST['province']),
                'compare' => 'LIKE'
            );
        }
        
        $args = array(
            'post_type' => 'chinese_character',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'meta_query' => $meta_query
        );
        
        // 如果有搜索关键词，则添加搜索条件
        if (!empty($_POST['search'])) {
            $args['s'] = sanitize_text_field($_POST['search']);
        }
        
        // 执行查询
        $characters_query = new WP_Query($args);
        $entries = array();
        
        if ($characters_query->have_posts()) {
            while ($characters_query->have_posts()) {
                $characters_query->the_post();
                
                // 获取结构化解释
                $structured_explanations = get_post_meta(get_the_ID(), '_character_structured_explanations', true);
                
                if (!empty($structured_explanations) && is_array($structured_explanations)) {
                    foreach ($structured_explanations as $explanation) {
                        // 检查是否匹配筛选条件
                        $matches_filter = true;
                        
                        if (!empty($_POST['dialect_region']) && 
                            (!isset($explanation['dialect_region']) || 
                             $explanation['dialect_region'] != sanitize_text_field($_POST['dialect_region']))) {
                            $matches_filter = false;
                        }
                        
                        if (!empty($_POST['dialect_city']) && 
                            (!isset($explanation['dialect_city']) || 
                             $explanation['dialect_city'] != sanitize_text_field($_POST['dialect_city']))) {
                            $matches_filter = false;
                        }
                        
                        if (!empty($_POST['province']) && 
                            (!isset($explanation['province']) || 
                             $explanation['province'] != sanitize_text_field($_POST['province']))) {
                            $matches_filter = false;
                        }
                        
                        // 如果有搜索关键词，检查是否匹配
                        if (!empty($_POST['search'])) {
                            $search_term = sanitize_text_field($_POST['search']);
                            $matches_search = (stripos(get_the_title(), $search_term) !== false) || // 字符匹配
                                             (isset($explanation['pinyin']) && stripos($explanation['pinyin'], $search_term) !== false) || // 拼音匹配
                                             (isset($explanation['explanation']) && stripos($explanation['explanation'], $search_term) !== false); // 释义匹配
                            
                            $matches_filter = $matches_filter && $matches_search;
                        }
                        
                        if ($matches_filter) {
                            $entries[] = array(
                                'id' => get_the_ID() . '_' . md5(serialize($explanation)), // 生成唯一ID
                                'post_id' => get_the_ID(),
                                'character' => get_the_title(),
                                'pronunciation' => isset($explanation['pinyin']) ? $explanation['pinyin'] : '',
                                'definition' => isset($explanation['explanation']) ? wp_kses_post($explanation['explanation']) : '',
                                'location' => $this->get_dialect_location_string($explanation)
                            );
                        }
                    }
                }
            }
            wp_reset_postdata();
        }
        
        wp_send_json_success($entries);
    }
    
    /**
     * 获取方言条目详情（AJAX回调）
     */
    public function get_dialect_entry_detail_callback() {
        $post_id = intval($_POST['post_id']);
        
        if (empty($post_id)) {
            wp_send_json_error('无效的文章ID');
        }
        
        $post = get_post($post_id);
        
        if (!$post || $post->post_type !== 'chinese_character') {
            wp_send_json_error('找不到指定的文章');
        }
        
        // 获取所有结构化解释
        $structured_explanations = get_post_meta($post_id, '_character_structured_explanations', true);
        
        if (empty($structured_explanations) || !is_array($structured_explanations)) {
            wp_send_json_error('该条目没有结构化解释信息');
        }
        
        // 获取第一个解释作为详情（实际应用中可能需要更精确的匹配）
        $explanation = $structured_explanations[0];
        
        $entry_detail = array(
            'character' => $post->post_title,
            'pronunciation' => isset($explanation['pinyin']) ? $explanation['pinyin'] : '',
            'definition' => isset($explanation['explanation']) ? wp_kses_post($explanation['explanation']) : '',
            'research' => isset($explanation['research']) ? wp_kses_post($explanation['research']) : '',
            'examples' => isset($explanation['example_sentences']) ? array_filter(preg_split('/\r\n|\r|\n/', wp_kses_post($explanation['example_sentences']))) : array(),
            'location' => $this->get_dialect_location_string($explanation)
        );
        
        wp_send_json_success($entry_detail);
    }
    
    /**
     * 构建方言位置字符串
     */
    private function get_dialect_location_string($explanation) {
        $location_parts = array();
        
        if (!empty($explanation['dialect_region'])) {
            $location_parts[] = $explanation['dialect_region'];
        }
        
        if (!empty($explanation['dialect_city'])) {
            $location_parts[] = $explanation['dialect_city'];
        }
        
        if (!empty($explanation['province'])) {
            $location_parts[] = $explanation['province'];
        }
        
        if (!empty($explanation['city'])) {
            $location_parts[] = $explanation['city'];
        }
        
        return implode(' · ', $location_parts);
    }
    
    /**
     * 获取拼音列表（包含自定义项）
     */
    public function get_pinyin_list() {
        // 应用过滤器获取基础列表
        $pinyin_list = apply_filters('chinese_character_pinyin_list', $this->pinyin_list);
        
        // 获取自定义拼音列表
        $custom_pinyin = get_option('chinese_character_custom_pinyin', array());
        
        // 合并列表
        if (!empty($custom_pinyin)) {
            $pinyin_list = array_merge($pinyin_list, $custom_pinyin);
            // 去重并排序
            $pinyin_list = array_unique($pinyin_list);
            sort($pinyin_list);
        }
        
        return $pinyin_list;
    }
    
    /**
     * 获取部首列表（包含自定义项）
     */
    public function get_radical_list() {
        // 应用过滤器获取基础列表
        $radical_list = apply_filters('chinese_character_radical_list', $this->radical_list);
        
        // 获取自定义部首列表
        $custom_radical = get_option('chinese_character_custom_radical', array());
        
        // 合并列表
        if (!empty($custom_radical)) {
            $radical_list = array_merge($radical_list, $custom_radical);
            // 去重
            $radical_list = array_unique($radical_list);
        }
        
        return $radical_list;
    }
    
    /**
     * 添加自定义查询变量
     */
    /**
     * 添加自定义查询变量
     */
    // public function add_query_vars($vars) {
    //     $vars[] = 'pinyin_index';
    //     $vars[] = 'radical_index';
    //     $vars[] = 'professional_search';
    //     $vars[] = 'subcategory';
    //     $vars[] = 'category_search';
    //     return $vars;
    // }
}

// 初始化插件
new ChineseCharacterDictionary();