import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Statistic, Table, Tag, Space, Button, message, Popconfirm, Select, Input, DatePicker, Tabs, Modal, Progress } from 'antd';
import { FileTextOutlined, CheckCircleOutlined, ClockCircleOutlined, CloseCircleOutlined, EyeOutlined, DeleteOutlined, EditOutlined, SearchOutlined, UserOutlined, GlobalOutlined, UserSwitchOutlined, PictureOutlined } from '@ant-design/icons';
import axios from 'axios';
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
import html2canvas from 'html2canvas';
import API_BASE_URL from '../config';
import AchievementDetails from '../components/AchievementDetails';
import AchievementEdit from '../components/AchievementEdit';
import AchievementFormRenderer from '../components/AchievementFormRenderer';
import { maskPhone } from '../utils/phoneMask';

const Dashboard = () => {
  const [stats, setStats] = useState({ total: 0, pending: 0, approved: 0, rejected: 0 });
  const [recentData, setRecentData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedId, setSelectedId] = useState(null);
  const [detailsVisible, setDetailsVisible] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const [filterType, setFilterType] = useState(null);
  const [filterStatus, setFilterStatus] = useState(null);
  const [keyword, setKeyword] = useState('');
  const [dateRange, setDateRange] = useState(null);
  const [activeTab, setActiveTab] = useState('my');
  const [pendingUsers, setPendingUsers] = useState(new Set());

  // 批量下载相关状态
  const [batchLoading, setBatchLoading] = useState(false);
  const [batchProgress, setBatchProgress] = useState({ current: 0, total: 0 });
  const [batchCurrentData, setBatchCurrentData] = useState(null);

  const user = JSON.parse(localStorage.getItem('user') || '{}');
  const canDeleteAchievement = (record) => (
    user.role === 'super_admin' ||
    (record.user_id === user.id && ['pending', 'rejected'].includes(record.status))
  );

  useEffect(() => {
    fetchDashboardData();
    fetchPendingUsers();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filterType, filterStatus, activeTab]);

  // 获取待定状态用户列表
  const fetchPendingUsers = async () => {
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get(`${API_BASE_URL}/api/users/pending-list`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      setPendingUsers(new Set(response.data));
    } catch (error) {
      console.error('获取待定用户列表失败', error);
    }
  };

  const fetchDashboardData = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      const params = { 
        type: filterType, 
        status: filterStatus,
        keyword: keyword,
        startDate: dateRange && dateRange[0] ? dateRange[0].format('YYYY-MM-DD') : null,
        endDate: dateRange && dateRange[1] ? dateRange[1].format('YYYY-MM-DD') : null
      };

      // 根据 Tab 决定查询范围
      if (activeTab === 'my') {
        params.scope = 'my';
      } else if (activeTab === 'public') {
        // 公共库只看已通过的
        params.status = 'approved';
      }
      // activeTab === 'all' 时，不传 scope 也不强制 status，后端默认返回所有（针对管理员）

      const config = { 
        headers: { Authorization: `Bearer ${token}` },
        params
      };
      
      const response = await axios.get(`${API_BASE_URL}/api/achievements`, config);
      const data = response.data;
      setRecentData(data); // 显示所有数据，支持分页更好，但这里先全量
      
      // 更新统计数据：基于当前列表数据计算
      // my: 显示个人统计
      // public: 显示公示统计（仅已通过）
      // all: 显示全系统统计
      const s = { total: data.length, pending: 0, approved: 0, rejected: 0 };
      data.forEach(item => {
        if (item.status === 'pending') s.pending++;
        else if (item.status === 'approved') s.approved++;
        else if (item.status === 'rejected') s.rejected++;
      });
      setStats(s);
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 80,
      render: (type) => {
        const typeMap = {
          paper: '论文', project: '项目', award: '奖励', standard: '标准',
          monograph: '专著', report: '技术报告', plan: '规划', patent: '专利',
          transformation: '成果转化', software: '软著'
        };
        return <Tag color="blue">{typeMap[type] || type}</Tag>;
      }
    },
    {
      title: '成果名称',
      dataIndex: 'name',
      key: 'name',
      width: 300,
      render: (text, record) => {
        const dateLabels = {
          paper: '发表日期', project: '验收时间', award: '获奖日期', standard: '发布日期',
          monograph: '出版时间', report: '报告提交时间', plan: '发布日期', patent: '授权时间',
          transformation: '验收时间', software: '授权证书时间'
        };
        const dateLabel = dateLabels[record.type] || '成果时间';
        
        return (
          <Space direction="vertical" size={0}>
            <span style={{ fontSize: '16px', fontWeight: 600, wordBreak: 'break-all', whiteSpace: 'normal' }}>{text}</span>
            <span style={{ color: '#888', fontSize: '12px' }}>
              {dateLabel}: {record.achievement_date ? new Date(record.achievement_date).toLocaleDateString() : '无'}
            </span>
          </Space>
        );
      }
    },
    {
      title: '提交人',
      key: 'submitter',
      width: 150,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <span><UserOutlined style={{ marginRight: 4 }} />{record.submitter_name || '未知'}</span>
          <small style={{ color: '#888' }}>{maskPhone(record.username)}</small>
        </Space>
      )
    },
    {
      title: '完成人',
      dataIndex: 'contributors',
      key: 'contributors',
      render: (contributors) => (
        <Space size={[0, 4]} wrap>
          {(contributors || []).map((c, idx) => {
            const isPending = pendingUsers.has(c.phone);
            return (
              <Tag 
                key={idx} 
                color={isPending ? 'red' : (c.isMain ? 'orange' : 'default')} 
                style={{ borderRadius: '10px' }}
              >
                {c.name}
                {c.isMain && <span style={{ marginLeft: 2, fontSize: '10px' }}>★</span>}
              </Tag>
            );
          })}
        </Space>
      )
    },
    {
      title: '归属部门',
      dataIndex: 'assigned_departments',
      key: 'assigned_departments',
      render: (depts) => (
        <Space size={[0, 4]} wrap>
          {(depts || []).map(dept => (
            <Tag color="cyan" key={dept}>{dept}</Tag>
          ))}
        </Space>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 90,
      render: (status) => {
        const statusMap = {
          pending: { color: 'gold', text: '待审核' },
          approved: { color: 'green', text: '已通过' },
          rejected: { color: 'red', text: '已驳回' },
        };
        const { color, text } = statusMap[status] || { color: 'default', text: status };
        return <Tag color={color}>{text}</Tag>;
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space>
          <Button size="small" icon={<EyeOutlined />} onClick={() => { setSelectedId(record.id); setDetailsVisible(true); }}>详情</Button>
          {(user.role === 'super_admin' || (user.role === 'user' && record.status === 'pending' && record.user_id === user.id)) && (
            <Button size="small" icon={<EditOutlined />} onClick={() => { setSelectedId(record.id); setEditVisible(true); }}>修改</Button>
          )}
          {canDeleteAchievement(record) && (
            <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
              <Button size="small" danger icon={<DeleteOutlined />}>删除</Button>
            </Popconfirm>
          )}
        </Space>
      ),
    }
  ];

  const handleDelete = async (id) => {
    try {
      const token = localStorage.getItem('token');
      await axios.delete(`${API_BASE_URL}/api/achievements/${id}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      message.success('删除成功');
      fetchDashboardData();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const buildExportParams = () => ({
    type: filterType || undefined,
    status: filterStatus || undefined,
    keyword: keyword || undefined,
    startDate: dateRange && dateRange[0] ? dateRange[0].format('YYYY-MM-DD') : undefined,
    endDate: dateRange && dateRange[1] ? dateRange[1].format('YYYY-MM-DD') : undefined
  });

  const downloadBlob = (blob, filename) => {
    const url = window.URL.createObjectURL(new Blob([blob]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);
  };

  const parseFilename = (contentDisposition, fallback) => {
    if (!contentDisposition) return fallback;
    const utf8Name = contentDisposition.match(/filename\\*=UTF-8''(.+)/);
    const normalName = contentDisposition.match(/filename="(.+)"/);
    if (utf8Name && utf8Name[1]) return decodeURIComponent(utf8Name[1]);
    if (normalName && normalName[1]) return normalName[1];
    return fallback;
  };

  const handleExportCsv = async () => {
    const hide = message.loading('正在导出 CSV...', 0);
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get(`${API_BASE_URL}/api/achievements/export/csv`, {
        headers: { Authorization: `Bearer ${token}` },
        params: buildExportParams(),
        responseType: 'blob'
      });
      const filename = parseFilename(response.headers['content-disposition'], 'achievements_export.csv');
      downloadBlob(response.data, filename);
      message.success('CSV 导出成功');
    } catch (error) {
      message.error('CSV 导出失败');
    } finally {
      hide();
    }
  };

  const handleExportZip = async () => {
    const hide = message.loading('正在导出 ZIP...', 0);
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get(`${API_BASE_URL}/api/achievements/export/zip`, {
        headers: { Authorization: `Bearer ${token}` },
        params: buildExportParams(),
        responseType: 'blob'
      });
      const filename = parseFilename(response.headers['content-disposition'], 'achievements_export.zip');
      downloadBlob(response.data, filename);
      message.success('ZIP 导出成功');
    } catch (error) {
      message.error('ZIP 导出失败');
    } finally {
      hide();
    }
  };

  const handleBatchDownloadForms = async () => {
    if (recentData.length === 0) {
      message.warning('当前列表没有数据可下载');
      return;
    }

    setBatchLoading(true);
    setBatchProgress({ current: 0, total: recentData.length });
    const zip = new JSZip();
    const token = localStorage.getItem('token');

    try {
      for (let i = 0; i < recentData.length; i++) {
        const item = recentData[i];
        setBatchProgress({ current: i + 1, total: recentData.length });
        
        // 1. 获取详情
        try {
          const response = await axios.get(`${API_BASE_URL}/api/achievements/${item.id}`, {
            headers: { Authorization: `Bearer ${token}` }
          });
          const detailData = response.data;
          
          // 2. 设置数据以触发渲染
          setBatchCurrentData(detailData);
          
          // 3. 等待渲染完成 (给 React 和 DOM 一点时间)
          await new Promise(resolve => setTimeout(resolve, 500));
          
          // 4. 截图
          const element = document.getElementById('batch-export-container');
          if (element) {
            const exportWidth = Math.max(element.scrollWidth, element.offsetWidth);
            const exportHeight = Math.max(element.scrollHeight, element.offsetHeight);
            const canvas = await html2canvas(element, {
              useCORS: true,
              scale: 2,
              backgroundColor: '#ffffff',
              width: exportWidth,
              height: exportHeight,
              windowWidth: exportWidth,
              windowHeight: exportHeight,
              scrollX: 0,
              scrollY: 0
            });
            
            // 5. 添加到 ZIP
            const imgData = canvas.toDataURL('image/png').split(',')[1];
            const fileName = `成果表单_${detailData.name || '未命名'}_${detailData.id}.png`;
            // 处理文件名中的非法字符
            const safeFileName = fileName.replace(/[\\/:*?"<>|]/g, '_');
            zip.file(safeFileName, imgData, { base64: true });
          }
        } catch (err) {
          console.error(`处理成果 ${item.id} 失败`, err);
          // 继续处理下一个，不中断
        }
      }

      // 6. 生成并下载 ZIP
      const content = await zip.generateAsync({ type: 'blob' });
      saveAs(content, `批量导出表单_${new Date().toISOString().slice(0,10)}.zip`);
      message.success('批量下载完成');
    } catch (error) {
      console.error(error);
      message.error('批量下载失败');
    } finally {
      setBatchLoading(false);
      setBatchCurrentData(null);
    }
  };

  return (
    <div>
      {/* 批量下载进度遮罩 */}
      <Modal
        open={batchLoading}
        footer={null}
        closable={false}
        centered
        maskClosable={false}
        title="正在批量生成表单图片"
      >
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Progress 
            type="circle" 
            percent={Math.round((batchProgress.current / batchProgress.total) * 100)} 
            format={() => `${batchProgress.current} / ${batchProgress.total}`}
          />
          <div style={{ marginTop: 20, color: '#666' }}>
            正在处理中，请勿关闭页面...<br/>
            此操作可能需要几分钟，请耐心等待。
          </div>
        </div>
      </Modal>

      {/* 隐藏的渲染容器 */}
      <div 
        id="batch-export-container" 
        style={{ 
          position: 'fixed', 
          left: '-100000px', 
          top: 0, 
          width: '1100px', 
          backgroundColor: '#fff', 
          padding: '40px',
          boxSizing: 'border-box',
          overflow: 'visible',
          zIndex: -1 
        }}
      >
        {batchCurrentData && (
          <>
            <div style={{ textAlign: 'center', marginBottom: '30px', borderBottom: '2px solid #1890ff', paddingBottom: '20px' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: '10px' }}>
                <img src="/logo.png" style={{ height: '50px', marginRight: '15px' }} onError={(e) => e.target.style.display='none'} alt="logo" />
                <h1 style={{ margin: 0, fontSize: '28px', fontWeight: 'bold', color: '#333', whiteSpace: 'normal', wordBreak: 'break-all', overflowWrap: 'anywhere' }}>科技成果管理表单</h1>
              </div>
              <div style={{ fontSize: '14px', color: '#666' }}>生成时间：{new Date().toLocaleString()}</div>
            </div>
            <AchievementFormRenderer data={batchCurrentData} />
          </>
        )}
      </div>

      <Card style={{ marginBottom: 24 }} bodyStyle={{ padding: '20px' }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '16px', justifyContent: 'space-between', alignItems: 'center' }}>
          <Space wrap size="middle" style={{ flex: 1 }}>
            <Input 
              prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
              placeholder="搜索名称/完成人/手机号" 
              style={{ width: 240 }} 
              value={keyword} 
              onChange={e => setKeyword(e.target.value)} 
              onPressEnter={fetchDashboardData} 
              allowClear 
            />
            <DatePicker.RangePicker style={{ width: 260 }} onChange={setDateRange} />
            <Select placeholder="按类型" style={{ width: 120 }} allowClear onChange={setFilterType}>
              <Select.Option value="paper">论文</Select.Option>
              <Select.Option value="project">项目</Select.Option>
              <Select.Option value="award">奖励</Select.Option>
              <Select.Option value="standard">标准</Select.Option>
              <Select.Option value="monograph">专著</Select.Option>
              <Select.Option value="report">技术报告</Select.Option>
              <Select.Option value="plan">规划</Select.Option>
              <Select.Option value="patent">专利</Select.Option>
              <Select.Option value="transformation">成果转化</Select.Option>
              <Select.Option value="software">软著</Select.Option>
            </Select>
            <Select placeholder="按状态" style={{ width: 120 }} allowClear onChange={setFilterStatus}>
              <Select.Option value="pending">待审核</Select.Option>
              <Select.Option value="approved">已通过</Select.Option>
              <Select.Option value="rejected">已驳回</Select.Option>
            </Select>
            <Button type="primary" icon={<SearchOutlined />} onClick={fetchDashboardData}>查询</Button>
          </Space>
          
          <Space>
            <Button icon={<PictureOutlined />} onClick={handleBatchDownloadForms} loading={batchLoading}>批量下载表单</Button>
            {user.role === 'super_admin' && (
              <>
                <Button icon={<FileTextOutlined />} onClick={handleExportCsv}>导出CSV</Button>
                <Button danger icon={<FileTextOutlined />} onClick={handleExportZip}>导出附件</Button>
              </>
            )}
          </Space>
        </div>
      </Card>

      <Row gutter={16}>
        <Col span={6}><Card><Statistic title="总成果数" value={stats.total} prefix={<FileTextOutlined />} /></Card></Col>
        <Col span={6}><Card><Statistic title="待审核" value={stats.pending} valueStyle={{ color: '#faad14' }} prefix={<ClockCircleOutlined />} /></Card></Col>
        <Col span={6}><Card><Statistic title="已通过" value={stats.approved} valueStyle={{ color: '#52c41a' }} prefix={<CheckCircleOutlined />} /></Card></Col>
        <Col span={6}><Card><Statistic title="已驳回" value={stats.rejected} valueStyle={{ color: '#f5222d' }} prefix={<CloseCircleOutlined />} /></Card></Col>
      </Row>

      <Card style={{ marginTop: 24 }} bodyStyle={{ padding: '24px' }}>
        <Tabs 
          type="card"
          activeKey={activeTab} 
          onChange={setActiveTab}
          tabBarStyle={{ marginBottom: 24 }}
          items={[
            {
              key: 'my',
              label: <span style={{ fontSize: '16px', padding: '4px 8px' }}><UserSwitchOutlined />我的成果</span>,
              children: <Table 
                columns={columns} 
                dataSource={recentData} 
                rowKey="id" 
                loading={loading} 
                pagination={{ pageSize: 10 }} 
                scroll={{ x: 1200 }} 
                rowClassName={(record) => {
                  const hasPendingContributor = (record.contributors || []).some(c => pendingUsers.has(c.phone));
                  if (record.has_data_issue || hasPendingContributor) return 'row-pending-issue';
                  return '';
                }}
              />
            },
            {
              key: 'public',
              label: <span style={{ fontSize: '16px', padding: '4px 8px' }}><GlobalOutlined />成果公示</span>,
              children: <Table 
                columns={columns} 
                dataSource={recentData} 
                rowKey="id" 
                loading={loading} 
                pagination={{ pageSize: 10 }} 
                scroll={{ x: 1200 }} 
                rowClassName={(record) => {
                  const hasPendingContributor = (record.contributors || []).some(c => pendingUsers.has(c.phone));
                  if (record.has_data_issue || hasPendingContributor) return 'row-pending-issue';
                  return '';
                }}
              />
            },
            ...(user.role === 'super_admin' ? [{
              key: 'all',
              label: <span style={{ fontSize: '16px', padding: '4px 8px' }}><FileTextOutlined />全部成果</span>,
              children: <Table 
                columns={columns} 
                dataSource={recentData} 
                rowKey="id" 
                loading={loading} 
                pagination={{ pageSize: 10 }} 
                scroll={{ x: 1200 }} 
                rowClassName={(record) => {
                  const hasPendingContributor = (record.contributors || []).some(c => pendingUsers.has(c.phone));
                  if (record.has_data_issue || hasPendingContributor) return 'row-pending-issue';
                  return '';
                }}
              />
            }] : [])
          ]}
        />
      </Card>

      <AchievementDetails id={selectedId} open={detailsVisible} onClose={() => { setDetailsVisible(false); setSelectedId(null); }} />
      <AchievementEdit id={selectedId} open={editVisible} onClose={() => { setEditVisible(false); setSelectedId(null); }} onSave={fetchDashboardData} />
      
      <style>{`
        .row-pending-issue {
          background-color: #ffccc7;
        }
        .row-pending-issue:hover > td {
          background-color: #ffa39e !important;
        }
      `}</style>
    </div>
  );
};

export default Dashboard;
