import React, { useState, useEffect } from 'react';
import { Modal, Button, message } from 'antd';
import { DownloadOutlined, PictureOutlined } from '@ant-design/icons';
import axios from 'axios';
import html2canvas from 'html2canvas';
import API_BASE_URL from '../config';
import AchievementFormRenderer from './AchievementFormRenderer';

const AchievementDetails = ({ id, open, onClose }) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);

  const fetchDetails = React.useCallback(async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get(`${API_BASE_URL}/api/achievements/${id}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      setData(response.data);
    } catch (error) {
      message.error('获取详情失败');
    } finally {
      setLoading(false);
    }
  }, [id]);

  useEffect(() => {
    if (open && id) {
      fetchDetails();
    }
  }, [open, id, fetchDetails]);

  const handleDownloadAttachment = async () => {
    if (data?.attachments && data.attachments.length > 0) {
      const hide = message.loading('正在打包下载...', 0);
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get(`${API_BASE_URL}/api/achievements/${id}/attachments/zip`, {
          headers: { Authorization: `Bearer ${token}` },
          responseType: 'blob'
        });

        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;

        let filename = `成果附件_${data.name || id}.zip`;
        const contentDisposition = response.headers['content-disposition'];
        if (contentDisposition) {
          const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)/) || contentDisposition.match(/filename="(.+)"/);
          if (filenameMatch && filenameMatch[1]) {
            filename = decodeURIComponent(filenameMatch[1]);
          }
        }

        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();
        link.remove();
        window.URL.revokeObjectURL(url);
        message.success('下载已开始');
      } catch (error) {
        console.error('下载失败:', error);
        message.error('下载失败，请稍后重试');
      } finally {
        hide();
      }
    } else {
      message.warning('该成果没有附件');
    }
  };

  const handleDownloadImage = async () => {
    const element = document.getElementById('achievement-detail-content');
    if (!element) return;

    const hideMessage = message.loading('正在生成图片...', 0);
    const EXPORT_WIDTH = 1100;

    const container = document.createElement('div');
    container.style.position = 'fixed';
    container.style.top = '0';
    container.style.left = '-100000px';
    container.style.zIndex = '-9999';
    container.style.width = `${EXPORT_WIDTH}px`;
    container.style.backgroundColor = '#fff';
    container.style.padding = '40px';
    container.style.boxSizing = 'border-box';
    container.style.overflow = 'visible';
    document.body.appendChild(container);

    const header = document.createElement('div');
    header.style.textAlign = 'center';
    header.style.marginBottom = '30px';
    header.style.borderBottom = '2px solid #1890ff';
    header.style.paddingBottom = '20px';
    header.innerHTML = `
      <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 10px;">
        <img src="/logo.png" style="height: 50px; margin-right: 15px;" onerror="this.style.display='none'" />
        <h1 style="margin: 0; font-size: 28px; font-weight: bold; color: #333; white-space: normal; word-break: break-all; overflow-wrap: anywhere;">科技成果管理表单</h1>
      </div>
      <div style="font-size: 14px; color: #666;">生成时间：${new Date().toLocaleString()}</div>
    `;
    container.appendChild(header);

    const contentClone = element.cloneNode(true);
    contentClone.style.overflow = 'visible';
    container.appendChild(contentClone);

    try {
      const exportWidth = Math.max(container.scrollWidth, container.offsetWidth);
      const exportHeight = Math.max(container.scrollHeight, container.offsetHeight);

      const canvas = await html2canvas(container, {
        useCORS: true,
        scale: 2,
        backgroundColor: '#ffffff',
        width: exportWidth,
        height: exportHeight,
        windowWidth: exportWidth,
        windowHeight: exportHeight,
        scrollX: 0,
        scrollY: 0
      });

      const link = document.createElement('a');
      link.download = `成果表单_${data.name || '未命名'}.png`;
      link.href = canvas.toDataURL('image/png');
      link.click();
      message.success('图片已下载');
    } catch (err) {
      console.error(err);
      message.error('生成图片失败');
    } finally {
      document.body.removeChild(container);
      hideMessage();
    }
  };

  return (
    <Modal
      title="成果详情"
      open={open}
      confirmLoading={loading}
      onCancel={onClose}
      footer={[
        <Button key="close" onClick={onClose}>关闭</Button>,
        <Button key="form" icon={<PictureOutlined />} onClick={handleDownloadImage}>下载表单</Button>,
        <Button key="attachment" type="primary" icon={<DownloadOutlined />} onClick={handleDownloadAttachment}>下载附件</Button>
      ]}
      width={800}
    >
      {data ? (
        <AchievementFormRenderer data={data} />
      ) : (
        <div style={{ textAlign: 'center', padding: '20px' }}>加载中...</div>
      )}
    </Modal>
  );
};

export default AchievementDetails;