import { saveAs } from 'file-saver'
import { Packer, Document, Paragraph, HeadingLevel, TextRun } 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,
      }),
    ],
  })
}

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

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