import { saveAs } from 'file-saver'
import {
  Packer,
  Document,
  Paragraph,
  HeadingLevel,
  TextRun,
  ImageRun,
} from 'docx'

function createHeading(text: string): Paragraph {
  return new Paragraph({
    text: text,
    heading: HeadingLevel.HEADING_1,
    thematicBreak: true,
  })
}

function createText(text: string): Paragraph {
  return new Paragraph({
    children: [
      new TextRun({
        text,
      }),
    ],
  })
}

async function createImage(key: string, urls: string[]) {
  const blobs = await Promise.all(
    urls.map(async (url) => await fetch(url).then((r: any) => r.blob())),
  )
  return new Paragraph({
    children: [
      new TextRun({ text: `${key}：` }),
      ...blobs.map(
        (blob) =>
          new ImageRun({
            data: blob,
            transformation: {
              width: 100,
              height: 100,
            },
          }),
      ),
    ],
  })
}

async function createDocument(data: any[], labelKey: string) {
  function arrayToString(e: unknown) {
    if (Array.isArray(e)) return e.join(',')
    return e
  }
  return new Document({
    sections: await Promise.all(
      data.map(async (item) => {
        const keys = Object.keys(item)
        return {
          children: [
            createHeading(item[labelKey]),
            ...(await Promise.all(
              keys.map(async (key) => {
                if (key === '居住地址') return createText('')
                if (key.startsWith('_')) return createText('')
                if (key.includes('照片'))
                  return await createImage(key, item[key])
                return createText(`${key}：${arrayToString(item[key])}`)
              }),
            )),
          ],
        }
      }),
    ),
  })
}

/**
 * 导出文件为docx
 * @param data 数组
 * @param labelKey 每个section的title取值
 * @param defaultFileName 默认导出名字（可选）
 */
export default async function useExportFile(
  data: any[],
  labelKey: string,
  defaultFileName: string = '导出',
) {
  const doc = await createDocument(data, labelKey)
  Packer.toBlob(doc).then((blob) => {
    saveAs(blob, `${defaultFileName}.docx`)
  })
}
