{% extends "admin/base_site.html" %}
{% load site_info %}
{% load i18n static %}

{% block extrastyle %}{{ block.super }}<link rel="stylesheet" href="{% static "admin/css/dashboard.css" %}"><script src="{% static "shared/js/echarts.min.js" %}"></script>{% endblock %}

{% block coltype %}colMS{% endblock %}

{% block bodyclass %}{{ block.super }} dashboard{% endblock %}

{% block nav-breadcrumbs %}
<div class="container-fluid  mt-1">
    <div class="row">
        <div class="col-md-3 col-lg-2">
            <div id="content-main">
                {% include "admin/app_list.html" with app_list=app_list show_changelinks=True %}
              </div>
        </div>
        <div class="col-md-7 col-lg-8">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-opacity-10 d-flex align-items-center py-2" style="background: linear-gradient(45deg, var(--dc-primary), #79aec8);color: white;">
                    <i class="bi bi-clipboard2-data-fill fs-5  me-2"></i>
                    <h6 class="mb-0 ">系统总览</h6>
                </div>
                
                <div class="card-body p-2">
                    {% get_auth_status as vip_mes %}
                    <dl class="row g-2 mb-0"> 
                        <!--运维日志-->
                        
                        <div class="col-12 mt-3">
                            <div class="bg-light rounded p-2">
                                <div class="d-flex align-items-center mb-2">
                                    <i class="bi bi-journal-text text-muted me-2"></i>
                                    <span class="fw-bold">授权信息</span>
                                    <span class="small text-secondary">（当服务器环境或授权发生变化时请及时重新认证授权，以免影响插件和应用的使用）</span>
                                </div>
                                <div class="row g-2 vip_box">
                                    
                                    <div class="alert alert-{% if vip_mes.is_valid %}success{% elif vip_mes.auth_info.username %}info{% else %}warning{% endif %}">
                                        {% if vip_mes.is_valid %}
                                        <div class="row my-3">
                                            <div class="col-md-3">
                                                <strong>用户名:</strong> {{vip_mes.auth_info.username}}
                                            </div>
                                            <div class="col-md-3">
                                                <strong>等级:</strong> {{vip_mes.auth_info.vip_level_display}}
                                            </div>
                                            <div class="col-md-3">
                                                <strong>状态:</strong> 
                                                {% if vip_mes.message == '授权有效' %}
                                                <span class="badge bg-success">
                                                    有效
                                                </span>
                                                {% else %}
                                                <span class="badge bg-secondary">
                                                    无效
                                                </span>
                                                {% endif %}
                                                
                                            </div>
                                            <div class="col-md-3">
                                                <strong>过期时间:</strong> {{vip_mes.auth_info.expires_at}}
                                            </div>
                                        </div>
                                        {% elif vip_mes.auth_info.username %}
                                        <p>您现在的授权状态为：普通。可以分别使用3个插件和自定义应用。</p>
                                        {% else %}
                                        <p>没有查询到您的授权信息，您将不可以使用插件和自定义应用功能。</p>
                                        
                                        {% endif %}
                                        <div>
                                            {% comment %} 如需要更正授权信息请<a href="#" class="btn btn-link djacore_login">登陆</a>后更新 {% endcomment %}
                                            <button class="btn btn-sm btn-outline-secondary mt-2" onclick="showLoginModal()">
                                                <i class="fas fa-sync me-1"></i>更新授权
                                            </button>
                                        </div>
                                        
                                    </div>
                                    
                                </div>
                            </div>
                        </div>          
                        <!-- 系统信息 -->
                        <div class="col-12">
                            <div class="bg-light rounded p-2 mb-2">
                                <div class="d-flex align-items-center mb-2">
                                    <i class="bi bi-pc-display-horizontal text-muted me-2"></i>
                                    <span class="fw-bold">系统信息</span>
                                </div>
                                <div class="row g-2">
                                    {% get_system_info as system_info %}
                                    {% for key, data in system_info.items %}
                                    <div class="col-6 col-md-4 col-lg-3">
                                        <div class="bg-white rounded p-2 border">
                                            <div class="text-muted small d-flex align-items-center">
                                                <i class="bi bi-circle-fill text-primary me-1" style="font-size: 6px"></i>
                                                {{key}}
                                            </div>
                                            <div class="fw-bold text-truncate">{{data|safe}}</div>
                                        </div>
                                    </div>
                                    {% endfor %}
                                    <div class="col-6 col-md-4 col-lg-3">
                                        <div class="bg-white rounded p-2 border">
                                            <div class="text-muted small d-flex align-items-center">
                                                <i class="bi bi-circle-fill text-primary me-1" style="font-size: 6px"></i>
                                                DjacoreCMS 版本：
                                            </div>
                                            <div class="fw-bold text-truncate">
                                                {% get_cms_version as version_info %} {{ version_info.0 }} 
                                                <a href="/admin/upgrade/upgradeprogress/" class="position-relative small">
                                                查看升级
                                                {% if version_info.1 %}
                                                <span class="bg-success border border-light p-1 position-absolute rounded-circle start-100 top-0 translate-middle">
                                                    <span class="visually-hidden">New alerts</span>
                                                </span>
                                                {% endif %}
                                                
        
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
            
                        <!-- 整站数据 -->
                        <div class="col-12">
                            <div class="bg-light rounded p-2">
                                <div class="d-flex align-items-center mb-2">
                                    <i class="bi bi-database text-muted me-2"></i>
                                    <span class="fw-bold">全局数据</span>
                                </div>
                                <div class="row g-2">
                                    {% get_content_stats as global_data %}
                                    {% for key, data in global_data.items %}
                                    <div class="col-6 col-md-4 col-lg-3">
                                        <div class="bg-white rounded p-2 border">
                                            <div class="text-muted small d-flex align-items-center">
                                                <i class="bi bi-circle-fill text-info me-1" style="font-size: 6px"></i>
                                                {{key}}总数
                                            </div>
                                            <div class="fw-bold text-truncate">{{data}}</div>
                                        </div>
                                    </div>
                                    {% endfor %}
                                </div>
                            </div>
                        </div>
                        <!--运维日志-->
                        
                        <div class="col-12 mt-3">
                            <div class="bg-light rounded p-2">
                                <div class="d-flex align-items-center mb-2">
                                    <i class="bi bi-journal-text text-muted me-2"></i>
                                    <span class="fw-bold">运维日志</span>
                                    <a class="ms-3" href="{% url 'admin:oplog_oplog_changelist' %}">more</a>
                                </div>
                                <div class="row g-2">
                                    {% admin_index_oplog_list as oplogs %}
                                    {% for item in oplogs %}
                                    <div class="col-12">
                                        <div class="bg-white rounded p-2 border d-flex justify-content-between align-items-center">
                                            <div class="d-flex align-items-center">
                                                <i class="bi bi-circle-fill text-primary me-2" style="font-size: 6px"></i>
                                                <span class="text-truncate">{{ item.create_time|date:"Y-m-d H:i" }} - {{ item.content|truncatechars:120 }}</span>
                                                
                                                {% if item.content|length > 120 %}
                                                <span data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="{{ item.content }}">
                                                    <i class="bi bi-eye ms-3"></i>
                                                </span>
                                                {% endif %}
                                            </div>
                                            
                                            <a href="{% url 'admin:oplog_oplog_change' item.pk %}" class="">
                                                <i class="bi bi-pencil-square"></i>
                                            </a>
                                        </div>
                                    </div>
                                    {% endfor %}
                                </div>
                            </div>
                        </div>

                    </dl>
                </div>
            </div>

            

            <div class="content-stats">
                {% combined_pie_charts %}
              </div>
            <div class="app-stats mt-3">
                <h2>内容发布统计</h2>
                {% recent_publish_charts %}  <!-- 可自定义显示天数 -->
            </div>
            <style>
                .app-stats {
                    padding: 20px;
                    background: #f8f9fa;
                    border-radius: 8px;
                    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                }
                .chart-container {
                    background: white;
                    padding: 20px;
                    border-radius: 8px;
                    margin-bottom: 25px;
                }
                </style>
            
            

        </div>
        <div class="col-md-2">
            <div id="">
                <div class="module" id="recent-actions-module">
                    <h2>{% translate 'Recent actions' %}</h2>
                    <h3>{% translate 'My actions' %}</h3>
                        {% load log %}
                        {% get_admin_log 10 as admin_log for_user user %}
                        {% if not admin_log %}
                        <p>{% translate 'None available' %}</p>
                        {% else %}
                        <ul class="actionlist">
                        {% for entry in admin_log %}
                        <li class="{% if entry.is_addition %}addlink{% endif %}{% if entry.is_change %}changelink{% endif %}{% if entry.is_deletion %}deletelink{% endif %}">
                            <span class="visually-hidden">{% if entry.is_addition %}{% translate 'Added:' %}{% elif entry.is_change %}{% translate 'Changed:' %}{% elif entry.is_deletion %}{% translate 'Deleted:' %}{% endif %}</span>
                            {% if entry.is_deletion or not entry.get_admin_url %}
                                {{ entry.object_repr }}
                            {% else %}
                                <a href="{{ entry.get_admin_url }}">{{ entry.object_repr }}</a>
                            {% endif %}
                            <br>
                            {% if entry.content_type %}
                                <span class="mini quiet">{% filter capfirst %}{{ entry.content_type.name }}{% endfilter %}</span>
                            {% else %}
                                <span class="mini quiet">{% translate 'Unknown content' %}</span>
                            {% endif %}
                        </li>
                        {% endfor %}
                        </ul>
                        {% endif %}
                </div>
            </div>
        </div> 
    </div>

</div>
<script>
    document.addEventListener('DOMContentLoaded', function() {
      var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
      tooltipTriggerList.map(function(tooltipTriggerEl) {
          return new bootstrap.Tooltip(tooltipTriggerEl);
      });
  });

// 模态框初始化和管理
document.addEventListener('DOMContentLoaded', function() {
    // 绑定登录按钮点击事件
    document.querySelector('.djacore_login').addEventListener('click', function(e) {
        e.preventDefault();
        showLoginModal();
    });
    
    // 初始化模态框
    const modal = new bootstrap.Modal(document.getElementById('global_commonModal'));
});

function showLoginModal() {
    // 设置模态框标题
    document.getElementById('modalHeader').textContent = '获取软件授权';
    
    // 显示加载器，隐藏主要内容
    document.getElementById('modalLoader').style.display = 'block';
    document.getElementById('modalMain').style.display = 'none';
    
    // 构建登录表单HTML
    const formHTML = `
        <form id="vipAuthForm" class="needs-validation" novalidate>
            <div class="mb-3">
                <label for="username" class="form-label">用户名</label>
                <input type="text" class="form-control" id="username" name="username" required>
                <div class="invalid-feedback">请输入用户名</div>
            </div>
            <div class="mb-3">
                <label for="password" class="form-label">密码</label>
                <input type="password" class="form-control" id="password" name="password" required>
                <div class="invalid-feedback">请输入密码</div>
            </div>
            <div class="d-grid">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-key me-2"></i>获取授权
                </button>
            </div>
            <div class="alert alert-info mt-3">使用在<a href="//djacore.com/users/login/" target="_blank" class="btn btn-link"><i>官方注册</i></a>的账号、密码可获取最新授权。</div>  
        </form>
        <div id="authResult" class="mt-3"></div>
    `;
    
    // 短暂延迟后显示表单（模拟加载）
    setTimeout(() => {
        document.getElementById('modalMain').innerHTML = formHTML;
        document.getElementById('modalLoader').style.display = 'none';
        document.getElementById('modalMain').style.display = 'block';
        
        // 绑定表单提交事件
        bindFormSubmit();
    }, 500);
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('global_commonModal'));
    modal.show();
}

function bindFormSubmit() {
    const form = document.getElementById('vipAuthForm');
    const resultDiv = document.getElementById('authResult');
    
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (!form.checkValidity()) {
            e.stopPropagation();
            form.classList.add('was-validated');
            return;
        }
        
        // 获取表单数据
        const formData = new FormData(form);
        const data = {
            username: formData.get('username'),
            password: formData.get('password')
        };
        
        // 显示加载状态
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>验证中...';
        submitBtn.disabled = true;
        
        // 发送AJAX请求
        fetch('/api/v1/client/config/sync/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            displayAuthResult(data);
        })
        .catch(error => {
            console.error('Error:', error);
            resultDiv.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    网络错误，请重试
                </div>
            `;
        })
        .finally(() => {
            // 恢复按钮状态
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        });
    });
}

function displayAuthResult(data) {
    const resultDiv = document.getElementById('authResult');
    
    if (data.code === 0) {
        // 成功情况
        const authInfo = data.data.auth_info;
        resultDiv.innerHTML = `
            <div class="alert alert-success">
                <h5><i class="fas fa-check-circle me-2"></i>${data.message}</h5>
                <hr>
                <div class="row">
                    <div class="col-md-6">
                        <strong>VIP等级:</strong> ${authInfo.vip_level_display}<br>
                        <strong>授权密钥:</strong> <code>${authInfo.auth_key}</code>
                    </div>
                    <div class="col-md-6">
                        <strong>授权时间:</strong> ${authInfo.authorized_at ? new Date(authInfo.authorized_at).toLocaleString() : 'N/A'}<br>
                        <strong>过期时间:</strong> ${authInfo.expires_at ? new Date(authInfo.expires_at).toLocaleString() : '永久'}
                    </div>
                </div>
                <div class="mt-2">
                    <strong>状态:</strong> 
                    <span class="badge ${authInfo.is_valid ? 'bg-success' : 'bg-warning'}">
                        ${authInfo.is_valid ? '有效' : '无效'}
                    </span>
                </div>
            </div>
        `;
        
        // 更新页面上的VIP信息显示
        updateVipBoxDisplay(data);
        // 在指定位置插入消息
        insertAuthMessage();
        // 3秒后自动关闭模态框
        setTimeout(() => {
            const modal = bootstrap.Modal.getInstance(document.getElementById('global_commonModal'));
            modal.hide();
        }, 3000);
        message_html=`<li class="success">授权信息已更新，系统将自动重启，以确保授权可正常使用。</li>`
        const messageList = document.querySelector('ul.messagelist');
        if(messageList) {
              messageList.insertAdjacentHTML('beforeend', message_html);
        }
        
    } else {
        // 错误情况
        let alertClass = 'alert-warning';
        if (data.code === 404) alertClass = 'alert-danger';
        if (data.code === 403) alertClass = 'alert-warning';
        
        resultDiv.innerHTML = `
            <div class="alert ${alertClass}">
                <h5><i class="fas fa-exclamation-circle me-2"></i>${data.error}</h5>
                <p class="mb-0">${data.message}</p>
            </div>
        `;
    }
}
function insertAuthMessage() {
    // 获取目标容器
    const targetContainer = document.querySelector('.col-md-7.col-lg-8');
    
    if (!targetContainer) {
        console.warn('目标容器 .col-md-7.col-lg-8 未找到');
        return;
    }
    
    // 检查是否已存在消息列表
    let messageList = targetContainer.querySelector('ul.messagelist');
    
    if (!messageList) {
        // 创建新的消息列表
        messageList = document.createElement('ul');
        messageList.className = 'messagelist';
        
        // 插入到容器顶部
        if (targetContainer.firstChild) {
            targetContainer.insertBefore(messageList, targetContainer.firstChild);
        } else {
            targetContainer.appendChild(messageList);
        }
    }
    
    // 创建成功消息
    const messageHTML = `<li class="success">授权信息已更新，系统将自动重启，以确保授权可正常使用。</li>`;
    
    // 添加消息到列表顶部
    messageList.insertAdjacentHTML('afterbegin', messageHTML);
    
    // 可选：添加自动消失效果
    setTimeout(() => {
        const successMessage = messageList.querySelector('li.success');
        if (successMessage) {
            successMessage.style.opacity = '0';
            successMessage.style.transition = 'opacity 0.5s ease';
            setTimeout(() => {
                if (successMessage.parentNode) {
                    successMessage.parentNode.removeChild(successMessage);
                }
                
                // 如果列表为空，移除整个列表
                if (messageList.children.length === 0) {
                    messageList.parentNode.removeChild(messageList);
                }
            }, 500);
        }
    }, 5000); // 5秒后开始消失
}
function updateVipBoxDisplay(data) {
    const vipBox = document.querySelector('.vip_box');
    if (data.code === 0) {
        const authInfo = data.data.auth_info;
        vipBox.innerHTML = `
            <div class="alert alert-success">
                <h5><i class="fas fa-crown me-2"></i>VIP授权信息</h5>
                <div class="row">
                    <div class="col-md-3">
                        <strong>用户名:</strong> ${authInfo.username}
                    </div>
                    <div class="col-md-3">
                        <strong>等级:</strong> ${authInfo.vip_level_display}
                    </div>
                    <div class="col-md-3">
                        <strong>状态:</strong> 
                        <span class="badge ${authInfo.is_valid ? 'bg-success' : 'bg-warning'}">
                            ${authInfo.is_valid ? '有效' : '无效'}
                        </span>
                    </div>
                    <div class="col-md-3">
                        <strong>过期时间:</strong> ${authInfo.expires_at ? new Date(authInfo.expires_at).toLocaleDateString() : '永久'}
                    </div>
                </div>
                <button class="btn btn-sm btn-outline-secondary mt-2" onclick="showLoginModal()">
                    <i class="fas fa-sync me-1"></i>更新授权
                </button>
            </div>
        `;
    }
}

// 获取CSRF token的辅助函数
function getCSRFToken() {
    return document.querySelector('[name=csrfmiddlewaretoken]').value;
}
  </script>
<!-- templates/admin/includes/secret_key_modal.html -->
<div class="modal fade" id="secretKeyModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">
          <i class="bi bi-key"></i> 重置 SECRET_KEY
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
      </div>
      <div class="modal-body">
        <div class="alert alert-danger">
          <h6><i class="bi bi-exclamation-triangle"></i> 重要警告</h6>
          <ul class="mb-0">
            <li><strong>所有用户会话将立即失效</strong></li>
            <li>需要重新登录系统</li>
            <li>系统将自动重启应用</li>
          </ul>
        </div>
        
        <div class="form-check mb-3">
          <input class="form-check-input" type="checkbox" id="confirmReset">
          <label class="form-check-label" for="confirmReset">
            我理解重置密钥的后果，确认继续
          </label>
        </div>
        
        <div id="resetResult" class="alert d-none"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-danger" id="confirmResetBtn" disabled>
          确认重置
        </button>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  const modal = document.getElementById('secretKeyModal');
  const confirmCheckbox = document.getElementById('confirmReset');
  const resetBtn = document.getElementById('confirmResetBtn');
  const resetResult = document.getElementById('resetResult');
  
  // 检查确认框
  confirmCheckbox.addEventListener('change', function() {
    resetBtn.disabled = !this.checked;
  });
  
  // 重置按钮点击事件
  resetBtn.addEventListener('click', function() {
    if (!confirmCheckbox.checked) return;
    
    // 显示加载状态
    resetBtn.disabled = true;
    resetBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> 重置中...';
    
    // 发送请求
    fetch('/api/secret-key/reset/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCookie('csrftoken')
      }
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        resetResult.className = 'alert alert-success';
        resetResult.innerHTML = `
          <h6><i class="bi bi-check-circle"></i> 重置成功</h6>
          <p>${data.message}</p>
          <p><strong>${data.warning}</strong></p>
          <p>${data.note}</p>
        `;
        
        // 5秒后自动刷新页面
        setTimeout(() => {
          location.reload();
        }, 5000);
      } else {
        resetResult.className = 'alert alert-danger';
        resetResult.innerHTML = `
          <h6><i class="bi bi-x-circle"></i> 重置失败</h6>
          <p>${data.message}</p>
        `;
        resetBtn.disabled = false;
        resetBtn.innerHTML = '确认重置';
      }
      
      resetResult.classList.remove('d-none');
    })
    .catch(error => {
      resetResult.className = 'alert alert-danger';
      resetResult.innerHTML = `
        <h6><i class="bi bi-x-circle"></i> 请求失败</h6>
        <p>${error.message}</p>
      `;
      resetResult.classList.remove('d-none');
      resetBtn.disabled = false;
      resetBtn.innerHTML = '确认重置';
    });
  });
  
  // 获取CSRF令牌
  function getCookie(name) {
    let cookieValue = null;
    if (document.cookie) {
      const cookies = document.cookie.split(';');
      for (let cookie of cookies) {
        cookie = cookie.trim();
        if (cookie.startsWith(name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }
  
  // 模态框关闭时重置
  modal.addEventListener('hidden.bs.modal', function() {
    confirmCheckbox.checked = false;
    resetBtn.disabled = true;
    resetBtn.innerHTML = '确认重置';
    resetResult.className = 'alert d-none';
    resetResult.innerHTML = '';
  });
});
</script>
{% endblock %}

{% block nav-sidebar %}
{% endblock %}

{% block body_main %}

{% endblock %}

{% block sidebar %}

{% endblock %}
{% block content_title %}{% endblock %}