from datetime import datetime

from apps.core.models.email_setting import EmailSetting
from django.core.mail import EmailMessage, get_connection
from django.http import JsonResponse
from django.views import View


class EmailSendError(Exception):
    """自定义邮件发送异常"""
    pass


def send_custom_email(subject, message, recipient_list, from_email=None, 
                     html_message=None, fail_silently=False):
    """
    邮件发送函数
    
    :param subject: 邮件主题
    :param message: 纯文本内容
    :param recipient_list: 收件人列表
    :param from_email: 发件人（可选）
    :param html_message: HTML内容（可选）
    :param fail_silently: 是否静默失败
    :return: True表示发送成功
    :raises EmailSendError: 发送失败时抛出
    """
    try:
        email_setting = EmailSetting.get_solo()
    except EmailSetting.DoesNotExist as e:
        raise EmailSendError("邮件服务暂不可用，请检查系统配置") from e

    if not email_setting.email_enabled:
        raise EmailSendError("邮件服务未启用")

    # 验证必要字段
    required_fields = {
        "SMTP服务器": email_setting.email_host,
        "邮箱账号": email_setting.email_user,
        "SMTP密码": email_setting.email_password,
        "SMTP端口": email_setting.email_port,
    }
    missing = [k for k, v in required_fields.items() if not v]
    if missing:
        raise EmailSendError(f"邮件服务配置不完整，缺失字段: {', '.join(missing)}")

    # 根据端口号自动判断加密方式
    use_tls = False
    use_ssl = False
    
    if email_setting.email_port == 465:
        use_ssl = True  # 465端口使用SSL加密
    elif email_setting.email_port == 587:
        use_tls = True   # 587端口使用TLS加密
    elif email_setting.email_port == 25:
        # 25端口通常不加密或使用TLS，但云服务器可能禁用
        use_tls = True  # 为安全起见，25端口也尝试使用TLS
    else:
        raise EmailSendError(f"不支持的端口号: {email_setting.email_port}")

    from_email = from_email or email_setting.default_sender or email_setting.email_user

    try:
        # 创建邮件连接[8](@ref)
        connection = get_connection(
            backend='django.core.mail.backends.smtp.EmailBackend',
            host=email_setting.email_host,
            port=email_setting.email_port,
            username=email_setting.email_user,
            password=email_setting.email_password,
            use_tls=use_tls,
            use_ssl=use_ssl,
        )
    except Exception as e:
        raise EmailSendError(f"邮件服务器连接失败: {str(e)}") from e

    try:
        # 创建邮件消息
        email = EmailMessage(
            subject=subject,
            body=html_message if html_message else message,
            from_email=from_email,
            to=recipient_list,
            connection=connection,
        )
        
        # 如果是HTML邮件，设置内容类型[8](@ref)
        if html_message:
            email.content_subtype = "html"

        # 发送邮件
        result = email.send(fail_silently=fail_silently)
        return result > 0  # 返回是否发送成功
        
    except Exception as e:
        raise EmailSendError(f"邮件发送失败: {str(e)}") from e
    finally:
        # 确保连接关闭
        try:
            connection.close()
        except:
            pass

def send_html_email(subject, html_content, recipient_list, from_email=None, 
                   text_content=None, fail_silently=False):
    """
    发送HTML邮件的便捷函数。如果收件人的邮件客户端不支持HTML，将显示备用的纯文本内容。
    
    :param subject: 邮件主题字符串
    :param html_content: HTML格式的邮件正文字符串
    :param recipient_list: 收件人邮箱地址列表，如 ['user1@example.com', 'user2@example.com']
    :param from_email: 发件人地址，可选。如不提供，将使用配置中的默认发件人[6](@ref)
    :param text_content: 纯文本备选内容，可选。当html_content无法显示时使用[7](@ref)
    :param fail_silently: 发送失败时是否静默处理（不抛出异常），默认为False
    :return: 成功发送的邮件数量（通常为1）
    :raises EmailSendError: 邮件发送失败时抛出（当fail_silently=False）
    
    示例：
    # 发送简单的HTML邮件
    send_html_email(
        subject='欢迎注册我们的网站',
        html_content='<h1>欢迎！</h1><p>感谢您注册我们的服务。</p>',
        recipient_list=['user@example.com']
    )
    """
    return send_custom_email(
        subject=subject,
        message=text_content or "您的邮箱客户端不支持HTML邮件",
        recipient_list=recipient_list,
        from_email=from_email,
        html_message=html_content,
        fail_silently=fail_silently
    )


class SendEmailAPIView(View):
    """邮件发送API视图"""

    def post(self, request):
        data = request.POST
        try:
            send_custom_email(subject=data['subject'],
                              message=data['message'],
                              recipient_list=data.getlist('recipients'),
                              html_message=data.get('html_message'))
            return JsonResponse({'status': 'success'})
        except EmailSendError as e:
            return JsonResponse({
                'status': 'error',
                'message': str(e)
            },
                                status=503)
        except KeyError as e:
            return JsonResponse({
                'status': 'error',
                'message': f'缺少必要参数: {e}'
            },
                                status=400)


class TestEmailConfigView(View):
    """测试邮件配置视图"""

    def post(self, request):
        html_content = f"""
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>djacoreCMS 功能体验报告</title>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
        <style>
        /* 基础网格样式 */
        .feature-grid {{ 
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        }}
        .tech-columns {{
            grid-template-columns: repeat(2, 1fr);
        }}

        /* 移动端适配 */
        @media (max-width: 640px) {{
            .feature-grid {{
                grid-template-columns: 1fr !important;
            }}
            .tech-columns {{
                grid-template-columns: 1fr !important;
            }}
        }}
    </style>
    </head>
    <body style="margin: 0; padding: 0; font-family: 'Segoe UI', system-ui, sans-serif;">
    <!-- 动态数据注入位置 -->
        
        <!-- 头部区域 -->
        <div style="background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); padding: 2rem; text-align: center;">
            <!-- <img src="https://example.com/logo.png" alt="djacoreCMS Logo" style="height: 60px;">-->
            <h1 style="color: white; margin: 1rem 0; font-size: 2.5rem;">djacoreCMS 系统能力验证</h1>
            <p style="color: rgba(255,255,255,0.9); font-size: 1.2rem;">发送时间：{datetime.now().strftime('%Y-%m-%d %H:%M')}</p>
        </div>

        <!-- 功能亮点 -->
        <div style="max-width: 1000px; margin: 2rem auto; padding: 0 1rem;">
            <h2 style="color: #1e3a8a; border-left: 4px solid #2563eb; padding-left: 1rem;">核心功能展示</h2>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1.5rem; margin-top: 1.5rem;">
                <!-- 功能卡片 -->
                <div style="background: #f8fafc; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <i class="fas fa-cubes" style="font-size: 2rem; color: #2563eb;"></i>
                    <h3 style="color: #1e3a8a; margin: 1rem 0;">模块化架构</h3>
                    <p style="color: #64748b;">支持插件化扩展，可按需启用内容管理、用户权限、工作流等模块</p>
                </div>

                <div style="background: #f8fafc; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <i class="fas fa-paint-brush" style="font-size: 2rem; color: #2563eb;"></i>
                    <h3 style="color: #1e3a8a; margin: 1rem 0;">可视化编辑</h3>
                    <p style="color: #64748b;">内置Block编辑器，支持实时预览和版本控制</p>
                </div>

                <div style="background: #f8fafc; padding: 1.5rem; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <i class="fas fa-globe" style="font-size: 2rem; color: #2563eb;"></i>
                    <h3 style="color: #1e3a8a; margin: 1rem 0;">多语言支持</h3>
                    <p style="color: #64748b;">内置i18n解决方案，支持实时内容翻译</p>
                </div>
            </div>
        </div>

        <!-- 技术优势 -->
        <div style="background: #f1f5f9; padding: 2rem 0;">
            <div style="max-width: 1000px; margin: 0 auto; padding: 0 1rem;">
                <h2 style="color: #1e3a8a; border-left: 4px solid #2563eb; padding-left: 1rem;">技术优势验证</h2>
                
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; margin-top: 1.5rem;">
                    <div style="background: white; padding: 1.5rem; border-radius: 8px;">
                        <h3 style="color: #2563eb; margin: 0 0 1rem 0;">性能指标</h3>
                        <ul style="color: #475569; list-style: none; padding: 0;">
                            <li style="padding: 0.5rem 0;"><i class="fas fa-bolt" style="margin-right: 0.5rem;"></i>请求响应时间：<strong>≤300ms</strong></li>
                            <li style="padding: 0.5rem 0;"><i class="fas fa-database" style="margin-right: 0.5rem;"></i>数据库查询：<strong>优化减少40%</strong></li>
                        </ul>
                    </div>

                    <div style="background: white; padding: 1.5rem; border-radius: 8px;">
                        <h3 style="color: #2563eb; margin: 0 0 1rem 0;">安全特性</h3>
                        <ul style="color: #475569; list-style: none; padding: 0;">
                            <li style="padding: 0.5rem 0;"><i class="fas fa-shield-alt" style="margin-right: 0.5rem;"></i>RBAC权限管理</li>
                            <li style="padding: 0.5rem 0;"><i class="fas fa-lock" style="margin-right: 0.5rem;"></i>审计日志追踪</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <!-- 客户评价 -->
        <div style="max-width: 1000px; margin: 2rem auto; padding: 0 1rem;">
            <h2 style="color: #1e3a8a; border-left: 4px solid #2563eb; padding-left: 1rem;">客户见证</h2>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1.5rem; margin-top: 1.5rem;">
                <div style="border: 1px solid #e2e8f0; padding: 1.5rem; border-radius: 8px;">
                    <p style="color: #475569; font-style: italic;">“djacoreCMS的扩展能力完全满足了我们复杂的业务需求”</p>
                    <div style="display: flex; align-items: center; margin-top: 1rem;">
                        <div style="width: 40px; height: 40px; background: #2563eb; border-radius: 50%;"></div>
                        <div style="margin-left: 1rem;">
                            <p style="margin: 0; font-weight: 500;">某科技公司CTO</p>
                            <p style="margin: 0; color: #64748b; font-size: 0.9rem;">互联网行业</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 页脚 -->
        <div style="background: #1e293b; color: white; padding: 2rem; text-align: center; margin-top: 3rem;">
            <p style="margin: 0.5rem 0;">© {datetime.now().year} djacoreCMS 企业级内容管理平台</p>
            <div style="margin-top: 1rem;">
                <a href="https://example.com" style="color: #93c5fd; text-decoration: none; margin: 0 1rem;">访问控制台</a>
                <a href="mailto:support@example.com" style="color: #93c5fd; text-decoration: none; margin: 0 1rem;">技术支持</a>
            </div>
        </div>
    </body>
    </html>
    """
        try:
            test_email = request.POST['test_email']

            send_custom_email(subject="配置测试邮件",
                              message="您的邮件配置测试成功！",
                              recipient_list=[test_email],
                              html_message=html_content)

            return JsonResponse({'success': True, 'message': '测试邮件已发送，请检查收件箱'})

        except EmailSendError as e:
            return JsonResponse(
                {
                    'success': False,
                    'message': f'配置错误: {str(e)}'
                }, status=500)

        except KeyError:
            return JsonResponse({
                'success': False,
                'message': '缺少测试邮箱参数'
            },
                                status=400)

    # def send_test_email(request):

    #     try:
    #         send_custom_email(subject="djacoreCMS 功能体验报告",
    #                           message="此为HTML邮件，请使用支持HTML的邮件客户端查看",
    #                           recipient_list=[test_email],
    #                           html_message=html_content)
    #         return JsonResponse({'success': True, 'message': '测试邮件已发送'})
    #     except EmailSendError as e:
    #         return JsonResponse({'success': False, 'message': str(e)})


# try:

#     send_custom_email(subject="订单通知",
#                       message="您的订单已发货",
#                       recipient_list=["customer@example.com"],
#                       html_message="<h1>HTML内容</h1>")
# except EmailSendError as e:
#     # 处理错误逻辑，例如返回给前端
#     print(f"发送失败2: {str(e)}")
