<?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 '<select id="ai-post-level-filter">'
            . '<option value="">所有级别</option>'
            . '<option value="0">信息</option>'
            . '<option value="1">警告</option>'
            . '<option value="2">错误</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(), log_level: $("#ai-post-level-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(), log_level: $("#ai-post-level-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(), log_level: $("#ai-post-level-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-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 (isset($_POST['log_level']) && $_POST['log_level'] !== '') {
            $filters['log_level'] = intval($_POST['log_level']);
        }
        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>是否AI改写</th><th>日志级别</th><th>原标题</th><th>生成日期</th><th>最终状态</th><th>操作</th></tr></thead><tbody>';
        if ($logs) {
            foreach ($logs as $log) {
                $rewrite_map = [ 'length' => '超长改写', 'empty' => '空标题改写', 'duplicate' => '重复改写' ];
                $rewrite_label = !empty($log['is_rewrite']) ? ($rewrite_map[$log['is_rewrite']] ?? '是') : '否';

                $log_level = isset($log['log_level']) ? intval($log['log_level']) : 0;
                $level_name = \HaoZiTeam\AIPost\Service\Features\RunLog::get_level_name($log_level);
                $level_class = $log_level === 2 ? 'error' : ($log_level === 1 ? 'warning' : 'info');

                echo '<tr class="level-' . esc_attr($level_class) . '">';
                echo '<td>' . esc_html($log['keyword'] ?? '') . '</td>';
                echo '<td>' . esc_html($log['title'] ?? '') . '</td>';
                echo '<td>' . esc_html($rewrite_label) . '</td>';
                echo '<td>' . esc_html($level_name) . '</td>';
                echo '<td>' . esc_html($log['original_title'] ?? '') . '</td>';
                echo '<td>' . esc_html($log['created_at'] ?? '') . '</td>';
                echo '<td>' . esc_html($log['final_status'] ?? '') . '</td>';
                echo '<td><a href="' . esc_url(admin_url('post.php?post=' . intval($log['post_id'] ?? 0) . '&action=edit')) . '" class="button">查看文章</a></td>';
                echo '</tr>';
            }
        } else {
            echo '<tr><td colspan="8">暂无数据</td></tr>';
        }
        echo '</tbody></table>';

        // 分页
        echo '<div class="ai-post-pagination" style="margin-top:10px;">';
        for ($i = 1; $i <= $total_pages; $i++) {
            $cls = $i === $paged ? 'ai-post-page-link current' : 'ai-post-page-link';
            echo '<a href="#" class="' . esc_attr($cls) . '" data-page="' . esc_attr($i) . '">' . esc_html((string)$i) . '</a>';
        }
        echo '</div>';

        return ob_get_clean();
    }
}
