import nodemailer from 'nodemailer';

// 创建邮件发送服务
export async function sendReportEmail(emailConfig, report) {
  try {
    // 创建SMTP传输器
    const transporter = nodemailer.createTransport({
      host: emailConfig.smtpHost,
      port: emailConfig.smtpPort || 587,
      secure: emailConfig.smtpPort === 465, // true for 465, false for other ports
      auth: {
        user: emailConfig.smtpUser,
        pass: emailConfig.smtpPass,
      },
    });

    // 生成HTML格式的报告内容
    const htmlContent = generateReportHtml(report);

    // 发送邮件
    const info = await transporter.sendMail({
      from: `"公告采集系统" <${emailConfig.smtpUser}>`,
      to: emailConfig.recipients,
      subject: `采购公告分析报告 - ${new Date().toLocaleDateString('zh-CN')}`,
      html: htmlContent,
    });

    return {
      success: true,
      messageId: info.messageId,
    };
  } catch (error) {
    console.error('发送邮件失败:', error);
    throw new Error(`邮件发送失败: ${error.message}`);
  }
}

// 生成HTML格式的报告
function generateReportHtml(report) {
  const { summary, projects } = report;

  return `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>采购公告分析报告</title>
  <style>
    body {
      font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 900px;
      margin: 0 auto;
      padding: 20px;
      background-color: #f5f5f5;
    }
    .container {
      background: white;
      border-radius: 8px;
      padding: 30px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    h1 {
      color: #667eea;
      border-bottom: 3px solid #667eea;
      padding-bottom: 10px;
      margin-bottom: 20px;
    }
    .summary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 20px;
      border-radius: 8px;
      margin-bottom: 30px;
    }
    .summary h2 {
      margin-top: 0;
      margin-bottom: 15px;
      font-size: 18px;
    }
    .stat-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 15px;
    }
    .stat {
      background: rgba(255,255,255,0.15);
      padding: 12px;
      border-radius: 6px;
    }
    .stat-label {
      font-size: 13px;
      opacity: 0.9;
      margin-bottom: 5px;
    }
    .stat-value {
      font-size: 22px;
      font-weight: bold;
    }
    .project-list {
      margin-top: 20px;
    }
    .project-item {
      background: #f9f9f9;
      border-left: 4px solid #667eea;
      padding: 15px;
      margin-bottom: 15px;
      border-radius: 4px;
    }
    .project-item h3 {
      color: #333;
      margin: 0 0 10px 0;
      font-size: 16px;
    }
    .project-meta {
      color: #666;
      font-size: 14px;
      margin: 5px 0;
    }
    .budget {
      display: inline-block;
      background: #667eea;
      color: white;
      padding: 4px 12px;
      border-radius: 4px;
      font-weight: bold;
      margin-top: 8px;
      font-size: 14px;
    }
    .project-link {
      color: #667eea;
      text-decoration: none;
      font-size: 13px;
      word-break: break-all;
    }
    .footer {
      margin-top: 30px;
      padding-top: 20px;
      border-top: 1px solid #e0e0e0;
      color: #999;
      font-size: 12px;
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>南京公共工程建设中心 - 采购公告分析报告</h1>

    <div class="summary">
      <h2>报告摘要</h2>
      <div class="stat-grid">
        <div class="stat">
          <div class="stat-label">总公告数量</div>
          <div class="stat-value">${summary.total_count} 条</div>
        </div>
        <div class="stat">
          <div class="stat-label">符合条件</div>
          <div class="stat-value">${summary.filtered_count} 条</div>
        </div>
        <div class="stat">
          <div class="stat-label">金额阈值</div>
          <div class="stat-value">${summary.threshold}</div>
        </div>
        <div class="stat">
          <div class="stat-label">总金额</div>
          <div class="stat-value">${summary.total_amount}</div>
        </div>
      </div>
      ${summary.date_range ? `
      <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid rgba(255,255,255,0.2);">
        <div class="stat-label">时间范围</div>
        <div style="font-size: 14px; margin-top: 5px;">
          ${summary.date_range.startDate || '不限'} 至 ${summary.date_range.endDate || '不限'}
        </div>
      </div>
      ` : ''}
    </div>

    <h2>项目详情</h2>
    <div class="project-list">
      ${projects.length === 0 ? '<p style="color: #999; text-align: center; padding: 20px;">暂无符合条件的项目</p>' : ''}
      ${projects.map((project, index) => `
        <div class="project-item">
          <h3>${index + 1}. ${project.title}</h3>
          <div class="project-meta">
            <strong>发布日期:</strong> ${project.date}
            ${project.publish_time ? ` | <strong>发布时间:</strong> ${project.publish_time}` : ''}
          </div>
          ${project.budget ? `
            <div class="budget">
              预算金额: ${project.budget.amount.toFixed(2)} ${project.budget.unit}
              ${project.budget.originalUnit !== project.budget.unit ? ` (原始: ${project.budget.originalUnit})` : ''}
            </div>
          ` : ''}
          <div style="margin-top: 10px;">
            <a href="${project.url}" class="project-link" target="_blank">${project.url}</a>
          </div>
        </div>
      `).join('')}
    </div>

    <div class="footer">
      <p>报告生成时间: ${new Date(summary.generated_at).toLocaleString('zh-CN')}</p>
      <p>本报告由公告采集系统自动生成</p>
    </div>
  </div>
</body>
</html>
  `;
}
