import JSZip from 'jszip'

// HTML → .docx（Word altChunk 方案：HTML 作为 MHT 分块嵌入，Word/WPS 打开时按 HTML 渲染并保留样式）
// 与 html-docx-js 同思路（该库 dist 含 with 语句、Rollup 无法解析，故在此自行实现）

const CONTENT_TYPES_XML = [
  '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
  '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">',
  '  <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />',
  '  <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml" />',
  '  <Override PartName="/word/afchunk.mht" ContentType="message/rfc822" />',
  '</Types>',
].join('\n')

const ROOT_RELS_XML = [
  '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
  '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">',
  '  <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="/word/document.xml" Id="R09c83fafc067488e" />',
  '</Relationships>',
].join('\n')

const DOCUMENT_RELS_XML = [
  '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
  '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">',
  '  <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunk.mht" Id="htmlChunk" />',
  '</Relationships>',
].join('\n')

// A4 纵向，四边 1 英寸页边距（单位 twips）
const DOCUMENT_XML = [
  '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
  '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">',
  '  <w:body>',
  '    <w:altChunk r:id="htmlChunk" />',
  '    <w:sectPr>',
  '      <w:pgSz w:w="12240" w:h="15840" w:orient="portrait" />',
  '      <w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0" />',
  '    </w:sectPr>',
  '  </w:body>',
  '</w:document>',
].join('\n')

// 组装 MHT 文档：正文为 quoted-printable 的 HTML（= 需转义为 =3D），data URI 图片拆为独立分块
const buildMht = (htmlSource) => {
  const imageParts = []
  htmlSource = htmlSource.replace(/"data:([\w.+-]+\/[\w.+-]+);(\w+),(\S+)"/g, (_m, contentType, encoding, encoded) => {
    const index = imageParts.length
    const extension = contentType.split('/')[1]
    const contentLocation = `file:///C:/fake/image${index}.${extension}`
    imageParts.push(
      [
        '------=mhtDocumentPart',
        `Content-Type: ${contentType}`,
        `Content-Transfer-Encoding: ${encoding}`,
        `Content-Location: ${contentLocation}`,
        '',
        encoded,
      ].join('\n')
    )
    return `"${contentLocation}"`
  })
  const escapedHtml = htmlSource.replace(/=/g, '=3D')
  return [
    'MIME-Version: 1.0',
    'Content-Type: multipart/related;',
    '    type="text/html";',
    '    boundary="----=mhtDocumentPart"',
    '',
    '',
    '------=mhtDocumentPart',
    'Content-Type: text/html;',
    '    charset="utf-8"',
    'Content-Transfer-Encoding: quoted-printable',
    'Content-Location: file:///C:/fake/document.html',
    '',
    escapedHtml,
    '',
    imageParts.join('\n'),
    '',
    '------=mhtDocumentPart--',
  ].join('\n')
}

// HTML 字符串 → .docx Blob
export const htmlToDocxBlob = async (htmlSource) => {
  const zip = new JSZip()
  zip.file('[Content_Types].xml', CONTENT_TYPES_XML)
  zip.folder('_rels').file('.rels', ROOT_RELS_XML)
  zip
    .folder('word')
    .file('document.xml', DOCUMENT_XML)
    .file('afchunk.mht', buildMht(String(htmlSource || '')))
    .folder('_rels')
    .file('document.xml.rels', DOCUMENT_RELS_XML)
  const buffer = await zip.generateAsync({ type: 'arraybuffer' })
  return new Blob([buffer], {
    type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  })
}
