import smtplib
import random
import string
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from flask import current_app
import logging

# 配置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)


# 配置邮件发送功能
def send_verification_email(to_email, verification_code):
    """
    发送验证码邮件
    """
    try:
        # 从应用配置获取邮件设置
        email_host = current_app.config['EMAIL_HOST']
        email_port = current_app.config['EMAIL_PORT']
        email_username = current_app.config['EMAIL_USERNAME']
        email_password = current_app.config['EMAIL_PASSWORD']
        email_from = current_app.config['EMAIL_FROM']
        email_from_name = current_app.config['EMAIL_FROM_NAME']

        logger.info(f"准备发送邮件到: {to_email}, 验证码: {verification_code}")
        logger.debug(f"邮件配置: 主机={email_host}, 端口={email_port}")

        # 邮件内容
        msg = MIMEMultipart()
        msg['From'] = f"{email_from_name} <{email_from}>"
        msg['To'] = to_email
        msg['Subject'] = "图书管理系统 - 验证码"

        # 邮件正文
        body = f"""
        <html>
        <body>
            <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e1e1e1; border-radius: 5px;">
                <h2 style="color: #4a89dc;">图书管理系统 - 邮箱验证</h2>
                <p>您好，</p>
                <p>感谢您注册图书管理系统，您的验证码是:</p>
                <div style="background-color: #f5f5f5; padding: 10px; border-radius: 5px; text-align: center; font-size: 24px; letter-spacing: 5px; font-weight: bold; margin: 20px 0;">
                    {verification_code}
                </div>
                <p>该验证码将在10分钟内有效，请勿将验证码分享给他人。</p>
                <p>如果您没有请求此验证码，请忽略此邮件。</p>
                <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #e1e1e1; font-size: 12px; color: #888;">
                    <p>此邮件为系统自动发送，请勿回复。</p>
                    <p>&copy; 2025 图书管理系统</p>
                </div>
            </div>
        </body>
        </html>
        """

        msg.attach(MIMEText(body, 'html'))

        logger.debug("尝试连接到SMTP服务器...")
        # 连接服务器发送邮件
        server = smtplib.SMTP(email_host, email_port)
        server.set_debuglevel(1)  # 启用详细的SMTP调试输出

        logger.debug("检查是否需要STARTTLS加密...")
        if current_app.config.get('EMAIL_ENCRYPTION') == 'starttls':
            logger.debug("启用STARTTLS...")
            server.starttls()

        logger.debug(f"尝试登录邮箱: {email_username}")
        server.login(email_username, email_password)

        logger.debug("发送邮件...")
        server.send_message(msg)

        logger.debug("关闭连接...")
        server.quit()

        logger.info(f"邮件发送成功: {to_email}")
        return True
    except Exception as e:
        logger.error(f"邮件发送失败: {str(e)}", exc_info=True)
        return False


def generate_verification_code(length=6):
    """
    生成数字验证码
    """
    return ''.join(random.choice(string.digits) for _ in range(length))
