// 거래명세표 엑셀/HTML 생성
import * as XLSX from "xlsx";

export interface StatementOrderItem {
  seq: number;
  itemName: string;
  unit: string;
  qty: number;
  unitPrice: number;
  supplyAmount: number;
  vatAmount: number;
  totalAmount: number;
  isTaxFree: boolean;
  remark?: string;
}

export interface StatementInput {
  orderNo: string;
  orderDate: string;        // YYYY-MM-DD
  customer: {
    companyName: string;
    ceoName?: string;
    bizNo?: string;
    phone?: string;
  };
  supplier: {
    companyName: string;    // "모모유통"
    bankAccount?: string;   // "기업은행 ____"
    phone?: string;
    email?: string;
  };
  items: StatementOrderItem[];
  totals: {
    supply: number;
    vat: number;
    total: number;
    taxFree: number;
    taxable: number;
    unpaid?: number;        // 미수액 (선택, 기본 = total)
  };
}

function fmt(n: number): number {
  return Math.round(n);
}

export function buildStatementXlsx(input: StatementInput): Buffer {
  const wb = XLSX.utils.book_new();
  const aoa: (string | number)[][] = [];

  aoa.push(["거 래 명 세 표"]);
  aoa.push([]);
  aoa.push([input.orderDate, "", "", "", "공급자", input.supplier.companyName]);
  aoa.push(["", input.customer.companyName + " 귀하", "", "", "계좌번호", input.supplier.bankAccount ?? "-"]);
  aoa.push(["", "", "", "", "전화번호", input.supplier.phone ?? "-"]);
  aoa.push(["", "", "", "", "이메일", input.supplier.email ?? "-"]);
  aoa.push([]);
  aoa.push(["아래와 같이 계산합니다."]);
  aoa.push([]);

  const unpaid = input.totals.unpaid ?? input.totals.total;
  aoa.push(["합계", fmt(input.totals.total), "(VAT포함)", "", "미수액", fmt(unpaid)]);
  aoa.push([]);

  // 거래처용이라 현재고 컬럼 없음
  aoa.push(["순번", "품명", "구분", "단위", "수량", "단가", "공급가액", "세액", "합계", "비고"]);

  for (const it of input.items) {
    aoa.push([
      it.seq,
      it.itemName,
      it.isTaxFree ? "면세" : "과세",
      it.unit || "EA",
      it.qty,
      fmt(it.unitPrice),
      fmt(it.supplyAmount),
      it.isTaxFree ? "" : fmt(it.vatAmount),
      fmt(it.totalAmount),
      it.remark ?? "",
    ]);
  }

  aoa.push([]);
  aoa.push(["", "", "", "", "", "", "", "면세 합계",   fmt(input.totals.taxFree)]);
  aoa.push(["", "", "", "", "", "", "", "과세 공급가", fmt(input.totals.taxable)]);
  aoa.push(["", "", "", "", "", "", "", "세액 합계",   fmt(input.totals.vat)]);
  aoa.push(["", "", "", "", "", "", "", "총 합계 (VAT포함)", fmt(input.totals.total)]);

  const ws = XLSX.utils.aoa_to_sheet(aoa);

  ws["!cols"] = [
    { wch: 6 }, { wch: 32 }, { wch: 6 }, { wch: 8 }, { wch: 6 },
    { wch: 12 }, { wch: 14 }, { wch: 12 }, { wch: 14 }, { wch: 18 },
  ];

  ws["!merges"] = [
    { s: { r: 0, c: 0 }, e: { r: 0, c: 9 } },
    { s: { r: 7, c: 0 }, e: { r: 7, c: 9 } },
  ];

  XLSX.utils.book_append_sheet(wb, ws, "거래명세표");
  const buf = XLSX.write(wb, { type: "buffer", bookType: "xlsx" }) as Buffer;
  return buf;
}

export function buildStatementHtml(input: StatementInput): string {
  const unpaid = input.totals.unpaid ?? input.totals.total;
  const rows = input.items
    .map(
      (it) => `
        <tr>
          <td style="border:1px solid #94a3b8;padding:6px;text-align:center">${it.seq}</td>
          <td style="border:1px solid #94a3b8;padding:6px">${escapeHtml(it.itemName)}</td>
          <td style="border:1px solid #94a3b8;padding:6px;text-align:center;color:${it.isTaxFree ? "#7c3aed" : "#e11d48"}">${it.isTaxFree ? "면세" : "과세"}</td>
          <td style="border:1px solid #94a3b8;padding:6px;text-align:center">${escapeHtml(it.unit || "EA")}</td>
          <td style="border:1px solid #94a3b8;padding:6px;text-align:right">${formatNumber(it.qty)}</td>
          <td style="border:1px solid #94a3b8;padding:6px;text-align:right">${formatNumber(fmt(it.unitPrice))}</td>
          <td style="border:1px solid #94a3b8;padding:6px;text-align:right">${formatNumber(fmt(it.supplyAmount))}</td>
          <td style="border:1px solid #94a3b8;padding:6px;text-align:right">${it.isTaxFree ? "-" : formatNumber(fmt(it.vatAmount))}</td>
          <td style="border:1px solid #94a3b8;padding:6px;text-align:right;font-weight:700;background:#fffbeb">${formatNumber(fmt(it.totalAmount))}</td>
          <td style="border:1px solid #94a3b8;padding:6px;font-size:11px;color:#64748b">${escapeHtml(it.remark ?? "")}</td>
        </tr>`
    )
    .join("");

  return `<!doctype html>
<html lang="ko"><head><meta charset="utf-8"></head>
<body style="font-family:'Apple SD Gothic Neo','Malgun Gothic',sans-serif;color:#0f172a;padding:24px;background:#fff">
  <h2 style="text-align:center;letter-spacing:8px;margin:0 0 16px;font-size:22px">거 래 명 세 표</h2>

  <table style="width:100%;margin-bottom:14px;border-collapse:collapse">
    <tr>
      <td style="vertical-align:top;width:60%;font-size:13px">
        <div style="margin-bottom:8px">${escapeHtml(input.orderDate)}</div>
        <div style="border:1px solid #94a3b8;padding:10px;background:#fafafa">
          <b style="font-size:14px">${escapeHtml(input.customer.companyName)}</b>
          <span style="margin-left:6px;color:#475569">귀하</span>
          ${input.customer.ceoName ? `<br><span style="color:#64748b;font-size:12px">대표: ${escapeHtml(input.customer.ceoName)}</span>` : ""}
        </div>
      </td>
      <td style="vertical-align:top;width:40%">
        <table style="border-collapse:collapse;font-size:12px;width:100%">
          <tr>
            <td rowspan="3" style="border:1px solid #94a3b8;background:#475569;color:#fff;text-align:center;font-weight:700;padding:6px;width:24px">공<br>급<br>자</td>
            <td style="border:1px solid #94a3b8;background:#f1f5f9;text-align:center;font-weight:600;padding:5px 8px;width:80px">결제계좌</td>
            <td style="border:1px solid #94a3b8;padding:5px 8px;font-weight:700">${escapeHtml(input.supplier.bankAccount ?? "-")}</td>
          </tr>
          <tr>
            <td style="border:1px solid #94a3b8;background:#f1f5f9;text-align:center;font-weight:600;padding:5px 8px">전화번호</td>
            <td style="border:1px solid #94a3b8;padding:5px 8px">${escapeHtml(input.supplier.phone ?? "-")}</td>
          </tr>
          <tr>
            <td style="border:1px solid #94a3b8;background:#f1f5f9;text-align:center;font-weight:600;padding:5px 8px">이메일</td>
            <td style="border:1px solid #94a3b8;padding:5px 8px;color:#1d4ed8">${escapeHtml(input.supplier.email ?? "-")}</td>
          </tr>
        </table>
      </td>
    </tr>
  </table>

  <p style="text-align:center;margin:14px 0 8px;font-size:13px">아래와 같이 계산합니다.</p>

  <table style="width:100%;border-collapse:collapse;margin-bottom:10px;font-size:13px">
    <tr>
      <td style="border:1px solid #94a3b8;background:#fffbeb;padding:8px;text-align:center;font-weight:700;width:80px">합계</td>
      <td style="border:1px solid #94a3b8;background:#fef9c3;padding:8px;text-align:center;font-weight:800;font-size:18px;color:#0f172a">₩ ${formatNumber(fmt(input.totals.total))}</td>
      <td style="border:1px solid #94a3b8;padding:8px;text-align:center;font-weight:600;color:#475569;width:90px">(VAT포함)</td>
      <td style="border:1px solid #94a3b8;background:#f1f5f9;padding:8px;text-align:center;font-weight:700;width:80px">미수액</td>
      <td style="border:1px solid #94a3b8;padding:8px;text-align:right;font-weight:700;font-size:14px">₩ ${formatNumber(fmt(unpaid))}</td>
    </tr>
  </table>

  <table style="width:100%;border-collapse:collapse;font-size:12px;font-variant-numeric:tabular-nums">
    <thead>
      <tr style="background:#e2e8f0">
        <th style="border:1px solid #94a3b8;padding:6px;width:40px">순번</th>
        <th style="border:1px solid #94a3b8;padding:6px;text-align:left">품명</th>
        <th style="border:1px solid #94a3b8;padding:6px;width:50px">구분</th>
        <th style="border:1px solid #94a3b8;padding:6px;width:50px">단위</th>
        <th style="border:1px solid #94a3b8;padding:6px;width:60px">수량</th>
        <th style="border:1px solid #94a3b8;padding:6px;width:80px">단가</th>
        <th style="border:1px solid #94a3b8;padding:6px;width:90px">공급가액</th>
        <th style="border:1px solid #94a3b8;padding:6px;width:80px">세액</th>
        <th style="border:1px solid #94a3b8;padding:6px;width:90px;background:#fef3c7">합계</th>
        <th style="border:1px solid #94a3b8;padding:6px;width:120px">비고</th>
      </tr>
    </thead>
    <tbody>${rows}</tbody>
  </table>

  <table style="margin-top:14px;margin-left:auto;font-size:13px;font-variant-numeric:tabular-nums">
    <tr><td style="padding:4px 12px;color:#7c3aed">면세 합계</td><td style="padding:4px 0;text-align:right;min-width:140px">₩ ${formatNumber(fmt(input.totals.taxFree))}</td></tr>
    <tr><td style="padding:4px 12px;color:#e11d48">과세 공급가</td><td style="padding:4px 0;text-align:right">₩ ${formatNumber(fmt(input.totals.taxable))}</td></tr>
    <tr><td style="padding:4px 12px">세액 합계</td><td style="padding:4px 0;text-align:right">₩ ${formatNumber(fmt(input.totals.vat))}</td></tr>
    <tr><td style="padding:8px 12px;font-weight:700;border-top:2px solid #0f172a">총 합계 (VAT포함)</td><td style="padding:8px 0;text-align:right;font-weight:700;border-top:2px solid #0f172a">₩ ${formatNumber(fmt(input.totals.total))}</td></tr>
  </table>

  <div style="margin-top:32px;padding-top:16px;border-top:1px solid #e2e8f0;font-size:12px;color:#475569;text-align:center">
    위와 같이 계산합니다. &nbsp;·&nbsp; <b>${escapeHtml(input.supplier.companyName)}</b>
  </div>
</body></html>`;
}

function formatNumber(n: number): string {
  return n.toLocaleString("ko-KR");
}

function escapeHtml(s: string): string {
  return s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}
