import { saveAs } from 'file-saver'
import {
  Packer,
  Document,
  Paragraph,
  HeadingLevel,
  TextRun,
  ImageRun,
  ExternalHyperlink,
} 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, items: any[]) {
  const blobs = await Promise.all(
    items.map(async (item) => await fetch(item.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,
            },
          }),
      ),
    ],
  })
}
function createLink(key: string, items: any[]) {
  return new Paragraph({
    children: [
      new TextRun({ text: `${key}：` }),
      ...items.map(
        (item: any) =>
          new ExternalHyperlink({
            link: item.url,
            child: new TextRun({
              text: decodeURIComponent(item.url.split('_').pop() || '未命名'),
            }),
          }),
      ),
    ],
  })
}

function arrayToString(e: unknown) {
  if (Array.isArray(e)) return e.join(',')
  return e
}

async function createDocument(data: any[], labelKey: string) {
  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])
                if (key.includes('文件')) return createLink(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`)
  })
}
