from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import os
import json
import time
import sys
import io
from datetime import datetime
from dotenv import load_dotenv

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# 加载环境变量
try:
    with open("1.env", "r", encoding="UTF-8") as f:
        load_dotenv(stream=f)
    print("1.env 文件加载成功")
except Exception as e:
    print(f"1.env 文件加载失败：{str(e)}")
    print("将尝试使用系统环境变量或默认值")

# 读取环境变量
SMTP_HOST = os.getenv("SMTP_HOST", "smtp.qq.com")
SMTP_PORT = int(os.getenv("SMTP_PORT", 465))
SMTP_USER = os.getenv("SMTP_USER", "")
SMTP_PASS = os.getenv("SMTP_PASS", "")
TARGET_EMAIL = os.getenv("TARGET_EMAIL", "")

# 邮件存储文件
MAILBOX_FILE = "mailbox.json"

# 初始化 Flask 应用
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})

def load_mailbox():
    """加载邮件数据"""
    try:
        if os.path.exists(MAILBOX_FILE):
            with open(MAILBOX_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
    except Exception as e:
        print(f"加载邮件数据失败：{str(e)}")
    return []

def save_mailbox(mailbox):
    """保存邮件数据"""
    try:
        with open(MAILBOX_FILE, 'w', encoding='utf-8') as f:
            json.dump(mailbox, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存邮件数据失败：{str(e)}")
        return False

def add_email_to_mailbox(name, email, content):
    """添加邮件到收件箱"""
    mailbox = load_mailbox()
    
    new_email = {
        "id": int(time.time() * 1000),  # 使用时间戳作为唯一ID
        "name": name,
        "email": email,
        "content": content,
        "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "read": False  # 标记是否已读
    }
    
    mailbox.insert(0, new_email)  # 新邮件放在最前面
    return save_mailbox(mailbox)

def send_email(name, email, content):
    """发送邮件核心函数"""
    if not SMTP_USER or not SMTP_PASS or not TARGET_EMAIL:
        print("错误：SMTP_USER、SMTP_PASS、TARGET_EMAIL 配置不能为空！")
        return False

    # 创建邮件对象
	# msg["From"] = f"{Header(name, 'utf-8')} <{SMTP_USER}>"
	# msg["From"] = f"{Header(name, 'utf-8').encode()} <{SMTP_USER}>"
    msg = MIMEMultipart()
    try:
        subject = f"新的网站留言 - 来自 {name}"
        msg["Subject"] = subject
        msg["From"] = SMTP_USER  # 直接使用邮箱，避免编码问题
        msg["To"] = TARGET_EMAIL
        
        html_content = f"""
        <!DOCTYPE html>
        <html>
        <body>
            <h3 style="color: #333; border-bottom: 1px solid #eee; padding-bottom: 10px;">网站留言通知</h3>
            <p><strong>发送人：</strong>{name}</p>
            {f'<p><strong>联系邮箱：</strong>{email}</p>' if email else '<p><strong>联系邮箱：</strong>未提供</p>'}
            <p><strong>留言内容：</strong></p>
            <div style="background: #f5f5f5; padding: 15px; border-radius: 4px; margin: 10px 0;">
                <p style="margin: 0; white-space: pre-line;">{content}</p>
            </div>
            <p style="color: #666; font-size: 12px; margin-top: 20px;">此邮件由网站自动发送，请勿直接回复</p>
        </body>
        </html>
        """
        msg.attach(MIMEText(html_content, "html", "utf-8"))
    except Exception as e:
        print(f"邮件内容构建失败：错误类型：{type(e).__name__}，详情：{str(e)}")
        return False

    # 发送邮件
    try:
        context = ssl.create_default_context()
        with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, context=context, timeout=15) as server:
            print(f"\n=== 邮件发送调试信息 ===")
            print(f"SMTP 服务器：{SMTP_HOST}:{SMTP_PORT}")
            print(f"发送方邮箱：{SMTP_USER}")
            print(f"接收方邮箱：{TARGET_EMAIL}")
            print(f"邮件主题：{subject}")
            
            server.login(SMTP_USER, SMTP_PASS)
            print("邮箱登录成功")
            
            recipient_list = [email.strip() for email in TARGET_EMAIL.split(",") if email.strip()]
            email_message = msg.as_string()
            # server.sendmail(SMTP_USER, recipient_list, email_message.encode('utf-8'))
            email_data = msg.as_string()
            if isinstance(email_data, str):
                email_data = email_data.encode('utf-8')
            server.sendmail(SMTP_USER, recipient_list, email_data)
            print("邮件发送成功！")
        return True
    except smtplib.SMTPAuthenticationError:
        print("错误：邮箱登录失败！请检查 SMTP_USER 和 SMTP_PASS 是否正确")
        return False
    except Exception as e:
        print(f"邮件发送失败：错误类型：{type(e).__name__}，详情：{str(e)}")
        return False

# 邮件发送接口
@app.route("/send-email", methods=["POST"])
def handle_send_email():
    try:
        data = request.get_json()
        if not data:
            return jsonify({"message": "请提交有效的表单数据"}), 400
        
        name = data.get("name", "").strip()
        email = data.get("email", "").strip()
        content = data.get("content", "").strip()
        
        if not name:
            return jsonify({"message": "您的姓名不能为空"}), 400
        if not content:
            return jsonify({"message": "留言内容不能为空"}), 400
        
        # 保存到本地收件箱
        save_success = add_email_to_mailbox(name, email, content)
        if not save_success:
            print("警告：邮件保存到本地收件箱失败")
        
        # 发送到邮箱
        send_success = send_email(name, email, content)
        if send_success:
            return jsonify({"message": "邮件发送成功！我们会尽快回复您"}), 200
        else:
            return jsonify({"message": "邮件发送失败，但已保存到本地收件箱"}), 500
    except Exception as e:
        print(f"接口处理失败：{str(e)}")
        return jsonify({"message": "服务器内部错误，请稍后再试"}), 500

# 获取收件箱列表
@app.route("/mailbox", methods=["GET"])
def get_mailbox():
    try:
        mailbox = load_mailbox()
        return jsonify({
            "success": True,
            "data": mailbox,
            "total": len(mailbox),
            "unread": len([mail for mail in mailbox if not mail.get("read", False)])
        })
    except Exception as e:
        print(f"获取收件箱失败：{str(e)}")
        return jsonify({"success": False, "message": "获取邮件列表失败"}), 500

# 标记邮件为已读
@app.route("/mailbox/<int:mail_id>/read", methods=["PUT"])
def mark_as_read(mail_id):
    try:
        mailbox = load_mailbox()
        for mail in mailbox:
            if mail["id"] == mail_id:
                mail["read"] = True
                break
        
        if save_mailbox(mailbox):
            return jsonify({"success": True, "message": "标记为已读成功"})
        else:
            return jsonify({"success": False, "message": "保存失败"}), 500
    except Exception as e:
        print(f"标记已读失败：{str(e)}")
        return jsonify({"success": False, "message": "操作失败"}), 500

# 删除邮件
@app.route("/mailbox/<int:mail_id>", methods=["DELETE"])
def delete_mail(mail_id):
    try:
        mailbox = load_mailbox()
        mailbox = [mail for mail in mailbox if mail["id"] != mail_id]
        
        if save_mailbox(mailbox):
            return jsonify({"success": True, "message": "删除成功"})
        else:
            return jsonify({"success": False, "message": "保存失败"}), 500
    except Exception as e:
        print(f"删除邮件失败：{str(e)}")
        return jsonify({"success": False, "message": "操作失败"}), 500

# 收件箱管理页面
@app.route("/admin")
def admin_page():
    return """
    <!DOCTYPE html>
    <html>
    <head>
        <title>邮件收件箱管理</title>
        <meta charset="utf-8">
        <style>
            body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
            .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; }
            .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
            .mail-item { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 5px; }
            .mail-item.unread { background: #f0f7ff; border-left: 4px solid #2196F3; }
            .mail-header { display: flex; justify-content: space-between; margin-bottom: 10px; }
            .mail-sender { font-weight: bold; color: #333; }
            .mail-time { color: #666; font-size: 14px; }
            .mail-email { color: #2196F3; margin-left: 10px; }
            .mail-content { color: #555; line-height: 1.5; }
            .mail-actions { margin-top: 10px; }
            .btn { padding: 5px 10px; margin-right: 5px; border: none; border-radius: 3px; cursor: pointer; }
            .btn-read { background: #4CAF50; color: white; }
            .btn-delete { background: #f44336; color: white; }
            .stats { background: #e3f2fd; padding: 10px; border-radius: 5px; margin-bottom: 20px; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>邮件收件箱管理</h1>
                <button onclick="loadMailbox()">刷新</button>
            </div>
            <div class="stats" id="stats">加载中...</div>
            <div id="mailbox"></div>
        </div>

        <script>
            async function loadMailbox() {
                try {
                    const response = await fetch('/mailbox');
                    const result = await response.json();
                    
                    if (result.success) {
                        // 更新统计信息
                        document.getElementById('stats').innerHTML = 
                            `总邮件数: ${result.total} | 未读邮件: ${result.unread}`;
                        
                        // 渲染邮件列表
                        const mailboxEl = document.getElementById('mailbox');
                        mailboxEl.innerHTML = result.data.map(mail => `
                            <div class="mail-item ${mail.read ? '' : 'unread'}">
                                <div class="mail-header">
                                    <div>
                                        <span class="mail-sender">${mail.name}</span>
                                        <span class="mail-email">${mail.email || '无邮箱'}</span>
                                    </div>
                                    <span class="mail-time">${mail.timestamp}</span>
                                </div>
                                <div class="mail-content">${mail.content}</div>
                                <div class="mail-actions">
                                    ${!mail.read ? `<button class="btn btn-read" onclick="markAsRead(${mail.id})">标记已读</button>` : ''}
                                    <button class="btn btn-delete" onclick="deleteMail(${mail.id})">删除</button>
                                </div>
                            </div>
                        `).join('');
                    }
                } catch (error) {
                    console.error('加载失败:', error);
                }
            }

            async function markAsRead(mailId) {
                try {
                    const response = await fetch(`/mailbox/${mailId}/read`, { method: 'PUT' });
                    const result = await response.json();
                    if (result.success) {
                        loadMailbox();
                    }
                } catch (error) {
                    console.error('标记已读失败:', error);
                }
            }

            async function deleteMail(mailId) {
                if (confirm('确定要删除这封邮件吗？')) {
                    try {
                        const response = await fetch(`/mailbox/${mailId}`, { method: 'DELETE' });
                        const result = await response.json();
                        if (result.success) {
                            loadMailbox();
                        }
                    } catch (error) {
                        console.error('删除失败:', error);
                    }
                }
            }

            // 页面加载时自动获取邮件列表
            loadMailbox();
            // 每30秒自动刷新
            setInterval(loadMailbox, 30000);
        </script>
    </body>
    </html>
    """

# 启动服务器
if __name__ == "__main__":
    print(f"服务器启动中... 端口：5000")
    print(f"SMTP 配置预览：{SMTP_HOST}:{SMTP_PORT}（发送方：{SMTP_USER}）")
    print(f"收件箱管理页面：http://localhost:5000/admin")
    app.run(debug=True, host="0.0.0.0", port=5000)