# admin.py
from django.conf import settings
from django.contrib import admin
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _

from ..models.post_set import PostSet
from .mixins import SingletonAdminMixin


@admin.register(PostSet)
class PostSetAdmin(SingletonAdminMixin, admin.ModelAdmin):
    change_form_template = 'admin/core/post_set/change_form.html'

    fieldsets = (
        ('', {
            'fields': (),
            'description':
            mark_safe('''<div class="card bg-info-subtle">
                <div class="card-body">
                可以通过get方法触发URL进行将预计内容转为发布状态
                <pre class="bg-dark text-light p-3 rounded my-3"><code>url:http(s)://host/api/update_status99?code=安全码</code></pre>
                </div>''')
        }),
        ('内容来源设置', {
            'fields': ('content_type', ),
            'description': '选择内容管理方式'
        }),
        ('编辑分配设置', {
            'fields': ('editor_candidates', ),
            'description': '设置文章编辑分配规则'
        }),
        ('核心设置', {
            'fields': ('num', 'publish_status'),
        }),
        ('栏目管理', {
            'fields': ('nodekey', ),
            'description': "栏目控制选项（支持多栏目配置）"
        }),
        ('余量提醒', {
            'fields': ('enable_remainder_alert', 'remainder_threshold'),
            'description':
            mark_safe(
                '<div class="alert alert-secondary">余量提醒相关配置:本功能暂未开启，我们还在考虑如果考虑提醒的周期</div>'
            )
        }),
    )

    # class Media:
    #     js = ('js/admin/post_set_dynamic.js', )

    # 显示字段调整
    # list_display = ('display_publish_status', 'num', 'short_nodekey')
    # list_display_links = None  # 禁用详情链接

    # def short_nodekey(self, obj):
    #     return obj.nodekey[:50] + '...' if len(
    #         obj.nodekey) > 50 else obj.nodekey

    # short_nodekey.short_description = '栏目简码'

    # def display_publish_status(self, obj):
    #     return obj.get_publish_status_display()

    # display_publish_status.short_description = '发布状态'

    def response_change(self, request, obj):
        # 处理测试邮件按钮点击
        if "_send_test_email" in request.POST:
            self.send_test_email(request, obj)
            self.message_user(request, "测试邮件已发送，请查收收件箱")
            return HttpResponseRedirect(
                reverse('admin:core_post_set_change', args=[obj.id]))
        return super().response_change(request, obj)

    def send_test_email(self, request, obj):
        """
        邮件发送函数封装（需后期实现）
        """
        # 实际发送邮件逻辑需要在此处实现
        # 示例参数：
        recipient = "admin@example.com"
        subject = "余量提醒测试邮件"
        message = f"当前余量阈值：{obj.remainder_threshold}"

        # TODO: 调用实际邮件发送代码
        # send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [recipient])
        print('模拟邮件发送')
        pass

    def change_view(self, request, object_id, form_url='', extra_context=None):
        # 添加自定义按钮到上下文
        extra_context = extra_context or {}
        extra_context['show_save_and_test'] = True  # 控制按钮显示
        return super().change_view(request,
                                   object_id,
                                   form_url,
                                   extra_context=extra_context)

    def send_test_email2(self, request, obj):
        from django.core.mail import send_mail
        try:
            send_mail(
                subject="余量提醒测试邮件",
                message=f"当前系统配置的余量阈值为：{obj.remainder_threshold}",
                from_email=settings.DEFAULT_FROM_EMAIL,
                recipient_list=[settings.ADMIN_EMAIL],
                fail_silently=False,
            )
            self.message_user(request, "测试邮件发送成功")
        except Exception as e:
            self.message_user(request, f"邮件发送失败：{str(e)}", level=ERROR)
