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

{% block title %}{% if errors %}{% translate "Error:" %} {% endif %}{{ block.super }}{% endblock %}
{% block extrahead %}{{ block.super }}
<script src="{% url 'admin:jsi18n' %}"></script>
{{ media }}
{% endblock %}

{% block extrastyle %}{{ block.super }}<link rel="stylesheet" href="{% static "admin/css/forms.css" %}">{% endblock %}

{% block coltype %}colM{% endblock %}

{% block bodyclass %}{{ block.super }} app-{{ opts.app_label }} model-{{ opts.model_name }} change-form{% endblock %}

{% if not is_popup %}
{% block breadcrumbs %}
<div class="breadcrumbs">
<a href="{% url 'admin:index' %}"><i class="bi bi-house"></i> {% translate 'Home' %}</a>
&rsaquo; <a href="{% url 'admin:app_list' app_label=opts.app_label %}">{{ opts.app_config.verbose_name }}</a>
&rsaquo; {% if has_view_permission %}<a href="{% url opts|admin_urlname:'changelist' %}">{{ opts.verbose_name_plural|capfirst }}</a>{% else %}{{ opts.verbose_name_plural|capfirst }}{% endif %}
&rsaquo; {% if add %}{% blocktranslate with name=opts.verbose_name %}Add {{ name }}{% endblocktranslate %}{% else %}{{ original|truncatewords:"18" }}{% endif %}
</div>
{% endblock %}
{% endif %}

{% block object-tools %}
{% if change and not is_popup %}
  <ul class="object-tools">
    {% block object-tools-items %}
      {% change_form_object_tools %}
    {% endblock %}
  </ul>
{% endif %}
{% endblock %}

{% block body_main %}
<div id="content-main">
<form {% if has_file_field %}enctype="multipart/form-data" {% endif %}{% if form_url %}action="{{ form_url }}" {% endif %}method="post" id="{{ opts.model_name }}_form" novalidate>{% csrf_token %}{% block form_top %}{% endblock %}
<div>
{% if is_popup %}<input type="hidden" name="{{ is_popup_var }}" value="1">{% endif %}
{% if to_field %}<input type="hidden" name="{{ to_field_var }}" value="{{ to_field }}">{% endif %}
{% if save_on_top %}{% block submit_buttons_top %}{% submit_row %}{% endblock %}{% endif %}
{% if errors %}
    <p class="errornote">
    {% blocktranslate count counter=errors|length %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktranslate %}
    </p>
    {{ adminform.form.non_field_errors }}
{% endif %}

{% block field_sets %}
{% for fieldset in adminform %}
  {% include "admin/includes/fieldset.html" with heading_level=2 prefix="fieldset" id_prefix=0 id_suffix=forloop.counter0 %}
{% endfor %}
{% endblock %}

{% block after_field_sets %}{% endblock %}

{% block inline_field_sets %}
{% for inline_admin_formset in inline_admin_formsets %}   
    {% include inline_admin_formset.opts.template %}
{% endfor %}
{% endblock %}

{% block after_related_objects %}{% endblock %}

{% block submit_buttons_bottom %}{% submit_row %}{% endblock %}

{% block admin_change_form_document_ready %}

<style>
  .collapse:not(.show) {
      display: block;
  }
</style>
    <script id="django-admin-form-add-constants"
            src="{% static 'admin/js/change_form.js' %}"
            {% if adminform and add %}
                data-model-name="{{ opts.model_name }}"
            {% endif %}
            async>
    </script>
{% endblock %}

{# JavaScript for prepopulated fields #}
{% prepopulated_fields_js %}

</div>
</form></div>

<script>
  html=`<div id="draft-list" class="list-group list-group-flush small"></div>`
  django.jQuery('#id_content_script-word-count').after(html);
  // 获取当前时间并格式化
function getFormattedTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份补零
  const day = String(now.getDate()).padStart(2, '0');        // 日期补零
  const hours = String(now.getHours()).padStart(2, '0');     // 小时补零
  const minutes = String(now.getMinutes()).padStart(2, '0'); // 分钟补零
  
  return `草稿于${year}${month}${day} ${hours}:${minutes}已保存`;
}
  
  (function($) {
    
    // 获取 CSRF 令牌
    function getCookie(name) {
      let cookieValue = null;
      if (document.cookie && document.cookie !== '') {
          const cookies = document.cookie.split(';');
          for (let i = 0; i < cookies.length; i++) {
              const cookie = cookies[i].trim();
              if (cookie.substring(0, name.length + 1) === (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      return cookieValue;
  }
  const csrftoken = getCookie('csrftoken');

  // 配置 AJAX 全局头部
  $.ajaxSetup({
      beforeSend: function(xhr, settings) {
          if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
              xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
      }
  });
  $(document).ready(function() {
    // 基础配置
    const MODEL = '{{ opts.model_name }}';
    const OBJ_ID = '{{ original.pk|default:"new" }}';
    const USER_ID = '{{ request.user.id }}';
    const firstEditorKey = Object.keys(editors).find(k => k === 'id_content') || Object.keys(editors)[0];
    const editor = editors[firstEditorKey];
    let isDirty = false;
    let saveTimer = null;
    
    // 时间格式化函数
    function formatTime(isoString) {
        const dt = new Date(isoString);
        return `${dt.getFullYear()}-${(dt.getMonth()+1).toString().padStart(2, '0')}-` +
               `${dt.getDate().toString().padStart(2, '0')} ${dt.getHours().toString().padStart(2, '0')}:` +
               `${dt.getMinutes().toString().padStart(2, '0')}`;
    }

    // 状态显示函数
    function showStatus(msg, type='info') {
        const $status = $('#draft-status');
        $status.removeClass().addClass(`draft-${type}`).text(msg).fadeIn();
        setTimeout(() => $status.fadeOut(), 3000);
    }

    // 自动保存逻辑
    function autoSave() {
        const formData = {
            model: MODEL,
            object_id: OBJ_ID,
            title: $('#id_title').val() || '未命名',
            content: editor.getData() || '',
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
        };

        $.post('{% url 'save_draft' %}', formData)
            .done(() => {
                isDirty = false;
                loadDraftList();
                // 动态检测并更新
                
                if ($('.ck-word-count #draft-status').length) {
                  showStatus(getFormattedTime(), 'info');
                } else {
                  $('.ck-word-count').append(`<div id="draft-status"></div>`);
                  showStatus(getFormattedTime(), 'info');
                }
                $('#draft-status').show()
            })
            .fail(() => showStatus('自动保存失败', 'error'));
    }
    var $list_caogao = $('#draft-list')
    // 加载草稿列表
    function loadDraftList() {
        $.get('{% url 'load_draft' %}', {
            model: MODEL,
            object_id: OBJ_ID
        }, function(data) {
          console.log('data----->',data)
            const $list = $('#draft-list').empty();
            if (!data || data.exists === false) {
              $list.append('<div class="no-draft">暂无历史草稿</div>');
              return;
          }
          // 统一数据结构处理（兼容单草稿和列表）
        const drafts = Array.isArray(data) ? data : [data];

        drafts.forEach(draft => {
              
                  const $item = $(`
                  <div class="list-group-item py-2 px-3 d-flex align-items-center">
                      <span class="text-muted me-2">${formatTime(draft.timestamp)}</span>
                      <span class="text-truncate">${draft.title}</span>
                      <button class="btn text-danger p-0 ms-2" 
                              data-obj_id="${OBJ_ID}"
                              style="line-height:1;font-size:0.875em">
                          <i class="bi bi-x fs-6"></i>
                      </button>
                  </div>
              `);
              // 存储草稿数据到元素
              $item.data('draft', draft);
              $list.append($item);
            });
        });
        // 点击草稿项事件委托
        $list_caogao.off('click', '.list-group-item').on('click', '.list-group-item', function(e) {
          // 排除删除按钮的点击
          if ($(e.target).closest('button').length > 0) return;
          
          const draft = $(this).data('draft');
          const confirmMessage = `是否将 "${draft.title}" 的草稿内容恢复到编辑区？`;
          if (confirm(confirmMessage)) {
              // 填充标题
              $('#id_title').val(draft.title);
              // 填充CKEditor内容
              if (editors && editor) {
                  editor.setData(draft.content);
              }
          }
      });
    }

    // 初始化事件处理器
    function initDraftHandlers() {
        // 自动保存定时器（30秒间隔）
        saveTimer = setInterval(() => {
          console.log('setInterval==>',11111,isDirty)
            if (isDirty) autoSave();
        }, 30000);

        // 输入内容标记为脏数据
        
        editor.model.document.on('change', () => isDirty = true);

        // 草稿删除处理
        $('#draft-list').on('click', '.delete-draft', function() {
            const objId = $(this).data('obj_id');
            if (confirm('确定永久删除这个草稿吗？')) {
                $.post('{% url 'draft_delete' %}', {
                    model: MODEL,
                    object_id: objId,
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
                }).done(() => {
                    loadDraftList();
                    showStatus('草稿已删除', 'success');
                }).fail(() => showStatus('删除失败', 'error'));
            }
        });

        // 离开页面保护
        window.onbeforeunload = function(e) {
            if (isDirty) {
                e = e || window.event;
                e.returnValue = '您有未保存的草稿内容';
                return e.returnValue;
            }
        };

        // 表单提交时清理状态
        $('form').submit(() => {
            clearInterval(saveTimer);
            window.onbeforeunload = null;
        });

        // 初始加载草稿列表
        loadDraftList();
    }

    initDraftHandlers();
});
  })(django.jQuery);
  </script>
  <style>
    .draft-info{color:var(--bs-info)}
    .draft-success{color:var(--bs-success)}
    .draft-error{color:var(--bs-danger)}
    #draft-status{margin-left:2rem;}
  </style>

{% endblock %}
