/**
 * 数据导出 composable
 */
import { ref } from 'vue'

export interface ExportColumn {
  key: string
  label: string
  width?: number
}

export interface ExportOptions {
  filename: string
  columns: ExportColumn[]
  data: Record<string, any>[]
}

export function useDataExport() {
  const exporting = ref(false)

  /**
   * 导出为CSV
   */
  const exportToCsv = async (options: ExportOptions) => {
    exporting.value = true
    try {
      const { filename, columns, data } = options

      // 构建CSV内容
      const header = columns.map(col => `"${col.label}"`).join(',')
      const rows = data.map(item =>
        columns.map(col => {
          const value = item[col.key]
          if (value === null || value === undefined) return ''
          return `"${String(value).replace(/"/g, '""')}"`
        }).join(',')
      )

      const csv = [header, ...rows].join('\n')

      // 添加BOM以支持中文
      const BOM = '\uFEFF'
      const blob = new Blob([BOM + csv], { type: 'text/csv;charset=utf-8;' })

      // 下载
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `${filename}_${formatDate(new Date())}.csv`
      link.click()
      URL.revokeObjectURL(link.href)
    } finally {
      exporting.value = false
    }
  }

  /**
   * 导出为JSON
   */
  const exportToJson = async (options: ExportOptions) => {
    exporting.value = true
    try {
      const { filename, data } = options

      const json = JSON.stringify(data, null, 2)
      const blob = new Blob([json], { type: 'application/json' })

      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `${filename}_${formatDate(new Date())}.json`
      link.click()
      URL.revokeObjectURL(link.href)
    } finally {
      exporting.value = false
    }
  }

  /**
   * 导出为Excel (使用HTML table方式)
   */
  const exportToExcel = async (options: ExportOptions) => {
    exporting.value = true
    try {
      const { filename, columns, data } = options

      const tableHtml = `
        <table border="1">
          <thead>
            <tr>
              ${columns.map(col => `<th>${col.label}</th>`).join('')}
            </tr>
          </thead>
          <tbody>
            ${data.map(item =>
              `<tr>${columns.map(col => `<td>${item[col.key] ?? ''}</td>`).join('')}</tr>`
            ).join('')}
          </tbody>
        </table>
      `

      const blob = new Blob([tableHtml], { type: 'application/vnd.ms-excel' })

      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `${filename}_${formatDate(new Date())}.xls`
      link.click()
      URL.revokeObjectURL(link.href)
    } finally {
      exporting.value = false
    }
  }

  /**
   * 打印数据
   */
  const printData = (options: ExportOptions) => {
    const { columns, data } = options

    const tableHtml = `
      <html>
        <head>
          <style>
            table { border-collapse: collapse; width: 100%; }
            th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
            th { background-color: #f2f2f2; }
          </style>
        </head>
        <body>
          <table>
            <thead>
              <tr>
                ${columns.map(col => `<th>${col.label}</th>`).join('')}
              </tr>
            </thead>
            <tbody>
              ${data.map(item =>
                `<tr>${columns.map(col => `<td>${item[col.key] ?? ''}</td>`).join('')}</tr>`
              ).join('')}
            </tbody>
          </table>
        </body>
      </html>
    `

    const printWindow = window.open('', '_blank')
    if (printWindow) {
      printWindow.document.write(tableHtml)
      printWindow.document.close()
      printWindow.print()
    }
  }

  return {
    exporting,
    exportToCsv,
    exportToJson,
    exportToExcel,
    printData
  }
}

function formatDate(date: Date): string {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}${month}${day}`
}
