<?php

namespace HaoZiTeam\AIPost\Service\Settings\Traits;

defined('ABSPATH') || exit;

trait TraitRunLogPanel
{
    // 渲染：运行日志面板（原 Setting.php 匿名回调迁移）
    public function render_run_log_panel(): void
    {
        // 工具栏 + 今日概况
        echo '<div class="ai-post-toolbar">';
        echo '<div class="ai-post-auto-refresh">';
        echo '<label for="ai-post-auto-refresh-toggle" style="margin-right:8px;display:flex;align-items:center;">';
        echo '<input type="checkbox" id="ai-post-auto-refresh-toggle" /> 自动刷新';
        echo '<select id="ai-post-refresh-interval" style="margin-left:8px;width:90px;">'
            . '<option value="3000">3秒</option>'
            . '<option value="5000">5秒</option>'
            . '<option value="10000">10秒</option>'
            . '<option value="30000">30秒</option>'
            . '</select>';
        echo '<span id="ai-post-refresh-indicator" style="margin-left:10px;display:none;align-items:center;">'
            . '<span class="spinner is-active" style="float:none;margin:0 5px 0 0;"></span>'
            . '<span class="refresh-status">正在刷新...</span>'
            . '<span class="refresh-countdown" style="margin-left:5px;color:#888;"></span>'
            . '</span>';
        echo '</label>';
        echo '</div>';

        echo '<div class="ai-post-filters">';
        echo '<select id="ai-post-status-filter">'
            . '<option value="">所有状态</option>'
            . '<option value="publish">已发布</option>'
            . '<option value="draft">草稿</option>'
            . '<option value="trash">回收站</option>'
            . '</select>';
        echo '<input type="text" id="ai-post-search-filter" placeholder="搜索关键词或标题...">';
        echo '<button type="button" id="ai-post-apply-filters" class="button">应用筛选</button>';
        echo '</div>';
        echo '</div>';

        echo '<div id="ai-post-today-stats" style="margin:10px 0;padding:10px;border-radius:6px;background:#fff;border:1px solid #e5e7eb;color:#111;display:flex;align-items:center;gap:12px;flex-wrap:wrap;">';
        echo '<strong>今日统计概况：</strong>';
        echo '<span id="ai-post-today-stats-text">--</span>';
        echo '<button type="button" class="button" id="ai-post-refresh-today-stats">刷新统计</button>';
        echo '</div>';

        $paged = isset($_GET['ai_post_log_page']) ? max(1, intval($_GET['ai_post_log_page'])) : 1; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $per_page = 20;
        echo '<div class="ai-post-log-table-wrap">' . $this->render_runlog_table($paged, $per_page) . '</div>';

        echo '<div class="ai-post-bottom-actions">';
        echo '<div class="ai-post-retention-days">';
        echo '<label for="log_retention_days">日志保留天数：</label>';
        echo '<input type="number" id="log_retention_days" min="0" max="365" value="' . esc_attr(get_option($this->prefix . '_log_retention_days', 30)) . '" />';
        echo '<span class="description">（0表示不自动清理）</span>';
        echo '<button type="button" id="ai-post-save-retention" class="button">保存</button>';
        echo '</div>';
        echo '<div class="ai-post-operations">';
        echo '<button type="button" class="button button-danger" id="ai-post-clear-logs">清空日志</button>';
        echo '<button type="button" class="button button-primary" id="ai-post-fix-table">修复数据库表结构</button>';
        echo '</div>';
        echo '</div>';

        echo '<script>jQuery(document).ready(function($){
            function refreshTodayStats(){
                var $txt = $("#ai-post-today-stats-text");
                $txt.text("统计中...");
                $.post(ajaxurl, {action: "ai_post_debug_log_stats", _ajax_nonce: ' . json_encode(wp_create_nonce('ai_post_debug_log')) . '}, function(res){
                    if(res && res.success){
                        var d = res.data || {};
                        $txt.text("今日生成 " + (d.generated || 0) + " 篇，成功发布 " + (d.published || 0) + " 篇，草稿 " + (d.draft || 0) + " 篇");
                    } else {
                        $txt.text((res && res.data && res.data.message) ? res.data.message : "统计失败");
                    }
                }).fail(function(){
                    $("#ai-post-today-stats-text").text("请求失败");
                });
            }
            refreshTodayStats();
            $("#ai-post-refresh-today-stats").on("click", function(){ refreshTodayStats(); });

            var autoRefreshEnabled = false;
            var refreshInterval = null;
            var refreshIntervalTime = parseInt($("#ai-post-refresh-interval").val()) || 3000;
            var isRefreshing = false;

            $("#ai-post-refresh-interval").on("change", function(){
                refreshIntervalTime = parseInt($(this).val()) || 3000;
                if(autoRefreshEnabled){ stopAutoRefresh(); startAutoRefresh(); startCountdown(); }
            });

            $("#ai-post-auto-refresh-toggle").on("change", function(){
                autoRefreshEnabled = $(this).is(":checked");
                if(autoRefreshEnabled){
                    startAutoRefresh();
                    $("#ai-post-refresh-indicator").css("display","inline-flex");
                    $("#ai-post-apply-filters").prop("disabled", true).css("opacity", 0.6);
                    startCountdown();
                } else {
                    stopAutoRefresh();
                    $("#ai-post-refresh-indicator").hide();
                    $("#ai-post-apply-filters").prop("disabled", false).css("opacity", 1);
                    $(".refresh-countdown").text("");
                }
            });

            var countdownTimer;
            function startCountdown(){
                if(countdownTimer) clearInterval(countdownTimer);
                var countdown = refreshIntervalTime / 1000;
                updateCountdown(countdown);
                countdownTimer = setInterval(function(){
                    countdown--; if(countdown <= 0){ clearInterval(countdownTimer); return; }
                    updateCountdown(countdown);
                }, 1000);
            }
            function updateCountdown(seconds){ $(".refresh-countdown").text("(" + seconds + "s)"); }

            function startAutoRefresh(){
                if(refreshInterval) clearInterval(refreshInterval);
                refreshInterval = setInterval(function(){ if(!isRefreshing){ refreshLogs(); startCountdown(); } }, refreshIntervalTime);
            }
            function stopAutoRefresh(){ if(refreshInterval){ clearInterval(refreshInterval); refreshInterval = null; } }

            function refreshLogs(){
                isRefreshing = true; $(".refresh-status").text("正在刷新...");
                $.ajax({
                    url: ajaxurl, type: "POST",
                    data: { action: "ai_post_get_runlog_table", page_num: $(".ai-post-page-link.current").data("page") || 1, status: $("#ai-post-status-filter").val(), search: $("#ai-post-search-filter").val() },
                    success: function(res){
                        if(res.success){
                            var $oldTable = $(".ai-post-log-table-wrap table"); var oldLogCount = $oldTable.find("tbody tr").length;
                            $(".ai-post-log-table-wrap").html(res.data.html);
                            var $newTable = $(".ai-post-log-table-wrap table"); var newLogCount = $newTable.find("tbody tr").length;
                            if(newLogCount > oldLogCount && oldLogCount > 0){
                                $newTable.find("tbody tr:lt(" + (newLogCount - oldLogCount) + ")").addClass("new-log-highlight");
                                $(".refresh-status").text("发现" + (newLogCount - oldLogCount) + "条新日志！");
                                setTimeout(function(){ $newTable.find("tr.new-log-highlight").removeClass("new-log-highlight"); }, 3000);
                            } else {
                                $(".refresh-status").text("已更新"); setTimeout(function(){ if(autoRefreshEnabled){ $(".refresh-status").text("等待下次刷新"); } }, 1000);
                            }
                        } else { $(".refresh-status").text("刷新失败"); }
                    },
                    error: function(){ $(".refresh-status").text("刷新失败"); },
                    complete: function(){ isRefreshing = false; }
                });
            }

            $(document).on("click", ".ai-post-page-link", function(e){ e.preventDefault(); var $link = $(this); if($link.hasClass("current")) return; var pageNum = $link.data("page");
                $.ajax({ url: ajaxurl, type: "POST", data: { action: "ai_post_get_runlog_table", page_num: pageNum, status: $("#ai-post-status-filter").val(), search: $("#ai-post-search-filter").val() }, beforeSend: function(){ $(".ai-post-log-table-wrap").css("opacity", 0.5); }, success: function(res){ if(res.success){ $(".ai-post-log-table-wrap").html(res.data.html); } else { alert(res.data.message || "加载失败"); } }, complete: function(){ $(".ai-post-log-table-wrap").css("opacity", 1); } });
            });

            $("#ai-post-save-retention").on("click", function(){ var days = $("#log_retention_days").val(); var btn = $(this); btn.prop("disabled", true).text("保存中...");
                $.ajax({ url: ajaxurl, type: "POST", data: { action: "ai_post_save_retention_days", days: days }, success: function(res){ if(res.success){ btn.text("已保存"); setTimeout(function(){ btn.prop("disabled", false).text("保存"); }, 1000); } else { btn.prop("disabled", false).text("保存"); } }, error: function(){ btn.prop("disabled", false).text("保存"); } });
            });

            $("#ai-post-clear-logs").on("click", function(){ if(confirm("确定要清空所有日志吗？此操作不可恢复！")){ $.post(ajaxurl, { action: "ai_post_clear_run_logs" }, function(){ location.reload(); }); } });

            $("#ai-post-fix-table").on("click", function(){ var btn = $(this); btn.prop("disabled", true).text("修复中...");
                $.ajax({ url: ajaxurl, type: "POST", data: { action: "ai_post_fix_runlog_table" }, success: function(res){ if(res.success){ alert("表结构修复成功，页面将刷新以应用更改。"); location.reload(); } else { alert(res.data && res.data.message ? res.data.message : "修复失败"); btn.prop("disabled", false).text("修复数据库表结构"); } }, error: function(){ alert("修复请求失败"); btn.prop("disabled", false).text("修复数据库表结构"); } });
            });

            $("#ai-post-apply-filters").on("click", function(){
                $.ajax({ url: ajaxurl, type: "POST", data: { action: "ai_post_get_runlog_table", page_num: 1, status: $("#ai-post-status-filter").val(), search: $("#ai-post-search-filter").val() }, beforeSend: function(){ $(".ai-post-log-table-wrap").css("opacity", 0.5); }, success: function(res){ if(res.success){ $(".ai-post-log-table-wrap").html(res.data.html); } else { alert(res.data.message || "加载失败"); } }, complete: function(){ $(".ai-post-log-table-wrap").css("opacity", 1); } });
            });
        });</script>';

        echo '<style>
        .ai-post-toolbar{display:flex;justify-content:space-between;margin-bottom:15px;background:#fff;padding:10px;border:1px solid #ddd;border-radius:4px;}
        .ai-post-auto-refresh{display:flex;align-items:center;margin-right:15px;}
        .ai-post-filters{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-left:auto;}
        .ai-post-filters select,.ai-post-filters input{padding:5px;}
        .ai-post-filters select{-webkit-appearance:none;appearance:none;padding-right:32px;min-width:96px;}
        .ai-post-bottom-actions{display:flex;justify-content:space-between;align-items:center;margin-top:15px;gap:12px;}
        .new-log-highlight{animation:newLogFlash 0.5s ease-in-out 3; background:#fff7ed;}
        @keyframes newLogFlash{0%{background:#fff7ed;}50%{background:#ffd7ba;}100%{background:#fff7ed;}}
        </style>';
    }

    // AJAX：保存日志保留天数（迁移自 Setting）
    public function handle_save_retention_days(): void
    {
        if (!\current_user_can('manage_options')) {
            \wp_send_json_error();
            return;
        }
        $days = isset($_POST['days']) ? intval($_POST['days']) : 30;
        $days = max(0, min(365, $days));
        \update_option($this->prefix . '_log_retention_days', $days);
        \wp_send_json_success();
    }

    // AJAX：获取运行日志表格（迁移自 Setting）
    public function ajax_get_runlog_table(): void
    {
        if (!\current_user_can('manage_options')) {
            \wp_send_json_error(['message' => '权限不足']);
        }

        $paged = isset($_POST['page_num']) ? max(1, intval($_POST['page_num'])) : 1;
        $per_page = 20;

        $filters = [];
        if (!empty($_POST['status'])) {
            $filters['status'] = sanitize_text_field($_POST['status']);
        }
        if (!empty($_POST['search'])) {
            $filters['search'] = sanitize_text_field($_POST['search']);
        }

        $html = $this->render_filtered_runlog_table($paged, $per_page, $filters);
        \wp_send_json_success(['html' => $html]);
    }

    // 渲染：非筛选版本（兼容旧调用）
    private function render_runlog_table(int $paged, int $per_page): string
    {
        return $this->render_filtered_runlog_table($paged, $per_page, []);
    }

    // 渲染：根据筛选条件输出运行日志表格（迁移自 Setting）
    private function render_filtered_runlog_table(int $paged, int $per_page, array $filters = []): string
    {
        $logs_data = empty($filters)
            ? \HaoZiTeam\AIPost\Service\Features\RunLog::get_logs($paged, $per_page)
            : \HaoZiTeam\AIPost\Service\Features\RunLog::get_filtered_logs($filters, $paged, $per_page);

        $logs = $logs_data['logs'] ?? [];
        $total = (int) ($logs_data['total'] ?? 0);
        $total_pages = max(1, (int) ceil($total / max(1, $per_page)));

        ob_start();
        echo '<table class="widefat fixed striped"><thead><tr><th>关键词</th><th>生成的标题</th><th>所用模型</th><th>栏目</th><th>生成日期</th><th>最终状态</th><th>操作</th></tr></thead><tbody>';
        if ($logs) {
            foreach ($logs as $log) {
                // 将内部状态值映射为中文标签，仅用于界面展示
                $status_raw = (string)($log['status'] ?? '');
                switch ($status_raw) {
                    case 'publish':
                        $status_label = '已发布';
                        break;
                    case 'draft':
                        $status_label = '草稿';
                        break;
                    case 'trash':
                        $status_label = '回收站';
                        break;
                    case 'processing':
                        $status_label = '处理中';
                        break;
                    case 'success':
                        $status_label = '成功';
                        break;
                    case 'fail':
                    case 'failed':
                        $status_label = '失败';
                        break;
                    default:
                        $status_label = $status_raw;
                        break;
                }

                echo '<tr>';
                // 关键词列：RunLog 表使用 instruction 字段存储首行关键词/指令
                echo '<td>' . esc_html($log['instruction'] ?? '') . '</td>';
                echo '<td>' . esc_html($log['title'] ?? '') . '</td>';

                $extra = (string)($log['extra'] ?? '');

                $model_used = '';
                if ($extra !== '' && preg_match('/\bmodel\s*:\s*([^,;\n\r]+)/i', $extra, $m)) {
                    $model_used = trim((string)$m[1]);
                }

                $pid = intval($log['post_id'] ?? 0);
                if ($pid <= 0) {
                    if ($extra !== '' && preg_match('/\bpost_id\s*:\s*(\d+)\b/i', $extra, $m)) {
                        $pid = (int)$m[1];
                    }
                }

                $category_label = '';
                if ($pid > 0 && function_exists('wp_get_post_terms')) {
                    $terms = wp_get_post_terms($pid, 'category');
                    if (!is_wp_error($terms) && is_array($terms) && !empty($terms)) {
                        $names = array();
                        foreach ($terms as $t) {
                            if (is_object($t) && isset($t->name)) {
                                $names[] = (string)$t->name;
                            }
                        }
                        $category_label = implode(', ', array_filter($names));
                    }
                }
                if ($category_label === '' && $extra !== '' && preg_match('/\bcategory\s*:\s*([^,;\n\r]+)/i', $extra, $m)) {
                    $category_label = trim((string)$m[1]);
                }

                echo '<td>' . esc_html($model_used) . '</td>';
                echo '<td>' . esc_html($category_label) . '</td>';
                echo '<td>' . esc_html($log['created_at'] ?? '') . '</td>';
                // 最终状态列：使用 status 字段的值映射后的中文标签
                echo '<td>' . esc_html($status_label) . '</td>';

                if ($pid > 0) {
                    $front = function_exists('get_permalink') ? get_permalink($pid) : '';
                    if (is_string($front)) { $front = trim($front); }
                    if (!is_string($front) || $front === '') {
                        $front = admin_url('post.php?post=' . $pid . '&action=edit');
                    }
                    echo '<td><a href="' . esc_url($front) . '" class="button" target="_blank" rel="noopener noreferrer">查看文章</a></td>';
                } else {
                    echo '<td><span class="button disabled" style="opacity:.5;cursor:not-allowed;">查看文章</span></td>';
                }
                echo '</tr>';
            }
        } else {
            echo '<tr><td colspan="7">暂无数据</td></tr>';
        }
        echo '</tbody></table>';

        // 分页
        if ($total_pages > 1) {
            $link_style = 'display:inline-block;min-width:32px;height:32px;line-height:32px;text-align:center;margin:0 3px;padding:0 8px;border:1px solid #dcdcde;border-radius:4px;background:#fff;color:#2271b1;text-decoration:none;font-size:13px;box-sizing:border-box;';
            $current_style = $link_style . 'background:#2271b1;color:#fff;border-color:#2271b1;font-weight:600;pointer-events:none;';
            $disabled_style = $link_style . 'color:#a7aaad;border-color:#dcdcde;background:#f6f7f7;pointer-events:none;cursor:default;';
            $dots_style = 'display:inline-block;min-width:32px;height:32px;line-height:32px;text-align:center;margin:0 2px;color:#50575e;font-size:13px;';

            echo '<div class="ai-post-pagination" style="margin-top:12px;display:flex;align-items:center;flex-wrap:wrap;gap:2px;">';

            // 总记录 & 页码提示
            echo '<span style="margin-right:12px;color:#50575e;font-size:13px;">共 ' . esc_html((string)$total) . ' 条，第 ' . esc_html((string)$paged) . ' / ' . esc_html((string)$total_pages) . ' 页</span>';

            // 上一页
            if ($paged > 1) {
                echo '<a href="#" class="ai-post-page-link" data-page="' . esc_attr((string)($paged - 1)) . '" style="' . esc_attr($link_style) . '">&laquo;</a>';
            } else {
                echo '<span style="' . esc_attr($disabled_style) . '">&laquo;</span>';
            }

            // 页码（带省略号）
            $show_dots_start = false;
            $show_dots_end = false;
            $range = 2; // 当前页前后各显示2页

            for ($i = 1; $i <= $total_pages; $i++) {
                if ($i === 1 || $i === $total_pages || ($i >= $paged - $range && $i <= $paged + $range)) {
                    if ($i === $paged) {
                        echo '<span class="ai-post-page-link current" style="' . esc_attr($current_style) . '">' . esc_html((string)$i) . '</span>';
                    } else {
                        echo '<a href="#" class="ai-post-page-link" data-page="' . esc_attr((string)$i) . '" style="' . esc_attr($link_style) . '">' . esc_html((string)$i) . '</a>';
                    }
                    $show_dots_start = true;
                    $show_dots_end = true;
                } elseif ($i < $paged && $show_dots_start) {
                    echo '<span style="' . esc_attr($dots_style) . '">&hellip;</span>';
                    $show_dots_start = false;
                } elseif ($i > $paged && $show_dots_end) {
                    echo '<span style="' . esc_attr($dots_style) . '">&hellip;</span>';
                    $show_dots_end = false;
                }
            }

            // 下一页
            if ($paged < $total_pages) {
                echo '<a href="#" class="ai-post-page-link" data-page="' . esc_attr((string)($paged + 1)) . '" style="' . esc_attr($link_style) . '">&raquo;</a>';
            } else {
                echo '<span style="' . esc_attr($disabled_style) . '">&raquo;</span>';
            }

            echo '</div>';
        }

        return ob_get_clean();
    }
}
