import React, { useEffect, useRef, useState } from 'react';
import { Alert, Button, Card, Col, Input, message, Radio, Row, Select, Slider, Space, Spin, Switch, Table, Tag, Typography } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import {
  Area,
  Bar,
  BarChart,
  Brush,
  CartesianGrid,
  Cell,
  ComposedChart,
  Legend,
  Line,
  Pie,
  PieChart,
  PolarAngleAxis,
  PolarGrid,
  PolarRadiusAxis,
  Radar,
  RadarChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis
} from 'recharts';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import axios from 'axios';
import API_BASE_URL from '../config';

const { Title } = Typography;
const { Option } = Select;

const TYPE_MAP = {
  paper: '论文',
  project: '项目',
  award: '奖励',
  standard: '标准',
  monograph: '专著',
  report: '技术报告',
  plan: '规划',
  patent: '专利',
  transformation: '成果转化',
  software: '软著'
};

const STATUS_MAP = {
  pending: '待审核',
  approved: '已通过',
  rejected: '已驳回'
};

const AI_MODE_MAP = {
  standard: '标准模式（仅聚合）',
  deep: '深度模式（含成果名称样本）'
};

const AI_PROVIDER_MAP = {
  deepseek: 'DeepSeek'
};

const ChartContainer = ({ height, minHeight, children }) => {
  const containerRef = useRef(null);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    const el = containerRef.current;
    if (!el) return undefined;

    const refresh = () => {
      const rect = el.getBoundingClientRect();
      setReady(rect.width > 0 && rect.height > 0);
    };
    refresh();

    let observer = null;
    if (typeof ResizeObserver !== 'undefined') {
      observer = new ResizeObserver(refresh);
      observer.observe(el);
    } else {
      const timer = setInterval(refresh, 150);
      return () => clearInterval(timer);
    }

    return () => {
      if (observer) observer.disconnect();
    };
  }, []);

  return (
    <div ref={containerRef} style={{ width: '100%', height, minHeight }}>
      {ready ? (
        <ResponsiveContainer width="100%" height="100%" minWidth={0} minHeight={minHeight}>
          {children}
        </ResponsiveContainer>
      ) : (
        <div style={{ width: '100%', height: '100%' }} />
      )}
    </div>
  );
};

const Statistics = () => {
  const currentUser = (() => {
    try {
      return JSON.parse(localStorage.getItem('user') || '{}');
    } catch (e) {
      return {};
    }
  })();

  const canUseAi = ['admin', 'super_admin', 'senior_user', 'intermediate_user'].includes(currentUser?.role);

  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(null);

  const [pieYear, setPieYear] = useState('all');
  const [radarYear, setRadarYear] = useState('all');
  const [barYear, setBarYear] = useState('all');
  const [trendMode, setTrendMode] = useState('month');

  const [viewMode, setViewMode] = useState('chart');
  const [detailTitle, setDetailTitle] = useState('');
  const [detailLoading, setDetailLoading] = useState(false);
  const [detailList, setDetailList] = useState([]);

  const [aiLoading, setAiLoading] = useState(false);
  const [aiMode, setAiMode] = useState('standard');
  const [aiNameLimit, setAiNameLimit] = useState(100);
  const [aiNameStrategy, setAiNameStrategy] = useState('latest');
  const [aiQuestion, setAiQuestion] = useState('请从成果结构、部门差异、风险点和改进优先级四个方面给出分析建议。');
  const [aiResult, setAiResult] = useState('');
  const [aiMeta, setAiMeta] = useState(null);
  const aiAbortRef = useRef(null);
  const [aiFilters, setAiFilters] = useState({ year: 'all', type: 'all', status: 'all', department: 'all' });

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      try {
        const token = localStorage.getItem('token');
        const resp = await axios.get(`${API_BASE_URL}/api/statistics`, { headers: { Authorization: `Bearer ${token}` } });
        setData(resp.data);
      } catch (e) {
        message.error('获取统计数据失败');
      } finally {
        setLoading(false);
      }
    };
    load();
  }, []);

  const generateColor = (index) => `hsl(${(index * 137.508) % 360}, 65%, 40%)`;

  const years = data
    ? [...new Set((data.deptTypeDetails || []).map((item) => item.year))].filter(Boolean).sort((a, b) => b - a)
    : [];
  const departments = data
    ? [...new Set((data.byDepartment || []).map((item) => item.department).filter(Boolean))]
    : [];

  const inferYearFromQuestion = (text) => {
    const q = String(text || '').trim();
    if (!q) return null;
    const currentYear = new Date().getFullYear();
    if (/(今年|本年|当年)/.test(q)) return currentYear;
    if (/(去年|上年|上一年)/.test(q)) return currentYear - 1;
    if (/(明年|下年|下一年)/.test(q)) return currentYear + 1;

    const yearMatches = Array.from(q.matchAll(/(?:19|20|21)\d{2}/g))
      .map((m) => Number(m[0]))
      .filter((y) => y >= 2000 && y <= currentYear + 100);
    if (yearMatches.length === 0) return null;

    const uniqueYears = Array.from(new Set(yearMatches));
    if (uniqueYears.length === 1) return uniqueYears[0];
    if (/[-~至到]/.test(q)) return Math.max(...uniqueYears);
    return null;
  };

  const syncChartsByYear = (yearValue) => {
    const y = String(yearValue || 'all');
    setPieYear(y);
    setRadarYear(y);
    setBarYear(y);
  };

  const handleAiYearChange = (value) => {
    const y = String(value || 'all');
    setAiFilters((prev) => ({ ...prev, year: y }));
    syncChartsByYear(y);
  };

  const pieData = (() => {
    if (!data) return [];
    const m = {};
    (data.deptTypeDetails || []).forEach((item) => {
      if (pieYear !== 'all' && String(item.year) !== String(pieYear)) return;
      if (!m[item.department]) m[item.department] = { name: item.department, value: 0 };
      m[item.department].value += Number(item.count) || 0;
    });
    return Object.values(m).sort((a, b) => b.value - a.value);
  })();
  const pieColors = pieData.map((_, i) => generateColor(i));

  const radarData = (() => {
    if (!data) return [];
    const m = {};
    (data.deptTypeDetails || []).forEach((item) => {
      if (radarYear !== 'all' && String(item.year) !== String(radarYear)) return;
      if (!m[item.type]) m[item.type] = { typeKey: item.type, name: TYPE_MAP[item.type] || item.type, value: 0 };
      m[item.type].value += Number(item.count) || 0;
    });
    Object.keys(TYPE_MAP).forEach((k) => {
      if (!m[k]) m[k] = { typeKey: k, name: TYPE_MAP[k], value: 0 };
    });
    return Object.values(m).sort((a, b) => a.value - b.value);
  })();

  const barData = (() => {
    if (!data) return [];
    const m = {};
    (data.deptTypeDetails || []).forEach((item) => {
      if (barYear !== 'all' && String(item.year) !== String(barYear)) return;
      if (!m[item.department]) m[item.department] = { name: item.department, total: 0 };
      const key = TYPE_MAP[item.type] || item.type;
      const count = Number(item.count) || 0;
      m[item.department][key] = (m[item.department][key] || 0) + count;
      m[item.department].total += count;
    });
    return Object.values(m).sort((a, b) => b.total - a.total);
  })();

  const allTypes = Object.values(TYPE_MAP);
  const typeColorMap = {};
  allTypes.forEach((k, i) => { typeColorMap[k] = generateColor(i); });

  const trendData = (() => {
    if (!data || !data.byMonth || data.byMonth.length === 0) return [];

    const monthSet = new Set();
    (data.byMonth || []).forEach((item) => monthSet.add(item.month));
    (data.deptTrendDetails || []).forEach((item) => monthSet.add(item.month));
    const months = Array.from(monthSet).sort();
    if (months.length === 0) return [];

    const startMonth = months[0];
    const endMonth = months[months.length - 1];
    const fullMonths = [];
    let [curY, curM] = startMonth.split('-').map(Number);
    const [endY, endM] = endMonth.split('-').map(Number);
    while (curY < endY || (curY === endY && curM <= endM)) {
      fullMonths.push(`${curY}-${String(curM).padStart(2, '0')}`);
      curM += 1;
      if (curM > 12) {
        curM = 1;
        curY += 1;
      }
    }

    const incrementMap = {};
    fullMonths.forEach((m) => { incrementMap[m] = { 全单位: 0 }; });
    (data.byMonth || []).forEach((item) => { if (incrementMap[item.month]) incrementMap[item.month].全单位 = Number(item.count) || 0; });
    (data.deptTrendDetails || []).forEach((item) => { if (incrementMap[item.month]) incrementMap[item.month][item.department] = Number(item.count) || 0; });

    const deptKeys = [...new Set((data.deptTrendDetails || []).map((item) => item.department))];
    const cumulative = { 全单位: 0 };
    deptKeys.forEach((d) => { cumulative[d] = 0; });

    let result = fullMonths.map((m) => {
      const entry = { name: m, rawMonth: m };
      const increments = incrementMap[m] || {};
      cumulative.全单位 += increments.全单位 || 0;
      entry.全单位 = cumulative.全单位;
      deptKeys.forEach((d) => {
        cumulative[d] += increments[d] || 0;
        entry[d] = cumulative[d];
      });
      return entry;
    });

    if (trendMode === 'year') {
      const yearMap = {};
      result.forEach((item) => { yearMap[item.name.slice(0, 4)] = { ...item, name: item.name.slice(0, 4) }; });
      result = Object.values(yearMap).sort((a, b) => a.name.localeCompare(b.name));
    }
    return result;
  })();

  const allDepts = data ? [...new Set((data.deptTrendDetails || []).map((item) => item.department))] : [];
  const deptColorMap = {};
  allDepts.forEach((d, i) => { deptColorMap[d] = generateColor(i + 5); });

  const fetchDetailList = async ({ department, type, year }) => {
    setViewMode('list');
    setDetailLoading(true);
    setDetailList([]);

    const params = {};
    if (department) params.department = department;
    if (type) params.type = type;
    if (year && year !== 'all') {
      params.startDate = `${year}-01-01`;
      params.endDate = `${year}-12-31`;
    }

    try {
      const token = localStorage.getItem('token');
      const resp = await axios.get(`${API_BASE_URL}/api/achievements`, { params, headers: { Authorization: `Bearer ${token}` } });
      setDetailList(resp.data);
    } catch (e) {
      message.error('获取成果列表失败');
    } finally {
      setDetailLoading(false);
    }
  };

  const handlePieClick = (entry) => {
    if (!entry) return;
    setDetailTitle(`${entry.name} 成果列表 ${pieYear !== 'all' ? `(${pieYear}年)` : ''}`);
    fetchDetailList({ department: entry.name, year: pieYear });
  };

  const handleRadarClick = (eventData) => {
    if (!eventData) return;
    let item = null;
    if (eventData.payload && eventData.payload.value && !eventData.payload.typeKey) item = radarData.find((d) => d.name === eventData.payload.value);
    else if (eventData.payload && eventData.payload.typeKey) item = eventData.payload;
    else if (eventData.typeKey) item = eventData;
    else if (eventData.activePayload && eventData.activePayload.length > 0) item = eventData.activePayload[0].payload;

    if (item?.typeKey) {
      setDetailTitle(`${item.name} 列表 ${radarYear !== 'all' ? `(${radarYear}年)` : ''}`);
      fetchDetailList({ type: item.typeKey, year: radarYear });
    }
  };

  const handleBack = () => {
    setViewMode('chart');
    setDetailList([]);
  };

  const handleAiAnalyze = async () => {
    if (!canUseAi) {
      message.warning('当前账号无权使用 AI 分析');
      return;
    }
    if (aiLoading) return;

    let requestFilters = { ...aiFilters };
    const selectedYear = String(aiFilters?.year || 'all');
    if (selectedYear !== 'all') {
      syncChartsByYear(selectedYear);
    } else {
      const inferredYear = inferYearFromQuestion(aiQuestion);
      if (inferredYear) {
        const y = String(inferredYear);
        requestFilters = { ...requestFilters, year: y };
        setAiFilters((prev) => ({ ...prev, year: y }));
        syncChartsByYear(y);
        message.info(`已识别提问中的年份：${y}年，图表已自动切换。`);
      }
    }

    setAiLoading(true);
    setAiResult('');
    setAiMeta(null);
    try {
      const token = localStorage.getItem('token');
      const controller = new AbortController();
      aiAbortRef.current = controller;

      const resp = await fetch(`${API_BASE_URL}/api/ai-analysis/achievements/stream`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({
          provider: 'deepseek',
          question: aiQuestion,
          filters: requestFilters,
          mode: aiMode,
          nameLimit: aiMode === 'deep' ? aiNameLimit : undefined,
          nameStrategy: aiMode === 'deep' ? aiNameStrategy : undefined
        }),
        signal: controller.signal
      });

      if (!resp.ok) {
        let errMessage = 'AI 分析请求失败';
        try {
          const errJson = await resp.json();
          errMessage = errJson?.message || errMessage;
        } catch (e) {
          // ignore parse failure
        }
        throw new Error(errMessage);
      }

      const reader = resp.body?.getReader();
      if (!reader) throw new Error('当前环境不支持流式读取');
      const decoder = new TextDecoder('utf-8');
      let buffer = '';

      const processSseBlock = (block) => {
        const lines = block.split('\n');
        let eventName = 'message';
        const dataLines = [];
        lines.forEach((line) => {
          const clean = line.trimEnd();
          if (clean.startsWith('event:')) eventName = clean.slice(6).trim();
          else if (clean.startsWith('data:')) dataLines.push(clean.slice(5).trim());
        });
        if (dataLines.length === 0) return;

        let payload = {};
        const dataText = dataLines.join('\n');
        try { payload = JSON.parse(dataText); } catch (e) { payload = { message: dataText }; }

        if (eventName === 'token') {
          const delta = String(payload?.content || '');
          if (delta) setAiResult((prev) => `${prev}${delta}`);
          return;
        }
        if (eventName === 'meta') {
          setAiMeta((prev) => ({
            ...(prev || {}),
            provider: payload?.provider || prev?.provider,
            model: payload?.model || prev?.model,
            generatedAt: payload?.generatedAt || prev?.generatedAt || new Date().toISOString()
          }));
          return;
        }
        if (eventName === 'done') {
          setAiMeta((prev) => ({
            ...(prev || {}),
            provider: payload?.provider || prev?.provider,
            model: payload?.model || prev?.model,
            generatedAt: payload?.generatedAt || prev?.generatedAt || new Date().toISOString(),
            triedProviders: payload?.triedProviders || prev?.triedProviders,
            summary: payload?.datasetSummary || prev?.summary,
            protection: payload?.protection || prev?.protection,
            mode: payload?.mode || prev?.mode,
            nameSamples: payload?.nameSamples || prev?.nameSamples
          }));
          return;
        }
        if (eventName === 'error') throw new Error(payload?.message || 'AI 分析服务异常');
      };

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        buffer += decoder.decode(value, { stream: true }).replace(/\r/g, '');
        let splitIndex = buffer.indexOf('\n\n');
        while (splitIndex !== -1) {
          processSseBlock(buffer.slice(0, splitIndex));
          buffer = buffer.slice(splitIndex + 2);
          splitIndex = buffer.indexOf('\n\n');
        }
      }
      if (buffer.trim()) processSseBlock(buffer);
      message.success('AI 分析已生成');
    } catch (e) {
      if (e?.name === 'AbortError') message.info('已停止并清空输出');
      else message.error(e?.message || 'AI 分析失败');
    } finally {
      aiAbortRef.current = null;
      setAiLoading(false);
    }
  };

  const handleClearAiOutput = () => {
    if (aiAbortRef.current) {
      aiAbortRef.current.abort();
      aiAbortRef.current = null;
    }
    setAiResult('');
    setAiMeta(null);
    setAiMode('standard');
    setAiNameLimit(100);
    setAiNameStrategy('latest');
    setAiFilters({ year: 'all', type: 'all', status: 'all', department: 'all' });
    syncChartsByYear('all');
  };

  const detailColumns = [
    { title: '成果名称', dataIndex: 'name', key: 'name', ellipsis: true },
    { title: '主要完成人', dataIndex: 'main_contributors', key: 'main_contributors', ellipsis: true },
    { title: '归属部门', dataIndex: 'assigned_departments', key: 'assigned_departments', render: (v) => (v ? v.join(', ') : '-') },
    { title: '日期', dataIndex: 'achievement_date', key: 'achievement_date', width: 120, render: (v) => (v ? new Date(v).toLocaleDateString() : '-') },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => <Tag color={{ pending: 'orange', approved: 'green', rejected: 'red' }[status]}>{STATUS_MAP[status]}</Tag>
    }
  ];

  if (loading || !data) {
    return <div style={{ textAlign: 'center', padding: '50px' }}><Spin size="large" /></div>;
  }

  if (viewMode === 'list') {
    return (
      <div style={{ padding: 24 }}>
        <div style={{ marginBottom: 24, display: 'flex', alignItems: 'center' }}>
          <Button icon={<ArrowLeftOutlined />} onClick={handleBack} style={{ marginRight: 16 }}>返回</Button>
          <Title level={2} style={{ margin: 0 }}>{detailTitle}</Title>
        </div>
        <Card variant="borderless">
          <Table columns={detailColumns} dataSource={detailList} rowKey="id" loading={detailLoading} pagination={{ pageSize: 10 }} />
        </Card>
      </div>
    );
  }

  return (
    <div style={{ padding: 24 }}>
      <Title level={2} style={{ marginBottom: 32 }}>统计分析看板</Title>
      <Alert
        type="warning"
        showIcon
        message="统计口径说明：部门相关统计已排除院领导部门；每条成果仅归属一个部门（优先首个非院领导部门，否则回退首个部门）。"
        style={{ marginBottom: 16 }}
      />

      <Row gutter={[24, 24]}>
        {canUseAi && (
          <Col span={24}>
            <Card title="AI 智能分析（DeepSeek）" variant="borderless">
              <Alert
                type="info"
                showIcon
                message={aiMode === 'deep'
                  ? '深度模式：发送聚合统计 + 成果名称样本（不发送个人手机号、贡献者姓名、附件内容/路径/文件名）。'
                  : '标准模式：仅发送脱敏聚合统计数据（不发送成果名称、个人手机号、贡献者姓名、附件内容/路径/文件名）。'}
                style={{ marginBottom: 16 }}
              />

              <Row gutter={[12, 12]} style={{ marginBottom: 12 }}>
                <Col xs={24} sm={12} md={6}>
                  <Select value={aiMode} style={{ width: '100%' }} onChange={setAiMode}>
                    {Object.keys(AI_MODE_MAP).map((key) => <Option key={key} value={key}>{AI_MODE_MAP[key]}</Option>)}
                  </Select>
                </Col>
                {aiMode === 'deep' && (
                  <Col xs={24} sm={24} md={8}>
                    <div style={{ color: '#666', fontSize: 12, marginBottom: 6 }}>名称样本数量：{aiNameLimit}</div>
                    <Slider min={20} max={300} step={10} value={aiNameLimit} marks={{ 20: '20', 100: '100', 200: '200', 300: '300' }} onChange={(v) => { if (!Array.isArray(v)) setAiNameLimit(v); }} />
                  </Col>
                )}
                {aiMode === 'deep' && (
                  <Col xs={24} sm={12} md={4}>
                    <div style={{ color: '#666', fontSize: 12, marginBottom: 6 }}>类型均衡策略（关=最新优先）</div>
                    <Switch checked={aiNameStrategy === 'balanced'} onChange={(checked) => setAiNameStrategy(checked ? 'balanced' : 'latest')} checkedChildren="开" unCheckedChildren="关" />
                  </Col>
                )}
                <Col xs={24} sm={12} md={4}>
                  <Select value={aiFilters.year} style={{ width: '100%' }} onChange={handleAiYearChange}>
                    <Option value="all">全部年份</Option>
                    {years.map((y) => <Option key={y} value={String(y)}>{y}年</Option>)}
                  </Select>
                </Col>
                <Col xs={24} sm={12} md={4}>
                  <Select value={aiFilters.type} style={{ width: '100%' }} onChange={(v) => setAiFilters((prev) => ({ ...prev, type: v }))}>
                    <Option value="all">全部类型</Option>
                    {Object.keys(TYPE_MAP).map((k) => <Option key={k} value={k}>{TYPE_MAP[k]}</Option>)}
                  </Select>
                </Col>
                <Col xs={24} sm={12} md={4}>
                  <Select value={aiFilters.status} style={{ width: '100%' }} onChange={(v) => setAiFilters((prev) => ({ ...prev, status: v }))}>
                    <Option value="all">全部状态</Option>
                    {Object.keys(STATUS_MAP).map((k) => <Option key={k} value={k}>{STATUS_MAP[k]}</Option>)}
                  </Select>
                </Col>
                <Col xs={24} sm={12} md={4}>
                  <Select value={aiFilters.department} style={{ width: '100%' }} onChange={(v) => setAiFilters((prev) => ({ ...prev, department: v }))}>
                    <Option value="all">全部部门</Option>
                    {departments.map((d) => <Option key={d} value={d}>{d}</Option>)}
                  </Select>
                </Col>
              </Row>

              <Input.TextArea rows={4} maxLength={600} value={aiQuestion} onChange={(e) => setAiQuestion(e.target.value)} placeholder="请描述你要分析的角度，例如：2025年哪个部门成果增长最快，下一步改进重点是什么？" />
              <Space style={{ marginTop: 12, marginBottom: 12 }}>
                <Button type="primary" loading={aiLoading} onClick={handleAiAnalyze}>开始 AI 分析</Button>
                <Button onClick={handleClearAiOutput}>停止并清空</Button>
              </Space>

              {aiMeta && (
                <div style={{ color: '#666', marginBottom: 12, fontSize: 12 }}>
                  提供方：{AI_PROVIDER_MAP[aiMeta.provider] || aiMeta.provider || '-'} | 模型：{aiMeta.model || '-'} | 生成时间：{aiMeta.generatedAt ? new Date(aiMeta.generatedAt).toLocaleString() : '-'} | 模式：{aiMeta.mode === 'deep' ? '深度' : '标准'}
                  {aiMeta?.nameSamples?.mode === 'deep' ? ` | 名称样本：${aiMeta?.nameSamples?.sent || 0}/${aiMeta?.nameSamples?.total || 0}${aiMeta?.nameSamples?.truncated ? '（已截断）' : ''}` : ''}
                  {aiMeta?.nameSamples?.mode === 'deep' ? ` | 策略：${aiMeta?.nameSamples?.strategy === 'balanced' ? '类型均衡' : '最新优先'}` : ''}
                  {Array.isArray(aiMeta?.triedProviders) && aiMeta.triedProviders.length > 0 ? ` | 尝试顺序：${aiMeta.triedProviders.join(' -> ')}` : ''}
                </div>
              )}

              {aiResult && (
                <Card size="small" title="AI 分析结果">
                  <div style={{ lineHeight: 1.8, wordBreak: 'break-word' }}>
                    <ReactMarkdown remarkPlugins={[remarkGfm]}>{aiResult}</ReactMarkdown>
                  </div>
                </Card>
              )}
            </Card>
          </Col>
        )}

        <Col span={12} style={{ minWidth: 0 }}>
          <Card
            title={<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><span>部门成果占比（饼图）</span><Select value={pieYear} size="small" style={{ width: 100 }} onChange={(v) => setPieYear(String(v))}><Option value="all">全部年份</Option>{years.map((y) => <Option key={y} value={String(y)}>{y}年</Option>)}</Select></div>}
            variant="borderless"
          >
            <ChartContainer height={300} minHeight={240}>
              <PieChart>
                <Pie data={pieData} cx="50%" cy="50%" labelLine label={({ name, percent }) => `${name} (${(percent * 100).toFixed(0)}%)`} outerRadius={80} fill="#8884d8" dataKey="value" onClick={handlePieClick} style={{ cursor: 'pointer' }}>
                  {pieData.map((entry, index) => <Cell key={`cell-${index}`} fill={pieColors[index % pieColors.length]} style={{ cursor: 'pointer' }} />)}
                </Pie>
                <Tooltip />
                <Legend />
              </PieChart>
            </ChartContainer>
          </Card>
        </Col>

        <Col span={12} style={{ minWidth: 0 }}>
          <Card
            title={<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><span>成果类型分布（雷达图）</span><Select value={radarYear} size="small" style={{ width: 100 }} onChange={(v) => setRadarYear(String(v))}><Option value="all">全部年份</Option>{years.map((y) => <Option key={y} value={String(y)}>{y}年</Option>)}</Select></div>}
            variant="borderless"
          >
            <ChartContainer height={300} minHeight={240}>
              <RadarChart cx="50%" cy="50%" outerRadius="80%" data={radarData} onClick={handleRadarClick}>
                <defs>
                  <linearGradient id="radarGradient" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#1890ff" stopOpacity={0.8} />
                    <stop offset="95%" stopColor="#1890ff" stopOpacity={0.1} />
                  </linearGradient>
                </defs>
                <PolarGrid stroke="#e8e8e8" />
                <PolarAngleAxis dataKey="name" onClick={(payload) => handleRadarClick({ payload })} style={{ cursor: 'pointer', fontSize: 12, fontWeight: 'bold' }} tick={{ fill: '#666' }} />
                <PolarRadiusAxis angle={30} domain={[0, 'auto']} tick={false} axisLine={false} />
                <Radar name="成果类型数量" dataKey="value" stroke="#1890ff" strokeWidth={2} fill="url(#radarGradient)" fillOpacity={0.6} isAnimationActive={false} onClick={handleRadarClick} style={{ cursor: 'pointer' }} />
                <Tooltip contentStyle={{ borderRadius: 8, border: 'none', boxShadow: '0 2px 8px rgba(0,0,0,0.15)' }} itemStyle={{ color: '#1890ff' }} />
              </RadarChart>
            </ChartContainer>
          </Card>
        </Col>

        <Col span={24} style={{ minWidth: 0 }}>
          <Card
            title={<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><span>各部门成果种类统计</span><Select value={barYear} style={{ width: 120 }} onChange={(v) => setBarYear(String(v))}><Option value="all">全部年份</Option>{years.map((y) => <Option key={y} value={String(y)}>{y}年</Option>)}</Select></div>}
            variant="borderless"
          >
            <div style={{ width: '100%', overflowX: 'auto' }}>
              <div style={{ minWidth: '100%', width: barData.length > 8 ? barData.length * 100 : '100%' }}>
                <ChartContainer height={400} minHeight={280}>
                  <BarChart data={barData} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    {allTypes.map((name) => <Bar key={name} dataKey={name} fill={typeColorMap[name]} />)}
                  </BarChart>
                </ChartContainer>
              </div>
            </div>
          </Card>
        </Col>

        <Col span={24} style={{ minWidth: 0 }}>
          <Card
            title={<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><span>累计成果与部门趋势（按月/按年）</span><Radio.Group value={trendMode} onChange={(e) => setTrendMode(e.target.value)} buttonStyle="solid"><Radio.Button value="month">按月</Radio.Button><Radio.Button value="year">按年</Radio.Button></Radio.Group></div>}
            variant="borderless"
          >
            <div style={{ width: '100%' }}>
              {trendData.length > 0 ? (
                <ChartContainer height={400} minHeight={280}>
                  <ComposedChart data={trendData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis yAxisId="left" label={{ value: '累计成果总量', angle: -90, position: 'insideLeft' }} />
                    <YAxis yAxisId="right" orientation="right" label={{ value: '部门累计数量', angle: 90, position: 'insideRight' }} />
                    <Tooltip />
                    <Legend />
                    <Brush dataKey="name" height={30} stroke="#8884d8" startIndex={trendMode === 'month' && trendData.length > 12 ? trendData.length - 12 : 0} />
                    <Area type="monotone" dataKey="全单位" fill="#f0f0f0" stroke="#8884d8" yAxisId="left" />
                    {allDepts.map((dept) => <Line key={dept} type="monotone" dataKey={dept} stroke={deptColorMap[dept]} strokeWidth={2} dot={false} yAxisId="right" />)}
                  </ComposedChart>
                </ChartContainer>
              ) : (
                <div style={{ height: 400, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>暂无数据</div>
              )}
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Statistics;
