import { Injectable, Logger } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
import * as sharp from 'sharp';

export interface ProofData {
  orderNo: string;
  amount: string;
  txHash: string;
  sellerId: string;
  sellerAddress: string;
  completedAt: Date;
}

@Injectable()
export class PaymentProofService {
  private readonly logger = new Logger(PaymentProofService.name);
  private readonly uploadDir = path.resolve('./uploads/c2c-proofs');

  constructor() {
    if (!fs.existsSync(this.uploadDir)) {
      fs.mkdirSync(this.uploadDir, { recursive: true });
    }
  }

  /**
   * 生成付款水单图片（SVG → PNG）
   * @returns 文件 URL path（可直接存入数据库）
   */
  async generateProofImage(data: ProofData): Promise<string> {
    const timestamp = Date.now();
    const filename = `bot-proof-${data.orderNo}-${timestamp}.png`;
    const filePath = path.join(this.uploadDir, filename);

    const svg = this.buildSvg(data);
    await sharp(Buffer.from(svg)).png().toFile(filePath);

    this.logger.log(`[PROOF] Generated: ${filename}`);
    return `/api/v2/trading/c2c/proofs/${filename}`;
  }

  private buildSvg(data: ProofData): string {
    // toISOString() 返回 UTC，手动加 8 小时转北京时间
    const beijingDate = new Date(data.completedAt.getTime() + 8 * 60 * 60 * 1000);
    const time = beijingDate.toISOString().replace('T', ' ').slice(0, 19);

    return `<svg xmlns="http://www.w3.org/2000/svg" width="600" height="420">
  <defs>
    <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
      <stop offset="0%" stop-color="#f8fafc"/>
      <stop offset="100%" stop-color="#e2e8f0"/>
    </linearGradient>
  </defs>
  <rect width="600" height="420" rx="16" fill="url(#bg)"/>
  <rect x="20" y="20" width="560" height="380" rx="12" fill="white" stroke="#cbd5e1" stroke-width="1"/>

  <!-- Header -->
  <rect x="20" y="20" width="560" height="70" rx="12" fill="#1e40af"/>
  <rect x="20" y="60" width="560" height="30" fill="#1e40af"/>
  <text x="300" y="62" text-anchor="middle" font-family="Noto Sans CJK SC,Noto Sans SC,sans-serif" font-size="22" font-weight="bold" fill="white">C2C Bot 付款凭证</text>

  <!-- Stamp -->
  <circle cx="510" cy="160" r="40" fill="none" stroke="#16a34a" stroke-width="2.5" opacity="0.5"/>
  <text x="510" y="155" text-anchor="middle" font-family="Noto Sans CJK SC,Noto Sans SC,sans-serif" font-size="13" font-weight="bold" fill="#16a34a" opacity="0.5">已完成</text>
  <text x="510" y="172" text-anchor="middle" font-family="Noto Sans CJK SC,Noto Sans SC,sans-serif" font-size="10" fill="#16a34a" opacity="0.5">COMPLETED</text>

  <!-- Fields -->
  <text x="60" y="135" font-family="Noto Sans CJK SC,Noto Sans SC,sans-serif" font-size="13" fill="#64748b">订单编号</text>
  <text x="60" y="158" font-family="Noto Sans CJK SC,Noto Sans SC,sans-serif" font-size="16" font-weight="bold" fill="#1e293b">${this.esc(data.orderNo)}</text>

  <line x1="60" y1="175" x2="540" y2="175" stroke="#e2e8f0" stroke-width="1"/>

  <text x="60" y="200" font-family="Noto Sans CJK SC,Noto Sans SC,sans-serif" font-size="13" fill="#64748b">支付金额 (绿积分)</text>
  <text x="60" y="228" font-family="Noto Sans CJK SC,Noto Sans SC,sans-serif" font-size="26" font-weight="bold" fill="#1e40af">${this.esc(data.amount)}</text>

  <line x1="60" y1="248" x2="540" y2="248" stroke="#e2e8f0" stroke-width="1"/>

  <text x="60" y="275" font-family="Noto Sans CJK SC,Noto Sans SC,sans-serif" font-size="13" fill="#64748b">对方ID</text>
  <text x="60" y="298" font-family="Noto Sans CJK SC,Noto Sans SC,sans-serif" font-size="16" font-weight="bold" fill="#1e293b">${this.esc(data.sellerId)}</text>

  <line x1="60" y1="315" x2="540" y2="315" stroke="#e2e8f0" stroke-width="1"/>

  <text x="60" y="340" font-family="Noto Sans CJK SC,Noto Sans SC,sans-serif" font-size="13" fill="#64748b">完成时间</text>
  <text x="60" y="363" font-family="Noto Sans CJK SC,Noto Sans SC,sans-serif" font-size="15" fill="#1e293b">${this.esc(time)}</text>

  <!-- Footer -->
  <text x="300" y="395" text-anchor="middle" font-family="Noto Sans CJK SC,Noto Sans SC,sans-serif" font-size="11" fill="#94a3b8">由系统自动生成 · RWAdurian C2C Bot</text>
</svg>`;
  }

  private esc(str: string): string {
    return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  }
}
