<?php
/**
 * HMY 产品活动日志 - 独立公共入口
 *
 * 两个用途（按 mode 参数区分）：
 *   1. mode=config：输出悬浮按钮运行时配置 JSON（嵌入代码里的 JS 每 10 秒拉取）
 *   2. 默认：输出前台展示页（iframe 弹窗内嵌的文章/活动日志页面）
 *
 * 本文件被粘贴到任意外部页面的嵌入代码引用，刻意不依赖框架与插件其他文件：
 * 直接读取站点数据库配置连接 MySQL，所有清洗/规范化工具自包含。
 * 注意：本文件中的 SVG 清洗、位置规范化等与 lib/HmyConfigNormalizer 存在
 * 刻意保留的行为差异（如不剥离 SVG 注释），为保证线上行为一致不做合并。
 */

/* ==================== 1. 运行环境：禁用缓存 + 直连数据库 ==================== */

header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
$config = require dirname(__DIR__, 4) . '/app/config/database.php';
$prefix = preg_replace('/[^a-zA-Z0-9_]/', '', (string) ($config['prefix'] ?? 'shd_'));
$mysqli = @new mysqli(
    (string) ($config['hostname'] ?? 'localhost'),
    (string) ($config['username'] ?? ''),
    (string) ($config['password'] ?? ''),
    (string) ($config['database'] ?? ''),
    (int) ($config['hostport'] ?? 3306)
);
if ($mysqli->connect_errno) {
    http_response_code(503);
    exit('Service unavailable');
}
$mysqli->set_charset((string) ($config['charset'] ?? 'utf8mb4'));

/* ==================== 2. 自包含工具函数 ==================== */

/** 非空字符串兜底：去除首尾空白后为空则返回默认值 */
function hmyPublicConfigValue($value, $default = '')
{
    $value = trim((string) $value);
    return $value === '' ? $default : $value;
}

/**
 * SVG 安全清洗：仅接受 <svg>...</svg> 根结构，剥离危险标签、
 * 事件属性与 javascript:/data:/外链 URL()。
 * （与 lib/HmyConfigNormalizer::svg 的差异：本版本不剥离注释）
 */
function hmyPublicSvg($value)
{
    $value = trim((string) $value);
    if ($value === '' || strlen($value) > 100000 || !preg_match('/^<svg\\b[\\s\\S]*<\\/svg>$/i', $value)) return '';
    $value = preg_replace('/<\\/?(script|foreignObject|iframe|object|embed|form)\\b[^>]*>[\\s\\S]*?<\\/\\1\\s*>/is', '', $value);
    $value = preg_replace('/<\\/?(script|foreignObject|iframe|object|embed|form)\\b[^>]*\\/?\\s*>/is', '', $value);
    $value = preg_replace('/\\s(on[a-z]+|href|xlink:href|src)\\s*=\\s*(?:"[^"]*"|\\x27[^\\x27]*\\x27|[^\\s>]+)/i', '', $value);
    $value = preg_replace('/url\\s*\\(\\s*["\\x27]?\\s*(?:javascript:|data:|https?:|\\/\\/)[^)]*\\)/i', 'none', $value);
    return preg_match('/^<svg\\b[\\s\\S]*<\\/svg>$/i', trim($value)) ? trim($value) : '';
}

/**
 * 富文本白名单清洗：剥除 script/style/iframe/object/embed/form 标签、
 * on* 事件属性；style 仅保留 color/background(-color) 三类安全值；
 * 最后移除 javascript: 协议
 */
function hmyPublicClean($html)
{
    $html = (string) $html;
    // 先做最多 3 轮实体解码，防止多层编码绕过
    for ($hmyRound = 0; $hmyRound < 3; $hmyRound++) {
        $hmyDecoded = html_entity_decode($html, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        if ($hmyDecoded === $html) break;
        $html = $hmyDecoded;
    }
    $html = preg_replace('/<(script|style|iframe|object|embed|form)[^>]*>.*?<\/\1>/is', '', $html);
    $html = preg_replace('/\s(on[a-z]+)\s*=\s*(["\']).*?\2/is', '', $html);
    $html = preg_replace_callback('/\sstyle\s*=\s*(["\'])(.*?)\1/is', function($hmyMatch) {
        $hmySafeStyles = array();
        foreach (explode(';', (string) $hmyMatch[2]) as $hmyDeclaration) {
            $hmyParts = explode(':', $hmyDeclaration, 2);
            if (count($hmyParts) !== 2) continue;
            $hmyProperty = strtolower(trim($hmyParts[0]));
            $hmyValue = trim($hmyParts[1]);
            if (!in_array($hmyProperty, array('color', 'background-color', 'background'), true)) continue;
            if ($hmyValue === '' || preg_match('/url\s*\(|expression\s*\(|javascript\s*:/i', $hmyValue)) continue;
            if (!preg_match('/^(#[0-9a-f]{3,8}|rgba?\(\s*[0-9.%]+(?:\s*,\s*[0-9.%]+){2,3}\s*\)|hsla?\(\s*[0-9.%]+(?:\s*,\s*[0-9.%]+){2,3}\s*\)|[a-z][a-z0-9 -]{0,30})$/i', $hmyValue)) continue;
            $hmySafeStyles[] = $hmyProperty . ':' . $hmyValue;
        }
        return $hmySafeStyles ? ' style="' . htmlspecialchars(implode(';', $hmySafeStyles), ENT_QUOTES, 'UTF-8') . '"' : '';
    }, $html);
    return preg_replace('/javascript\s*:/i', '', $html);
}

/** HTML 输出转义 */
function hmyPublicEsc($value)
{
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}

/** 执行查询并返回全部行（查询失败返回空数组） */
function hmyPublicRows($mysqli, $sql)
{
    $rows = array();
    $result = $mysqli->query($sql);
    if (!$result) return $rows;
    while ($row = $result->fetch_assoc()) $rows[] = $row;
    $result->free();
    return $rows;
}

/** 给图片 URL 追加内容哈希版本参数，用于后台改图后突破浏览器缓存 */
function hmyPublicVersionedImageUrl($hmyUrl)
{
    $hmyUrl = trim((string) $hmyUrl);
    if ($hmyUrl === '') return '';
    $hmySeparator = strpos($hmyUrl, '?') === false ? '?' : '&';
    return $hmyUrl . $hmySeparator . 'hmy_bg=' . rawurlencode(substr(sha1($hmyUrl), 0, 12));
}

/**
 * 悬浮按钮位置规范化：仅放行 top/right/bottom/left 四方向
 * 与 px/%/rem/vw/vh 单位，非法输入回退默认位置
 */
function hmyPublicNormalizePosition($hmyValue, $hmyDefault)
{
    $hmyPositionFields = array('top', 'right', 'bottom', 'left');
    $hmyPosition = is_array($hmyValue) ? $hmyValue : json_decode(htmlspecialchars_decode(trim((string) $hmyValue), ENT_QUOTES), true);
    if (!is_array($hmyPosition)) $hmyPosition = $hmyDefault;
    $hmySafePosition = array();
    foreach ($hmyPosition as $hmyName => $hmyPositionValue) {
        if (in_array($hmyName, $hmyPositionFields, true) && preg_match('/^\d+(px|%|rem|vw|vh)$/', (string) $hmyPositionValue)) $hmySafePosition[$hmyName] = (string) $hmyPositionValue;
    }
    return $hmySafePosition ?: $hmyDefault;
}

/**
 * 输出悬浮按钮运行时配置 JSON 并结束请求（mode=config 分支）
 * 结构：{button:{...}, modal:{...}, 以及一组扁平兼容键}
 */
function hmyPublicServeConfig($mysqli, $hmyPluginConfig)
{
    $hmyButtonColor = preg_match('/^#[0-9a-fA-F]{6}$/', (string) ($hmyPluginConfig['hmy_button_color'] ?? '')) ? $hmyPluginConfig['hmy_button_color'] : '#2378f7';
    $hmyButtonSize = max(36, min(96, intval($hmyPluginConfig['hmy_button_size'] ?? 48)));
    $hmyModalAutoSize = (string) ($hmyPluginConfig['hmy_modal_auto_size'] ?? '1') === '1';
    $hmyModalWidth = max(600, min(1600, intval($hmyPluginConfig['hmy_modal_width'] ?? 1100)));
    $hmyModalHeight = max(400, min(1200, intval($hmyPluginConfig['hmy_modal_height'] ?? 820)));
    $hmyModalColor = preg_match('/^#[0-9a-fA-F]{6}$/', (string) ($hmyPluginConfig['hmy_modal_background_color'] ?? '')) ? $hmyPluginConfig['hmy_modal_background_color'] : '#ffffff';
    $hmyModalImage = trim((string) ($hmyPluginConfig['hmy_modal_background_image'] ?? ''));
    if ($hmyModalImage !== '' && !preg_match('#^(https?:)?//|^/#i', $hmyModalImage)) $hmyModalImage = '';
    $hmyDesktopPosition = hmyPublicNormalizePosition($hmyPluginConfig['hmy_button_desktop_position'] ?? '', array('right' => '28px', 'bottom' => '120px'));
    $hmyMobilePosition = hmyPublicNormalizePosition($hmyPluginConfig['hmy_button_mobile_position'] ?? '', array('right' => '14px', 'bottom' => '92px'));
    $hmyPagePaths = array();
    $hmyPageValue = str_replace(array("\r\n", "\r", ',', ';'), "\n", (string) ($hmyPluginConfig['hmy_button_page_paths'] ?? ''));
    foreach (preg_split('/\n+/', $hmyPageValue) as $hmyPageRow) {
        $hmyPageRow = trim($hmyPageRow);
        if ($hmyPageRow === '') continue;
        if ($hmyPageRow[0] !== '/') $hmyPageRow = '/' . $hmyPageRow;
        $hmyPageRow = parse_url($hmyPageRow, PHP_URL_PATH);
        $hmyPageRow = '/' . ltrim(preg_replace('#/+#', '/', (string) ($hmyPageRow ?: '/')), '/');
        if ($hmyPageRow !== '/') $hmyPageRow = rtrim($hmyPageRow, '/');
        if (preg_match('#^/[A-Za-z0-9_./-]*$#', $hmyPageRow) && !in_array($hmyPageRow, $hmyPagePaths, true)) $hmyPagePaths[] = $hmyPageRow;
    }
    $hmyPublicConfig = array(
        'button' => array(
            'enabled' => (string) ($hmyPluginConfig['hmy_button_enabled'] ?? '0') === '1',
            'text' => hmyPublicConfigValue($hmyPluginConfig['hmy_button_text'] ?? '', '产品更新日志'),
            'icon' => hmyPublicConfigValue($hmyPluginConfig['hmy_button_icon'] ?? '', '↗'),
            'color' => $hmyButtonColor,
            'size' => $hmyButtonSize,
            'icon_background_image' => preg_match('#^(https?:)?//|^/#i', trim((string) ($hmyPluginConfig['hmy_float_icon_background_image'] ?? ''))) ? trim((string) $hmyPluginConfig['hmy_float_icon_background_image']) : 'https://haimoyun.com/themes/web/sp/automatic.png',
            'icon_border_width' => max(0, intval($hmyPluginConfig['hmy_float_icon_border_width'] ?? 4)),
            'icon_border_color' => preg_match('/^(#[0-9a-fA-F]{3,8}|rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+(\s*,\s*(0|1|0?\.\d+))?\s*\))$/', (string) ($hmyPluginConfig['hmy_float_icon_border_color'] ?? '')) ? $hmyPluginConfig['hmy_float_icon_border_color'] : '#ffffff',
            'label_background_color' => preg_match('/^(#[0-9a-fA-F]{3,8}|rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+(\s*,\s*(0|1|0?\.\d+))?\s*\))$/', (string) ($hmyPluginConfig['hmy_float_label_background_color'] ?? '')) ? $hmyPluginConfig['hmy_float_label_background_color'] : '#2491ff',
            'label_padding' => array('top'=>max(0, intval($hmyPluginConfig['hmy_float_label_padding_top'] ?? 5)),'right'=>max(0, intval($hmyPluginConfig['hmy_float_label_padding_right'] ?? 9)),'bottom'=>max(0, intval($hmyPluginConfig['hmy_float_label_padding_bottom'] ?? 4)),'left'=>max(0, intval($hmyPluginConfig['hmy_float_label_padding_left'] ?? 9))),
            'label_border_width' => max(0, intval($hmyPluginConfig['hmy_float_label_border_width'] ?? 2)),
            'label_border_color' => preg_match('/^(#[0-9a-fA-F]{3,8}|rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+(\s*,\s*(0|1|0?\.\d+))?\s*\))$/', (string) ($hmyPluginConfig['hmy_float_label_border_color'] ?? '')) ? $hmyPluginConfig['hmy_float_label_border_color'] : '#ffffff',
            'desktop_position' => $hmyDesktopPosition,
            'mobile_position' => $hmyMobilePosition,
        ),
        'modal' => array(
            'page_paths' => $hmyPagePaths,
            'auto_size' => $hmyModalAutoSize,
            'width' => $hmyModalWidth,
            'height' => $hmyModalHeight,
            'background_color' => $hmyModalColor,
            'background_image' => $hmyModalImage,
            'z_index' => max(1000, min(2147483647, intval($hmyPluginConfig['hmy_modal_z_index'] ?? 10001))),
            'overlay_color' => preg_match('/^(#[0-9a-fA-F]{6}|rgba?\\(\\s*\\d+\\s*,\\s*\\d+\\s*,\\s*\\d+(\\s*,\\s*(0|1|0?\\.\\d+))?\\s*\\))$/', (string) ($hmyPluginConfig['hmy_modal_overlay_color'] ?? '')) ? $hmyPluginConfig['hmy_modal_overlay_color'] : 'rgba(15,23,42,.55)',
            'border_radius' => max(0, min(32, intval($hmyPluginConfig['hmy_modal_border_radius'] ?? 8))),
            'action_size' => max(28, min(64, intval($hmyPluginConfig['hmy_modal_action_size'] ?? 36))),
            'action_background' => preg_match('/^(#[0-9a-fA-F]{6}|rgba?\\(\\s*\\d+\\s*,\\s*\\d+\\s*,\\s*\\d+(\\s*,\\s*(0|1|0?\\.\\d+))?\\s*\\))$/', (string) ($hmyPluginConfig['hmy_modal_action_background'] ?? '')) ? $hmyPluginConfig['hmy_modal_action_background'] : 'rgba(255,255,255,.92)',
            'action_color' => preg_match('/^#[0-9a-fA-F]{6}$/', (string) ($hmyPluginConfig['hmy_modal_action_color'] ?? '')) ? $hmyPluginConfig['hmy_modal_action_color'] : '#475569',
            'full_svg' => hmyPublicSvg($hmyPluginConfig['hmy_modal_full_svg'] ?? ''),
            'full_width' => max(0, intval($hmyPluginConfig['hmy_modal_full_width'] ?? 36)),
            'full_height' => max(0, intval($hmyPluginConfig['hmy_modal_full_height'] ?? 36)),
            'full_background' => preg_match('/^(#[0-9a-fA-F]{3,8}|rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+(\s*,\s*(0|1|0?\.\d+))?\s*\))$/', (string) ($hmyPluginConfig['hmy_modal_full_background'] ?? '')) ? $hmyPluginConfig['hmy_modal_full_background'] : 'rgba(255,255,255,.92)',
            'full_top' => max(0, intval($hmyPluginConfig['hmy_modal_full_top'] ?? 3)),
            'close_svg' => hmyPublicSvg($hmyPluginConfig['hmy_modal_close_svg'] ?? ''),
            'close_width' => max(0, intval($hmyPluginConfig['hmy_modal_close_width'] ?? 36)),
            'close_height' => max(0, intval($hmyPluginConfig['hmy_modal_close_height'] ?? 36)),
            'close_background' => preg_match('/^(#[0-9a-fA-F]{3,8}|rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+(\s*,\s*(0|1|0?\.\d+))?\s*\))$/', (string) ($hmyPluginConfig['hmy_modal_close_background'] ?? '')) ? $hmyPluginConfig['hmy_modal_close_background'] : 'rgba(255,255,255,.92)',
            'close_top' => max(0, intval($hmyPluginConfig['hmy_modal_close_top'] ?? 3)),
            'close_on_overlay' => (string) ($hmyPluginConfig['hmy_modal_close_on_overlay'] ?? '1') === '1',
            'close_on_escape' => (string) ($hmyPluginConfig['hmy_modal_close_on_escape'] ?? '1') === '1',
            'title' => trim((string) ($hmyPluginConfig['hmy_modal_title'] ?? '产品更新日志')) ?: '产品更新日志',
        ),
    );
    // 扁平兼容键：兼容旧版嵌入代码直接读顶层字段的用法
    $hmyPublicConfig['button_enabled'] = $hmyPublicConfig['button']['enabled'];
    $hmyPublicConfig['button_text'] = $hmyPublicConfig['button']['text'];
    $hmyPublicConfig['button_icon'] = $hmyPublicConfig['button']['icon'];
    $hmyPublicConfig['button_color'] = $hmyPublicConfig['button']['color'];
    $hmyPublicConfig['button_size'] = $hmyPublicConfig['button']['size'];
    $hmyPublicConfig['modal_auto_size'] = $hmyPublicConfig['modal']['auto_size'];
    $hmyPublicConfig['modal_width'] = $hmyPublicConfig['modal']['width'];
    $hmyPublicConfig['modal_height'] = $hmyPublicConfig['modal']['height'];
    $hmyPublicConfig['modal_background_color'] = $hmyPublicConfig['modal']['background_color'];
    $hmyPublicConfig['modal_background_image'] = $hmyPublicConfig['modal']['background_image'];
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($hmyPublicConfig, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $mysqli->close();
    exit;
}

/* ==================== 3. 读取插件配置行 ==================== */

$hmyPluginTable = '`' . $prefix . 'plugin`';
$hmyPluginConfig = array();
$hmyPluginResult = $mysqli->query("SELECT config FROM {$hmyPluginTable} WHERE name='HmyProductActivityLog' AND module='addons' LIMIT 1");
if ($hmyPluginResult && ($hmyPluginRow = $hmyPluginResult->fetch_assoc())) {
    $hmyDecodedPluginConfig = json_decode((string) ($hmyPluginRow['config'] ?? ''), true);
    if (is_array($hmyDecodedPluginConfig)) $hmyPluginConfig = $hmyDecodedPluginConfig;
}
if ($hmyPluginResult) $hmyPluginResult->free();

/* ==================== 4. mode=config：输出运行时配置 JSON ==================== */

if (isset($_GET['mode']) && $_GET['mode'] === 'config') {
    hmyPublicServeConfig($mysqli, $hmyPluginConfig);
}

/* ==================== 5. 内容数据查询与整形 ==================== */

$articleTable = '`' . $prefix . 'hmy_articles`';
$activityTable = '`' . $prefix . 'hmy_product_activity_log`';
$categoryTable = '`' . $prefix . 'hmy_product_activity_category`';
$articles = hmyPublicRows($mysqli, "SELECT a.*, c.hmy_name AS hmy_category_name FROM {$articleTable} a LEFT JOIN {$categoryTable} c ON c.hmy_id=a.hmy_category_id WHERE a.hmy_status=1 ORDER BY a.hmy_is_top DESC, a.hmy_sort DESC, a.hmy_publish_time DESC, a.hmy_id DESC LIMIT 50");
$activities = hmyPublicRows($mysqli, "SELECT a.*, c.hmy_name AS hmy_category_name FROM {$activityTable} a LEFT JOIN {$categoryTable} c ON c.hmy_id=a.hmy_category_id WHERE a.hmy_status=1 ORDER BY a.hmy_sort DESC, a.hmy_activity_time DESC, a.hmy_id DESC LIMIT 50");
$categories = hmyPublicRows($mysqli, "SELECT hmy_id, hmy_name FROM {$categoryTable} WHERE hmy_status=1 ORDER BY hmy_sort ASC, hmy_id ASC");
foreach ($articles as &$article) {
    $article['hmy_content'] = hmyPublicClean($article['hmy_content'] ?? '');
    $article['hmy_description'] = hmyPublicClean($article['hmy_description'] ?? '');
    $article['hmy_time_text'] = !empty($article['hmy_publish_time']) ? date('Y-m-d H:i', (int) $article['hmy_publish_time']) : '-';
    $article['hmy_type'] = 'article';
}
unset($article);
foreach ($activities as &$activity) {
    $activity['hmy_content'] = hmyPublicClean($activity['hmy_content'] ?? '');
    $activity['hmy_time_text'] = !empty($activity['hmy_activity_time']) ? date('Y-m-d', (int) $activity['hmy_activity_time']) : '-';
    $activity['hmy_type'] = 'activity';
}
unset($activity);
// 按分类聚合文章发布月份，生成"YYYY年N期"期数导航
$hmyCategoryPeriodRows = hmyPublicRows($mysqli, "SELECT hmy_category_id, hmy_publish_time FROM {$articleTable} WHERE hmy_status=1 AND hmy_category_id>0 AND hmy_publish_time>0 ORDER BY hmy_publish_time DESC, hmy_id DESC");
$hmyCategoryPeriodMap = array();
foreach ($hmyCategoryPeriodRows as $hmyPeriodRow) {
    $hmyCategoryId = (int) ($hmyPeriodRow['hmy_category_id'] ?? 0);
    $hmyPublishTime = (int) ($hmyPeriodRow['hmy_publish_time'] ?? 0);
    if (!$hmyCategoryId || !$hmyPublishTime) continue;
    $hmyPeriodKey = date('Y-m', $hmyPublishTime);
    if (isset($hmyCategoryPeriodMap[$hmyCategoryId][$hmyPeriodKey])) continue;
    $hmyCategoryPeriodMap[$hmyCategoryId][$hmyPeriodKey] = array(
        'key' => $hmyPeriodKey,
        'text' => date('Y', $hmyPublishTime) . '年' . (int) date('n', $hmyPublishTime) . '期'
    );
}
foreach ($categories as &$category) {
    $hmyPeriods = array_values($hmyCategoryPeriodMap[(int) $category['hmy_id']] ?? array());
    $category['hmy_periods'] = $hmyPeriods;
    $category['hmy_period_text'] = $hmyPeriods ? implode('、', array_column($hmyPeriods, 'text')) : '';
}
unset($category);

/* ==================== 6. 前端展示配置解析 ==================== */

$hmyFrontDefaults = array('hmy_front_background_image'=>'','hmy_front_category_background_image'=>'','hmy_front_pc_background_image'=>'','hmy_front_mobile_background_image'=>'','hmy_front_pc_title_size'=>'70','hmy_front_mobile_title_size'=>'36','hmy_front_pc_body_size'=>'16','hmy_front_mobile_body_size'=>'13','hmy_front_category_pc_background_image'=>'','hmy_front_category_mobile_background_image'=>'','hmy_front_category_pc_title_size'=>'17','hmy_front_category_mobile_title_size'=>'17','hmy_front_category_pc_body_size'=>'16','hmy_front_category_mobile_body_size'=>'16','hmy_front_content_pc_background_image'=>'','hmy_front_content_mobile_background_image'=>'','hmy_front_title'=>'产品更新日志','hmy_front_brand'=>'海沫云','hmy_front_subtitle'=>'每月最新产品实时动态资讯','hmy_front_emphasis'=>'重磅发布','hmy_front_sidebar_title'=>'产品更新大纲','hmy_front_font_family'=>'Microsoft YaHei','hmy_front_title_size'=>'70','hmy_front_title_weight'=>'800','hmy_front_title_color'=>'#081d46','hmy_front_body_size'=>'16','hmy_front_body_color'=>'#334155','hmy_front_emphasis_color'=>'#ffffff','hmy_front_emphasis_background'=>'#f59e0b');
$hmyFrontConfig = $hmyFrontDefaults;
$hmyFrontStoredKeys = array();
$hmyPluginTable = '`' . $prefix . 'plugin`';
$hmyPluginResult = $mysqli->query("SELECT config FROM {$hmyPluginTable} WHERE name='HmyProductActivityLog' AND module='addons' LIMIT 1");
if ($hmyPluginResult && ($hmyPluginRow = $hmyPluginResult->fetch_assoc())) {
    $hmyStoredConfig = json_decode((string) ($hmyPluginRow['config'] ?? ''), true);
    if (is_array($hmyStoredConfig)) { $hmyFrontStoredKeys = array_keys($hmyStoredConfig); foreach ($hmyFrontDefaults as $hmyKey=>$hmyDefault) if (array_key_exists($hmyKey,$hmyStoredConfig)) $hmyFrontConfig[$hmyKey]=(string) $hmyStoredConfig[$hmyKey]; }
}
if ($hmyPluginResult) $hmyPluginResult->free();
// 图片配置仅放行 http(s) 外链或站内绝对路径
foreach (array('hmy_front_background_image','hmy_front_category_background_image','hmy_front_pc_background_image','hmy_front_mobile_background_image','hmy_front_category_pc_background_image','hmy_front_category_mobile_background_image','hmy_front_content_pc_background_image','hmy_front_content_mobile_background_image') as $hmyFrontImageKey) if ($hmyFrontConfig[$hmyFrontImageKey] !== '' && !preg_match('#^(https?:)?//|^/#i',$hmyFrontConfig[$hmyFrontImageKey])) $hmyFrontConfig[$hmyFrontImageKey]='';
// 旧配置兼容：未单独配置 PC/手机端背景图时逐级沿用旧字段
if (!in_array('hmy_front_pc_background_image', $hmyFrontStoredKeys, true)) $hmyFrontConfig['hmy_front_pc_background_image'] = $hmyFrontConfig['hmy_front_background_image'];
if (!in_array('hmy_front_mobile_background_image', $hmyFrontStoredKeys, true)) $hmyFrontConfig['hmy_front_mobile_background_image'] = $hmyFrontConfig['hmy_front_pc_background_image'];
if (!in_array('hmy_front_category_pc_background_image', $hmyFrontStoredKeys, true)) $hmyFrontConfig['hmy_front_category_pc_background_image'] = $hmyFrontConfig['hmy_front_category_background_image'];
if (!in_array('hmy_front_category_mobile_background_image', $hmyFrontStoredKeys, true)) $hmyFrontConfig['hmy_front_category_mobile_background_image'] = $hmyFrontConfig['hmy_front_category_pc_background_image'];
if (!in_array('hmy_front_content_mobile_background_image', $hmyFrontStoredKeys, true)) $hmyFrontConfig['hmy_front_content_mobile_background_image'] = $hmyFrontConfig['hmy_front_content_pc_background_image'];
// 响应式字号范围兜底（超出范围回退默认值）
$hmyFrontRanges = array('hmy_front_pc_title_size'=>array(32,100,'70'),'hmy_front_mobile_title_size'=>array(24,70,'36'),'hmy_front_pc_body_size'=>array(12,32,'16'),'hmy_front_mobile_body_size'=>array(10,24,'13'),'hmy_front_category_pc_title_size'=>array(14,32,'17'),'hmy_front_category_mobile_title_size'=>array(14,32,'17'),'hmy_front_category_pc_body_size'=>array(12,24,'16'),'hmy_front_category_mobile_body_size'=>array(12,24,'16'));
foreach ($hmyFrontRanges as $hmySizeKey=>$hmySizeRange) { $hmySizeValue=intval($hmyFrontConfig[$hmySizeKey]); if ($hmySizeValue<$hmySizeRange[0]||$hmySizeValue>$hmySizeRange[1]) $hmyFrontConfig[$hmySizeKey]=$hmySizeRange[2]; }
if (!preg_match('/^[12][0-9]|3[0-2]$/',$hmyFrontConfig['hmy_front_body_size'])) $hmyFrontConfig['hmy_front_body_size']='16';
if (!preg_match('/^(3[2-9]|[4-9][0-9]|100)$/',$hmyFrontConfig['hmy_front_title_size'])) $hmyFrontConfig['hmy_front_title_size']='70';
if (!in_array($hmyFrontConfig['hmy_front_title_weight'],array('400','500','600','700','800','900'),true)) $hmyFrontConfig['hmy_front_title_weight']='800';
foreach (array('hmy_front_title_color','hmy_front_body_color','hmy_front_emphasis_color','hmy_front_emphasis_background') as $hmyColorKey) if (!preg_match('/^#[0-9a-fA-F]{6}$/',$hmyFrontConfig[$hmyColorKey])) $hmyFrontConfig[$hmyColorKey]=$hmyFrontDefaults[$hmyColorKey];
$hmyFrontFontFamily = preg_replace('/[^a-zA-Z0-9_ ,\-\x{4e00}-\x{9fff}]/u','',$hmyFrontConfig['hmy_front_font_family']);
if ($hmyFrontFontFamily==='') $hmyFrontFontFamily=$hmyFrontDefaults['hmy_front_font_family'];
// CSS 变量用的背景 URL（去除引号与换行，并追加版本参数）
$hmyFrontBackgroundUrl = preg_replace('/["\'\r\n]/', '', $hmyFrontConfig['hmy_front_background_image']);
$hmyFrontCategoryBackgroundUrl = preg_replace('/["\'\r\n]/', '', $hmyFrontConfig['hmy_front_category_background_image']);
$hmyFrontPcBackgroundUrl = hmyPublicVersionedImageUrl(preg_replace('/["\'\r\n]/', '', $hmyFrontConfig['hmy_front_pc_background_image']));
$hmyFrontMobileBackgroundUrl = hmyPublicVersionedImageUrl(preg_replace('/["\'\r\n]/', '', $hmyFrontConfig['hmy_front_mobile_background_image']));
$hmyFrontCategoryPcBackgroundUrl = hmyPublicVersionedImageUrl(preg_replace('/["\'\r\n]/', '', $hmyFrontConfig['hmy_front_category_pc_background_image']));
$hmyFrontCategoryMobileBackgroundUrl = hmyPublicVersionedImageUrl(preg_replace('/["\'\r\n]/', '', $hmyFrontConfig['hmy_front_category_mobile_background_image']));
$hmyFrontContentPcBackgroundUrl = hmyPublicVersionedImageUrl(str_replace(array("\"","'",chr(13),chr(10)),'',$hmyFrontConfig['hmy_front_content_pc_background_image']));
$hmyFrontContentMobileBackgroundUrl = hmyPublicVersionedImageUrl(str_replace(array("\"","'",chr(13),chr(10)),'',$hmyFrontConfig['hmy_front_content_mobile_background_image']));
$hmyFrontTitle = hmyPublicEsc($hmyFrontConfig['hmy_front_title']);
$hmyFrontBrand = hmyPublicEsc($hmyFrontConfig['hmy_front_brand']);
$hmyFrontSubtitle = hmyPublicEsc($hmyFrontConfig['hmy_front_subtitle']);
$hmyFrontEmphasis = hmyPublicEsc($hmyFrontConfig['hmy_front_emphasis']);
$hmyFrontSidebarTitle = hmyPublicEsc($hmyFrontConfig['hmy_front_sidebar_title']);
$mysqli->close();

/* ==================== 7. 页面输出 ==================== */

$payload = json_encode(array('articles' => $articles, 'activities' => $activities, 'categories' => $categories), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
?><!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>产品更新日志</title>
<style>
*{box-sizing:border-box}html,body{margin:0;min-height:100%;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif;color:#162033;background:#f5f8fd}.hmy-public{padding:1px;background:#f5f8fd}.hmy-public-head{position:relative;min-height:278px;margin-bottom:26px;border-radius:6px;overflow:hidden;background:linear-gradient(135deg,#68a9ff 0%,#eaf4ff 74%)}.hmy-public-head:after{content:"";position:absolute;left:-5%;right:-5%;bottom:-110px;height:190px;background:rgba(255,255,255,.65);border-radius:50%}.hmy-public-hero{position:relative;z-index:1;padding:70px 30px 48px}.hmy-public-title{font-size:clamp(38px,5vw,70px);font-weight:800;letter-spacing:0;color:#081d46}.hmy-public-sub{margin-top:16px;color:#334155;font-size:16px}.hmy-public-hero-badge{display:inline-block;margin-left:18px;padding:7px 16px;background:#f59e0b;color:#fff;font-size:14px;transform:skew(-12deg);vertical-align:middle}.hmy-public-carousel{position:relative;z-index:2;margin:0 28px 22px;min-height:36px}.hmy-public-carousel-card{display:none;align-items:center;gap:22px;padding:14px 22px;border:1px solid rgba(255,255,255,.7);border-radius:8px;background:rgba(255,255,255,.82);box-shadow:0 8px 24px rgba(30,64,175,.08)}.hmy-public-carousel-card.on{display:flex}.hmy-public-carousel-cover{width:112px;height:64px;flex:0 0 112px;border-radius:5px;object-fit:cover}.hmy-public-carousel-info{min-width:0}.hmy-public-carousel-info h3{margin:0 0 5px;color:#142b63;font-size:18px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.hmy-public-carousel-info p{margin:0;color:#64748b;font-size:13px;line-height:1.5}.hmy-public-carousel-control{position:absolute;top:50%;width:30px;height:30px;border:0;border-radius:50%;background:#287df4;color:#fff;cursor:pointer;transform:translateY(-50%);z-index:3}.hmy-public-carousel-control.prev{left:-14px}.hmy-public-carousel-control.next{right:-14px}.hmy-public-carousel-dots{display:flex;justify-content:center;gap:6px;margin-top:10px}.hmy-public-carousel-dot{width:6px;height:6px;border:0;border-radius:50%;padding:0;background:#cbd5e1;cursor:pointer}.hmy-public-carousel-dot.on{width:18px;border-radius:6px;background:#287df4}.hmy-public-tabs{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:18px}.hmy-public-tab{border:0;border-radius:24px;background:#fff;color:#334155;padding:11px 20px;cursor:pointer;box-shadow:0 2px 10px rgba(30,64,175,.05);white-space:nowrap}.hmy-public-periods{display:flex;align-items:center;gap:10px;flex:1;min-width:260px;overflow-x:auto;padding:2px 0 6px;scrollbar-width:none}.hmy-public-periods::-webkit-scrollbar{display:none}.hmy-public-period-nav{width:34px;height:34px;flex:0 0 34px;border:0;border-radius:50%;background:#287df4;color:#fff;font-size:24px;line-height:1;display:inline-flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 2px 8px rgba(30,64,175,.12)}.hmy-public-period-nav:hover{background:#1d6fe5}.hmy-public-period{border:0;border-radius:24px;background:#fff;color:#64748b;padding:10px 16px;cursor:pointer;white-space:nowrap;box-shadow:0 2px 10px rgba(30,64,175,.05)}.hmy-public-period.on{background:#287df4;color:#fff}.hmy-public-tab.on{background:#287df4;color:#fff}.hmy-public-layout{display:grid;grid-template-columns:minmax(0,1fr) 232px;gap:26px;align-items:start}.hmy-public-list{background:#f8faff;border:1px solid #e6edf7;padding:18px;min-height:420px}.hmy-public-item{position:relative;margin:0 0 14px;padding:22px 24px;border:1px solid #e2eaf5;border-radius:8px;background:#fff;box-shadow:0 3px 12px rgba(30,64,175,.06);cursor:pointer;transition:border-color .18s ease,box-shadow .18s ease,transform .18s ease}.hmy-public-item:last-child{margin-bottom:0}.hmy-public-item:hover{border-color:#b8d2fa;box-shadow:0 7px 18px rgba(30,64,175,.1);transform:translateY(-1px)}.hmy-public-item h2{margin:0 0 12px;padding-bottom:11px;border-bottom:1px solid #edf2f8;font-size:20px;line-height:1.45;color:#142b63}.hmy-public-item p{margin:6px 0;color:#64748b;line-height:1.7}.hmy-public-item p:first-of-type{font-size:13px;color:#7890b2}.hmy-public-item p:last-of-type{color:#475569}.hmy-public-cover{width:180px;height:100px;float:right;object-fit:cover;margin:0 0 10px 22px;border:1px solid #e2eaf5;border-radius:6px}.hmy-public-category{background:#fff;padding:22px 18px;border:1px solid #edf1f7}.hmy-public-category h3{margin:0 0 16px;color:#142b63;font-size:17px}.hmy-public-category button{display:flex;align-items:center;justify-content:space-between;gap:10px;width:100%;border:0;border-bottom:1px solid #f1f5f9;background:transparent;color:#64748b;text-align:left;padding:10px 0;cursor:pointer}.hmy-public-category button span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.hmy-public-category button small{flex:0 0 auto;color:#94a3b8;font-size:12px;white-space:nowrap}.hmy-public-category button.on,.hmy-public-category button:hover{color:#287df4}.hmy-public-category button.on small,.hmy-public-category button:hover small{color:#287df4}.hmy-public-empty{text-align:center;color:#94a3b8;padding:70px 20px}.hmy-public-detail{display:none;background:#fff;padding:34px 52px;min-height:70vh;border:1px solid #edf1f7}.hmy-public-detail h1{margin:0 0 12px;color:#142b63}.hmy-public-detail-meta{color:#64748b;margin-bottom:22px}.hmy-public-body{line-height:1.9;color:#334155}.hmy-public-body img{max-width:100%;height:auto;display:block;margin:14px auto}.hmy-public-back{border:0;background:#eff6ff;color:#1d4ed8;border-radius:6px;padding:9px 14px;cursor:pointer;margin-bottom:22px}@media(max-width:1024px){.hmy-public{display:flex;flex-direction:column;min-width:0}.hmy-public-head{order:1}#hmyPublicListView{display:contents}.hmy-public-tabs{order:3}.hmy-public-period-nav{display:none}.hmy-public-periods{width:100%;min-width:0;flex:1 1 auto;flex-wrap:nowrap;overflow-x:auto;overflow-y:hidden;-webkit-overflow-scrolling:touch;touch-action:pan-x;padding-left:2px;padding-right:2px}.hmy-public-layout{display:contents}.hmy-public-category{order:2;width:100%;margin:0 0 12px;padding:12px 14px;border:1px solid #e5edf8;border-radius:8px;background-color:#fff;background-image:none;box-shadow:0 3px 12px rgba(30,64,175,.06)}.hmy-public-category h3{display:none}.hmy-public-category>div{display:flex;flex-wrap:nowrap;gap:8px;width:100%;min-width:0;overflow-x:auto;overflow-y:hidden;padding:0 2px 4px;scrollbar-width:none;-webkit-overflow-scrolling:touch;touch-action:pan-x}.hmy-public-category>div::-webkit-scrollbar{display:none}.hmy-public-category button{display:block;flex:0 0 auto;width:auto;min-width:112px;margin:0;padding:10px 18px;border:1px solid #e5edf8;border-radius:6px;background:#f8faff;color:#536987;text-align:center;line-height:1.35;white-space:nowrap;overflow:hidden}.hmy-public-category button span{display:block;white-space:nowrap}.hmy-public-category button small{display:none}.hmy-public-category button.on,.hmy-public-category button:hover{border-color:#287df4;background:#edf5ff;color:#287df4}.hmy-public-category button.on small,.hmy-public-category button:hover small{color:#287df4}.hmy-public-list{order:4;width:100%;min-width:0;overflow:hidden}.hmy-public-detail{order:5;width:100%;min-width:0;overflow:hidden}}@media(max-width:767px){.hmy-public{padding:1px}.hmy-public-head{min-height:226px}.hmy-public-hero{padding:42px 18px 30px}.hmy-public-title{font-size:36px}.hmy-public-sub{font-size:13px;margin-top:10px}.hmy-public-hero-badge{margin-left:8px;font-size:11px;padding:6px 10px}.hmy-public-carousel{margin:0 16px 14px}.hmy-public-carousel-card{gap:12px;padding:10px 12px}.hmy-public-carousel-cover{width:78px;height:52px;flex-basis:78px}.hmy-public-carousel-info h3{font-size:14px}.hmy-public-carousel-info p{font-size:12px}.hmy-public-periods{min-width:0}.hmy-public-periods{gap:8px}.hmy-public-period{padding:9px 14px;font-size:12px}.hmy-public-category{margin-bottom:12px;padding:10px 12px;background-color:transparent}.hmy-public-category>div{gap:6px}.hmy-public-category button{padding:9px 8px;font-size:13px}.hmy-public-list{padding:8px 12px}.hmy-public-detail{padding:24px 18px}.hmy-public-cover{float:none;width:100%;height:auto;margin:0 0 10px}}
.hmy-public-head{background-image:var(--hmy-front-pc-bg);background-size:cover;background-position:center}.hmy-public-category{background-image:var(--hmy-front-category-pc-bg);background-size:cover;background-position:center}.hmy-public-list{background-image:var(--hmy-front-content-pc-bg);background-size:cover;background-position:center}.hmy-public-title{font-family:var(--hmy-front-font);font-size:var(--hmy-front-pc-title-size);font-weight:var(--hmy-front-title-weight);color:var(--hmy-front-title-color)}.hmy-public-brand{display:inline-block;margin-left:14px;font-size:.42em;font-weight:600;vertical-align:middle;color:var(--hmy-front-body-color)}.hmy-public-sub{font-family:var(--hmy-front-font);font-size:var(--hmy-front-pc-body-size);color:var(--hmy-front-body-color)}.hmy-public-category h3{font-size:var(--hmy-front-category-pc-title-size)}.hmy-public-category button{font-size:var(--hmy-front-category-pc-body-size)}.hmy-public-hero-badge{color:var(--hmy-front-emphasis-color);background:var(--hmy-front-emphasis-bg)}
</style>
<style>:root{--hmy-front-content-pc-bg:<?php echo $hmyFrontContentPcBackgroundUrl !== '' ? 'url("'.$hmyFrontContentPcBackgroundUrl.'")' : 'none'; ?>;--hmy-front-content-mobile-bg:<?php echo $hmyFrontContentMobileBackgroundUrl !== '' ? 'url("'.$hmyFrontContentMobileBackgroundUrl.'")' : 'none'; ?>;--hmy-front-pc-bg:<?php echo $hmyFrontPcBackgroundUrl !== '' ? 'url("'.preg_replace('/["\r\n]/','',$hmyFrontPcBackgroundUrl).'")' : 'none'; ?>;--hmy-front-mobile-bg:<?php echo $hmyFrontMobileBackgroundUrl !== '' ? 'url("'.preg_replace('/["\r\n]/','',$hmyFrontMobileBackgroundUrl).'")' : 'none'; ?>;--hmy-front-category-pc-bg:<?php echo $hmyFrontCategoryPcBackgroundUrl !== '' ? 'url("'.preg_replace('/["\r\n]/','',$hmyFrontCategoryPcBackgroundUrl).'")' : 'none'; ?>;--hmy-front-category-mobile-bg:<?php echo $hmyFrontCategoryMobileBackgroundUrl !== '' ? 'url("'.preg_replace('/["\r\n]/','',$hmyFrontCategoryMobileBackgroundUrl).'")' : 'none'; ?>;--hmy-front-font:'<?php echo hmyPublicEsc($hmyFrontFontFamily); ?>',sans-serif;--hmy-front-pc-title-size:<?php echo (int) $hmyFrontConfig['hmy_front_pc_title_size']; ?>px;--hmy-front-mobile-title-size:<?php echo (int) $hmyFrontConfig['hmy_front_mobile_title_size']; ?>px;--hmy-front-pc-body-size:<?php echo (int) $hmyFrontConfig['hmy_front_pc_body_size']; ?>px;--hmy-front-mobile-body-size:<?php echo (int) $hmyFrontConfig['hmy_front_mobile_body_size']; ?>px;--hmy-front-category-pc-title-size:<?php echo (int) $hmyFrontConfig['hmy_front_category_pc_title_size']; ?>px;--hmy-front-category-mobile-title-size:<?php echo (int) $hmyFrontConfig['hmy_front_category_mobile_title_size']; ?>px;--hmy-front-category-pc-body-size:<?php echo (int) $hmyFrontConfig['hmy_front_category_pc_body_size']; ?>px;--hmy-front-category-mobile-body-size:<?php echo (int) $hmyFrontConfig['hmy_front_category_mobile_body_size']; ?>px;--hmy-front-title-weight:<?php echo hmyPublicEsc($hmyFrontConfig['hmy_front_title_weight']); ?>;--hmy-front-title-color:<?php echo hmyPublicEsc($hmyFrontConfig['hmy_front_title_color']); ?>;--hmy-front-body-color:<?php echo hmyPublicEsc($hmyFrontConfig['hmy_front_body_color']); ?>;--hmy-front-emphasis-color:<?php echo hmyPublicEsc($hmyFrontConfig['hmy_front_emphasis_color']); ?>;--hmy-front-emphasis-bg:<?php echo hmyPublicEsc($hmyFrontConfig['hmy_front_emphasis_background']); ?>}@media(max-width:1024px){.hmy-public-head{background-image:var(--hmy-front-mobile-bg)}.hmy-public-list{background-image:var(--hmy-front-content-mobile-bg)}.hmy-public-category{background-image:none}.hmy-public-title{font-size:var(--hmy-front-mobile-title-size)}.hmy-public-sub{font-size:var(--hmy-front-mobile-body-size)}.hmy-public-category h3{font-size:var(--hmy-front-category-mobile-title-size)}.hmy-public-category button{font-size:var(--hmy-front-category-mobile-body-size)}}</style><style>@media(max-width:767px){.hmy-public{position:relative}.hmy-public-category{position:absolute;left:12px;right:12px;top:190px;z-index:2;margin:0;padding:0;border:0;background:transparent;box-shadow:none}.hmy-public-category>div{justify-content:flex-start;gap:8px}.hmy-public-category button{background:#fff;border:0;border-radius:4px;color:#334155;font-size:13px;font-weight:500;padding:10px 18px;margin:0;box-shadow:0 2px 6px rgba(15,23,42,.12);transition:background .18s ease,color .18s ease}.hmy-public-category button:hover{background:#eef5ff;color:#1d4ed8}.hmy-public-category button.on,.hmy-public-category button.on:hover{background:#287df4;color:#fff}}</style>
</head>
<body>
<div class="hmy-public">
  <header class="hmy-public-head">
    <div class="hmy-public-hero"><div class="hmy-public-title"><?php echo $hmyFrontTitle; ?><?php if ($hmyFrontBrand !== ''): ?> <span class="hmy-public-brand"><?php echo $hmyFrontBrand; ?></span><?php endif; ?> <span class="hmy-public-hero-badge" id="hmyPublicHeroBadge"><?php echo $hmyFrontEmphasis; ?></span></div><div class="hmy-public-sub"><?php echo $hmyFrontSubtitle; ?></div></div>
    <div class="hmy-public-carousel" id="hmyPublicCarousel"><button class="hmy-public-carousel-control prev" type="button" id="hmyPublicPrev">‹</button><div id="hmyPublicSlides"></div><button class="hmy-public-carousel-control next" type="button" id="hmyPublicNext">›</button><div class="hmy-public-carousel-dots" id="hmyPublicDots"></div></div>
  </header>
  <nav class="hmy-public-tabs"><button class="hmy-public-period-nav" id="hmyPublicPeriodPrev" type="button" aria-label="上一期" title="上一期">‹</button><div class="hmy-public-periods" id="hmyPublicPeriods"></div><button class="hmy-public-period-nav" id="hmyPublicPeriodNext" type="button" aria-label="下一期" title="下一期">›</button></nav>
  <div id="hmyPublicListView"><div class="hmy-public-layout"><main class="hmy-public-list" id="hmyPublicList"></main><aside class="hmy-public-category"><h3><?php echo $hmyFrontSidebarTitle; ?></h3><div id="hmyPublicCategories"></div></aside></div></div>
  <article class="hmy-public-detail" id="hmyPublicDetail"><button class="hmy-public-back" type="button" id="hmyPublicBack">返回列表</button><h1 id="hmyPublicDetailTitle"></h1><div class="hmy-public-detail-meta" id="hmyPublicDetailMeta"></div><img id="hmyPublicDetailCover" style="display:none;max-width:100%;height:auto" alt=""><div class="hmy-public-body" id="hmyPublicDetailBody"></div></article>
</div>
<script>
var HMY_PUBLIC_DATA=<?php echo $payload; ?>,HMY_PUBLIC_TYPE='article',HMY_PUBLIC_CAT=0,HMY_PUBLIC_PERIOD='',HMY_PUBLIC_SLIDE=0,HMY_PUBLIC_TIMER=null;
function hmyPublicEsc(s){var d=document.createElement('div');d.textContent=String(s||'');return d.innerHTML}
function hmyPublicPeriodTitle(s){return String(s||'').replace(/^(\d{4})年(\d+)期$/,'$1年第$2期')}
function hmyPublicRows(){return (HMY_PUBLIC_DATA[HMY_PUBLIC_TYPE+'s']||[]).filter(function(x){if(HMY_PUBLIC_CAT&&Number(x.hmy_category_id)!==HMY_PUBLIC_CAT)return false;if(HMY_PUBLIC_PERIOD&&x.hmy_publish_time){var d=new Date(Number(x.hmy_publish_time)*1000),key=d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0');return key===HMY_PUBLIC_PERIOD}return !HMY_PUBLIC_PERIOD})}
function hmyPublicRender(){var rows=hmyPublicRows(),box=document.getElementById('hmyPublicList');if(!rows.length){box.innerHTML='<div class="hmy-public-empty">暂无已发布内容</div>';return}box.innerHTML=rows.map(function(x,i){var title=hmyPublicEsc(x.hmy_title),cat=hmyPublicEsc(x.hmy_category_name||'未分类'),time=hmyPublicEsc(x.hmy_time_text||'-'),summary=hmyPublicEsc(x.hmy_description||String(x.hmy_content||'').replace(/<[^>]+>/g,'').slice(0,160));return '<div class="hmy-public-item" data-index="'+i+'">'+(x.hmy_cover?'<img class="hmy-public-cover" src="'+hmyPublicEsc(x.hmy_cover)+'" alt="">':'')+'<h2>'+title+'</h2><p>'+cat+' · '+time+'</p><p>'+summary+'</p><div style="clear:both"></div></div>'}).join('');box.querySelectorAll('.hmy-public-item').forEach(function(el){el.onclick=function(){hmyPublicOpen(Number(el.getAttribute('data-index')))}})}
function hmyPublicOpen(i){var x=hmyPublicRows()[i];if(!x)return;document.getElementById('hmyPublicListView').style.display='none';document.querySelector('.hmy-public-tabs').style.display='none';document.getElementById('hmyPublicDetail').style.display='block';document.getElementById('hmyPublicDetailTitle').textContent=x.hmy_title||'';document.getElementById('hmyPublicDetailMeta').textContent=(x.hmy_category_name||'未分类')+' · '+(x.hmy_time_text||'-');var cover=document.getElementById('hmyPublicDetailCover');cover.src=x.hmy_cover||'';cover.style.display=x.hmy_cover?'block':'none';document.getElementById('hmyPublicDetailBody').innerHTML=x.hmy_content||''}
function hmyPublicRenderCategories(){var box=document.getElementById('hmyPublicCategories'),html='';(HMY_PUBLIC_DATA.categories||[]).forEach(function(x){html+='<button data-cat="'+Number(x.hmy_id)+'"'+(Number(x.hmy_id)===HMY_PUBLIC_CAT?' class="on"':'')+'>'+hmyPublicEsc(x.hmy_name)+'</span></button>'});box.innerHTML=html;box.querySelectorAll('button').forEach(function(btn){btn.onclick=function(){box.querySelectorAll('button').forEach(function(x){x.classList.remove('on')});btn.classList.add('on');HMY_PUBLIC_CAT=Number(btn.getAttribute('data-cat'));HMY_PUBLIC_PERIOD='';document.getElementById('hmyPublicHeroBadge').textContent='最新动态';document.querySelectorAll('.hmy-public-period').forEach(function(x){x.classList.remove('on')});hmyPublicRenderPeriods();hmyPublicSelectDefaultPeriod()}})}
function hmyPublicPeriodScore(key){var match=String(key||'').match(/^(\d{4})-(\d{1,2})$/);return match?Number(match[1])*12+Number(match[2]):null}
function hmyPublicRenderPeriods(){var box=document.getElementById('hmyPublicPeriods'),periods=[];(HMY_PUBLIC_DATA.categories||[]).forEach(function(x){(x.hmy_periods||[]).forEach(function(p){if(HMY_PUBLIC_CAT&&Number(x.hmy_id)!==HMY_PUBLIC_CAT)return;var score=hmyPublicPeriodScore(p.key);if(score!==null)periods.push({cat:Number(x.hmy_id),key:String(p.key),text:String(p.text||''),score:score})})});periods.sort(function(a,b){return b.score-a.score||a.cat-b.cat||a.key.localeCompare(b.key)});box.innerHTML=periods.map(function(p){return '<button class="hmy-public-period" data-cat="'+p.cat+'" data-period="'+hmyPublicEsc(p.key)+'">'+hmyPublicEsc(p.text)+'</button>'}).join('');box.querySelectorAll('.hmy-public-period').forEach(function(btn){btn.onclick=function(){HMY_PUBLIC_TYPE='article';HMY_PUBLIC_CAT=Number(btn.getAttribute('data-cat'));HMY_PUBLIC_PERIOD=btn.getAttribute('data-period')||'';document.getElementById('hmyPublicHeroBadge').textContent=hmyPublicPeriodTitle(btn.textContent);box.querySelectorAll('.hmy-public-period').forEach(function(x){x.classList.remove('on')});btn.classList.add('on');hmyPublicRenderCategories();hmyPublicRender()}})}
function hmyPublicSelectDefaultPeriod(){var buttons=Array.prototype.slice.call(document.querySelectorAll('.hmy-public-period')),now=new Date(),currentScore=now.getFullYear()*12+now.getMonth()+1,candidates=buttons.map(function(btn){return {button:btn,score:hmyPublicPeriodScore(btn.getAttribute('data-period'))}}).filter(function(item){return item.score!==null&&item.score<=currentScore}).sort(function(a,b){return b.score-a.score});if(candidates.length){candidates[0].button.click();return true}HMY_PUBLIC_PERIOD='';buttons.forEach(function(btn){btn.classList.remove('on')});document.getElementById('hmyPublicHeroBadge').textContent='最新动态';hmyPublicRenderCategories();hmyPublicRender();return false}
function hmyPublicPeriodMove(step){var buttons=document.querySelectorAll('.hmy-public-period'),current=-1;if(!buttons.length)return;buttons.forEach(function(btn,i){if(btn.classList.contains('on'))current=i});if(current<0)current=0;var next=(current+step+buttons.length)%buttons.length;buttons[next].click();buttons[next].scrollIntoView({behavior:'smooth',block:'nearest',inline:'center'})}
function hmyPublicRenderCarousel(){var rows=HMY_PUBLIC_DATA.activities||[],slides=document.getElementById('hmyPublicSlides'),dots=document.getElementById('hmyPublicDots');if(!rows.length){document.getElementById('hmyPublicCarousel').style.display='none';return}slides.innerHTML=rows.slice(0,8).map(function(x,i){return '<div class="hmy-public-carousel-card'+(i===0?' on':'')+'" data-slide="'+i+'">'+(x.hmy_cover?'<img class="hmy-public-carousel-cover" src="'+hmyPublicEsc(x.hmy_cover)+'" alt="">':'')+'<div class="hmy-public-carousel-info"><h3>'+hmyPublicEsc(x.hmy_title)+'</h3><p>'+hmyPublicEsc(x.hmy_category_name||'产品动态')+' · '+hmyPublicEsc(x.hmy_time_text||'-')+'</p></div></div>'}).join('');dots.innerHTML=rows.slice(0,8).map(function(x,i){return '<button class="hmy-public-carousel-dot'+(i===0?' on':'')+'" data-slide="'+i+'" type="button"></button>'}).join('');dots.querySelectorAll('button').forEach(function(btn){btn.onclick=function(){hmyPublicSlide(Number(btn.getAttribute('data-slide')))}})}
function hmyPublicSlide(i){var count=Math.min(8,(HMY_PUBLIC_DATA.activities||[]).length);if(!count)return;HMY_PUBLIC_SLIDE=(i+count)%count;document.querySelectorAll('.hmy-public-carousel-card').forEach(function(x,n){x.classList.toggle('on',n===HMY_PUBLIC_SLIDE)});document.querySelectorAll('.hmy-public-carousel-dot').forEach(function(x,n){x.classList.toggle('on',n===HMY_PUBLIC_SLIDE)});}
document.getElementById('hmyPublicPeriodPrev').onclick=function(){hmyPublicPeriodMove(-1)};document.getElementById('hmyPublicPeriodNext').onclick=function(){hmyPublicPeriodMove(1)};document.getElementById('hmyPublicPrev').onclick=function(){hmyPublicSlide(HMY_PUBLIC_SLIDE-1)};document.getElementById('hmyPublicNext').onclick=function(){hmyPublicSlide(HMY_PUBLIC_SLIDE+1)};document.querySelectorAll('.hmy-public-tab').forEach(function(tab){tab.onclick=function(){document.querySelectorAll('.hmy-public-tab').forEach(function(x){x.classList.remove('on')});tab.classList.add('on');HMY_PUBLIC_TYPE=tab.getAttribute('data-type');HMY_PUBLIC_CAT=0;hmyPublicRenderPeriods();hmyPublicRenderCategories();hmyPublicRender()}});document.getElementById('hmyPublicBack').onclick=function(){var hmyDetail=document.getElementById('hmyPublicDetail'),hmyListView=document.getElementById('hmyPublicListView'),hmyTabs=document.querySelector('.hmy-public-tabs');if(!hmyDetail||!hmyListView||!hmyTabs)return;hmyDetail.style.display='none';hmyListView.style.removeProperty('display');hmyTabs.style.removeProperty('display');hmyDetail.scrollTop=0;hmyListView.scrollTop=0};if(!HMY_PUBLIC_CAT&&HMY_PUBLIC_DATA.categories&&HMY_PUBLIC_DATA.categories.length)HMY_PUBLIC_CAT=Number(HMY_PUBLIC_DATA.categories[0].hmy_id);hmyPublicRenderCarousel();hmyPublicRenderPeriods();hmyPublicSelectDefaultPeriod();window.addEventListener('pageshow',function(){hmyPublicRenderPeriods();hmyPublicSelectDefaultPeriod()});hmyPublicTimer=setInterval(function(){hmyPublicSlide(HMY_PUBLIC_SLIDE+1)},5000);document.getElementById('hmyPublicCarousel').addEventListener('mouseenter',function(){clearInterval(hmyPublicTimer)});document.getElementById('hmyPublicCarousel').addEventListener('mouseleave',function(){hmyPublicTimer=setInterval(function(){hmyPublicSlide(HMY_PUBLIC_SLIDE+1)},5000)});
</script>
</body>
</html>
