import html2canvas from 'html2canvas';
import { ElMessage } from 'element-plus';

/**
 * 打印图表
 * @param chartElement 图表DOM元素
 */
export const printChart = async (chartElement: HTMLElement) => {
  if (!chartElement) {
    ElMessage.warning('图表未加载');
    return;
  }
  
  try {
    const canvas = await html2canvas(chartElement);
    const dataUrl = canvas.toDataURL('image/png');
    
    // 创建打印窗口
    const printWindow = window.open('', '_blank');
    if (!printWindow) {
      ElMessage.error('请允许打开新窗口');
      return;
    }
    
    printWindow.document.write(`
      <html>
        <head>
          <title>图表打印</title>
          <style>
            body { margin: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
            img { max-width: 100%; height: auto; }
          </style>
        </head>
        <body>
          <img src="${dataUrl}" />
        </body>
      </html>
    `);
    printWindow.document.close();
    
    // 等待图片加载完成后打印
    const img = printWindow.document.querySelector('img');
    if (img) {
      img.onload = () => {
        setTimeout(() => {
          printWindow.print();
          printWindow.close();
        }, 100);
      };
    }
  } catch (error) {
    console.error('打印失败:', error);
    ElMessage.error('打印失败，请稍后重试');
  }
};
