
{% extends "admin/change_list.html" %}
{% block body_main %}
{% if auth_mes %}
<div class="alert 
    {% if auth_mes.service_level == 'premium_vip' or auth_mes.service_level == 'vip_valid' %}alert-success
    {% elif auth_mes.service_level == 'basic_user' %}alert-info
    {% else %}alert-warning
    {% endif %} 
    text-center">
  <div class="alert-body">
    {# 显示友好的状态消息 #}
    <h4 class="alert-heading">
        {% if auth_mes.has_service %}
            <i class="fas fa-check-circle"></i> 服务状态正常
        {% else %}
            <i class="fas fa-exclamation-triangle"></i> 服务受限
        {% endif %}
    </h4>
    
    {# 显示具体的状态消息 #}
    <p class="mb-1"><strong>{{ auth_mes.message }}</strong></p>
    
    {# 显示详细的服务级别信息 #}
    {% comment %}<div class="mt-2">
        <span class="badge 
            {% if auth_mes.service_level == 'premium_vip' %}bg-success
            {% elif auth_mes.service_level == 'vip_valid' %}bg-primary
            {% elif auth_mes.service_level == 'basic_user' %}bg-info
            {% else %}bg-warning
            {% endif %}">
            服务级别: {{ auth_mes.service_level }}
        </span>
        
         {# 显示服务状态标志 #}
        <span class="badge {% if auth_mes.has_service %}bg-success{% else %}bg-danger{% endif %}">
            {% if auth_mes.has_service %}服务正常{% else %}服务受限{% endif %}
        </span> 
    </div>{% endcomment %}
  </div>
</div>
{% endif %}
<div class="alert alert-info text-center">
  <div class="alert-body ">
    <p>插件的初次使用安装顺序为 <code>插件依赖-->启动-->迁移数据库</code></p>
    <div>打开或者关闭插件须<a href="/api/restart_sys?code=udGuhfeN" class="mx-2"><i>重载插件</i></a>，以达到最完美的插件性能。 </div>
  </div>
  
</div>
<ul class="messagelist"></ul>
<div class="container-fluid">
  {% for plugin in plugins %}
  <div class="card mb-3 plugin-card" data-plugin="{{ plugin.package }}" 
       style="border-left: 5px solid {% if plugin.meta.is_active %}#28a745{% else %}#6c757d{% endif %}">
    <div class="card-header {% if plugin.meta.is_active %}bg-success-light{% else %}bg-light{% endif %}">
      <div class="d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center">
          {% if plugin.has_image %}
            <img src="{{ plugin.package }}/plugin.jpg" class="rounded me-3" width="40" height="40">
          {% else %}
            <i class="bi bi-plug me-3 text-secondary"></i>
          {% endif %}
          <div>
            <h3 class="mb-0">{{ plugin.meta.name }}</h3>
            <small class="text-muted">
              版本: {{ plugin.meta.version }} | 作者: {{ plugin.meta.author }}
            </small>
          </div>
        </div>
        {% if plugin.meta.dependency_status == 'pending' %}
            <button class="install-deps btn btn-info" 
                    data-package="{{ plugin.package  }}"
                    data-url="{% url 'admin:plugin_install_deps' plugin.package  %}">
                <i class="fa fa-download"></i> 安装依赖
            </button>  
            {% else %}
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" 
              data-package="{{ plugin.package }}"
              {% if plugin.meta.is_active %}checked{% endif %}>
       
          </div>
            {% endif %}
        {% if plugin.meta.requires_db and plugin.meta.migration_status == 'pending' and plugin.meta.dependency_status == 'installed' %}
            <button class="btn btn-sm btn-warning migrate-plugin" 
                    data-package="{{ plugin.package }}">迁移数据库</button>
          {% endif %}
      </div>
    </div>
    <div class="card-body">
      <div class="mb-3">
        <small class="text-muted d-block">DjacoreCMS版本: {{ plugin.meta.djacore_version }}</small>
      </div>
      <div class="description-container" style="max-height: 100px; overflow: hidden;">
        {% if plugin.meta.dependency_status == 'pending' %}
          <div class="alert alert-danger">
            该插件需要安装依赖，请先安装依赖再启动插件、迁移数据库
          </div>
        {% endif %}
        
        {{ plugin.meta.description|safe }}
      </div>
      <!-- Button trigger modal -->
      <button class="btn btn-sm btn-link mt-2 toggle-description" 
              data-bs-toggle="modal" 
              data-bs-target="#pluginDescriptionModal"
              data-description='{{ plugin.meta.description|escapejs|safe }}'>
        显示全部介绍
      </button>
    </div>
  </div>
  {% endfor %}
</div>
<!-- 添加模态框 -->
<div class="modal fade" id="pluginDescriptionModal" tabindex="-1" aria-labelledby="pluginDescriptionModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="pluginDescriptionModalLabel">插件详情</h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="pluginDescriptionContent">
        <!-- 内容将通过JavaScript动态填充 -->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>
<style>
.bg-success-light {
  background-color: rgba(40, 167, 69, 0.1);
}
.plugin-card {
  transition: all 0.3s ease;
}
.description-container {
  transition: max-height 0.3s ease;
  position: relative;
}
.description-container.expanded {
  max-height: none !important;
}
.description-container:not(.expanded)::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 20px;
  background: linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,1));
}
.toast {
    transition: all 0.3s ease;
    opacity: 0;
  }
  .toast.show {
    opacity: 1;
  }
  .bg-success {
    background-color: #28a745 !important;
  }
  .bg-error {
    background-color: #dc3545 !important;
  }
  .bg-info {
    background-color: #17a2b8 !important;
  }
  
</style>
<script>
  function decodeEscapedHTML(str) {
    const div = document.createElement('div');
    div.innerHTML = str;
    return div.textContent || div.innerText;
  }
  document.addEventListener('DOMContentLoaded', function() {
    var descriptionModal = document.getElementById('pluginDescriptionModal');
    if (descriptionModal) {
      descriptionModal.addEventListener('show.bs.modal', function(event) {
        var button = event.relatedTarget;
        var description = button.getAttribute('data-description');
        var modalBody = descriptionModal.querySelector('.modal-body');
        
        modalBody.innerHTML = JSON.parse(`"${description}"`);
      });
    }
  });
  document.addEventListener('DOMContentLoaded', function() {
    // 获取所有插件卡片
    const pluginCards = document.querySelectorAll('.plugin-card');
    
    pluginCards.forEach(card => {
        // 获取当前卡片中的复选框和迁移按钮
        const checkbox = card.querySelector('.form-check-input');
        const migrateBtn = card.querySelector('.migrate-plugin');
        // 如果存在迁移按钮
        if (migrateBtn) {
            // 初始状态检查
            updateButtonState(checkbox, migrateBtn);
            
            // 添加复选框变化监听
            checkbox.addEventListener('change', function() {
                updateButtonState(this, migrateBtn);
            });
        }
    });
    
    function updateButtonState(checkbox, button) {
        if (!checkbox.checked) {
            button.disabled = true;
            button.classList.add('disabled');
        } else {
            button.disabled = false;
            button.classList.remove('disabled');
        }
    }
});
  </script>
<script>
  
/**
 * 显示插件详情模态框
 * @param {string} title - 模态框标题
 * @param {string} htmlContent - 模态框主体HTML内容
 * @param {boolean} [showFooter=true] - 是否显示底部关闭按钮
 */
function showPluginDescriptionModal(title, htmlContent, showFooter = true) {
  // 获取模态框元素
  const modal = new bootstrap.Modal(document.getElementById('pluginDescriptionModal'));
  const titleElement = document.getElementById('pluginDescriptionModalLabel');
  const bodyElement = document.getElementById('pluginDescriptionContent');
  const footerElement = document.querySelector('#pluginDescriptionModal .modal-footer');
  
  // 设置标题和内容
  titleElement.textContent = title;
  bodyElement.innerHTML = htmlContent;
  
  // 控制底部按钮显示
  footerElement.style.display = showFooter ? 'flex' : 'none';
  
  // 显示模态框
  modal.show();
}


// 示例调用方式
// showPluginDescriptionModal('示例标题', '<p>这里是HTML内容</p>');

    document.querySelectorAll('.form-check-input').forEach(checkbox => {
      checkbox.addEventListener('change', async function() {
        const package = this.dataset.package;
        const card = this.closest('.plugin-card');
        const header = card.querySelector('.card-header');
        
        try {
          const response = await fetch(`/admin/plugin_manager/plugin/toggle/${package}/`, {
            method: 'GET',
            headers: {
              'X-Requested-With': 'XMLHttpRequest',
              'X-CSRFToken': '{{ csrf_token }}'
            }
          });
    
          const result = await response.json();
          
          if(result.status === 'success') {
            // 显示操作成功提示
            showToast(
              result.is_active ? '插件已启用' : '插件已停用',
              result.is_active ? 'success' : 'info'
            );
            let message_html;
            if(result.is_active) {
              card.style.borderLeftColor = '#28a745';
              header.classList.replace('bg-light', 'bg-success-light');
              message_html=`<li class="success">插件已启动，系统将自动重启，以确保插件正确插入。</li>`

            } else {
              card.style.borderLeftColor = '#6c757d';
              header.classList.replace('bg-success-light', 'bg-light');
              message_html=`<li class="success">插件已停用，系统将自动重启，以确保插件正确停止。</li>` 
              //location.reload(); 
            }
            // 向messagelist插入消息
            const messageList = document.querySelector('ul.messagelist');
            if(messageList) {
              messageList.insertAdjacentHTML('beforeend', message_html);
        }
          } else {
            this.checked = !this.checked;
            showToast('操作失败: ' + result.message, 'error');
          }
        } catch (error) {
          this.checked = !this.checked;
          showToast('网络请求错误: ' + error, 'error');
        }
      });
    });
    
    // 添加Toast提示函数
    function showToast(message, type) {
      const toast = document.createElement('div');
      toast.className = `toast show position-fixed bottom-0 end-0 m-3 bg-${type}`;
      toast.style.zIndex = 1100;
      toast.innerHTML = `
        <div class="toast-body text-white d-flex justify-content-between">
          ${message}
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
        </div>
      `;
      document.body.appendChild(toast);
      
      setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
      }, 3000);
      
      toast.querySelector('.btn-close').addEventListener('click', () => {
        toast.remove();
      });
    }
    
    
    document.querySelectorAll('.migrate-plugin').forEach(btn => {
      btn.addEventListener('click', async () => {
        const package = btn.dataset.package;
        showPluginDescriptionModal(
          `正在迁移数据库`,
          `<div class="text-center">
            <div class="spinner-border text-primary me-3" role="status">
              <span class="visually-hidden">加载中...</span>
            </div>
            <p>正在为插件“${package}”迁移数据库，请勿关闭页面</p>
          </div>`
        );
        
        // 禁用按钮并添加加载状态
        btn.disabled = true;
        btn.classList.add('opacity-50', 'cursor-not-allowed');
        
        try {
          const response = await fetch(`/admin/plugin_manager/plugin/migrate/${package}/`);
          
          // 检查响应状态
          if (!response.ok) {
            throw new Error(`HTTP错误，状态码: ${response.status}`);
          }
          
          const result = await response.json();
          
          if (result.status === 'success') {
            // 迁移成功
            btn.innerHTML = '<i class="fas fa-check-circle mr-2"></i>迁移完成';
            showToast('数据库迁移成功', 'success');
            setTimeout(() => location.reload(), 1500);
          } else {
            // 迁移失败
            const errorMsg = result.message || '迁移失败';
            showToast(errorMsg, 'error');
            throw new Error(errorMsg);
          }
        } catch (error) {
          // 恢复按钮状态
          btn.disabled = false;
          btn.classList.remove('opacity-50', 'cursor-not-allowed');
          
          // 错误处理
          console.error('迁移错误:', error);
          showToast(`错误: ${error.message}`, 'error');
          
          // 如果是服务器错误，显示更详细的提示
          if (error.message.includes('500')) {
            showPluginDescriptionModal(
              '服务器错误',
              `<div class="alert alert-danger">
                服务器处理请求时发生错误，请联系管理员检查服务器日志。
                <br><small>错误详情: ${error.message}</small>
              </div>`
            );
          }
        }
      });
    });
    

document.querySelectorAll('.install-deps').forEach(btn => {
  btn.addEventListener('click', async function() {
    
      const package = this.dataset.package;
      showPluginDescriptionModal(`安装插件依赖 `, `<div class="text-center"><div class="spinner-border text-primary me-3" role="status">
                <span class="visually-hidden">加载中...</span>
            </div><p>正在安装${package}插件依赖</p></div>`)
      const response = await fetch(this.dataset.url, {
          method: 'POST',
          headers: {'X-CSRFToken': '{{ csrf_token }}'}
      });
      
      const result = await response.json(); 
      console.log('result===========>',result)
      if (result.status === 'success') {
          showToast(`依赖安装成功: ${package}`, 'success');
          location.reload();
      } else {
          showToast(`安装失败: ${result.message || '未知错误'}`, 'danger');
      }
  });
});

    </script>
    
    
{% endblock %}
