/**
 * 能耗管理页面
 * - 顶部数据卡片：今日/本月能耗、电费估算、在线柜子
 * - 柜子能耗排行表格
 * - 项目能耗统计表格
 * - 能耗/充电趋势图（日/周/月切换）
 * - 异步导出 Excel
 */

import { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Select,
  Message,
  Grid,
  Spin,
} from '@arco-design/web-react';
import { IconDownload } from '@arco-design/web-react/icon';
import {
  LineChart,
  BarChart,
  Line,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';
import { api } from '@/api/request';
import DownloadCenter from '../charge-records/DownloadCenter';

const Row = Grid.Row;
const Col = Grid.Col;

/** 总览数据 */
interface Summary {
  today_energy: number;
  month_energy: number;
  estimated_cost: number;
  cabinet_count: number;
  online_count: number;
}

/** 柜子排行项 */
interface CabinetRank {
  cabinet_id: number;
  abstract_id: string;
  name: string | null;
  today_energy: number;
  month_energy: number;
}

/** 项目统计项 */
interface ProjectStat {
  project_id: number;
  name: string;
  cabinet_count: number;
  today_energy: number;
  month_energy: number;
}

/** 趋势数据点 */
interface TrendPoint {
  period: string;
  energy: number;
  charge_count: number;
}

/** 趋势数据 */
interface TrendData {
  granularity: string;
  list: TrendPoint[];
}

export default function Energy() {
  // 总览
  const [summary, setSummary] = useState<Summary | null>(null);
  // 柜子排行
  const [cabinetRanking, setCabinetRanking] = useState<CabinetRank[]>([]);
  // 项目统计
  const [projectStats, setProjectStats] = useState<ProjectStat[]>([]);
  // 趋势
  const [trendData, setTrendData] = useState<TrendPoint[]>([]);
  const [granularity, setGranularity] = useState<string>('day');
  // 通用
  const [loading, setLoading] = useState(true);
  const [downloadVisible, setDownloadVisible] = useState(false);

  /** 加载总览 */
  const fetchSummary = useCallback(async () => {
    try {
      const res = await api.get<Summary>('/energy-stats/summary');
      setSummary(res.data);
    } catch {
      Message.error('加载总览数据失败');
    }
  }, []);

  /** 加载柜子排行 */
  const fetchCabinetRanking = useCallback(async () => {
    try {
      const res = await api.get<CabinetRank[]>('/energy-stats/cabinets');
      setCabinetRanking(res.data || []);
    } catch {
      Message.error('加载柜子排行失败');
    }
  }, []);

  /** 加载项目统计 */
  const fetchProjectStats = useCallback(async () => {
    try {
      const res = await api.get<ProjectStat[]>('/energy-stats/projects');
      setProjectStats(res.data || []);
    } catch {
      Message.error('加载项目统计失败');
    }
  }, []);

  /** 加载趋势 */
  const fetchTrend = useCallback(async () => {
    try {
      const res = await api.get<TrendData>(
        `/energy-stats/trend?granularity=${granularity}&range=30`
      );
      setTrendData(res.data.list || []);
    } catch {
      Message.error('加载趋势数据失败');
    }
  }, [granularity]);

  /** 初次加载全部数据 */
  useEffect(() => {
    setLoading(true);
    Promise.all([fetchSummary(), fetchCabinetRanking(), fetchProjectStats(), fetchTrend()])
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [fetchSummary, fetchCabinetRanking, fetchProjectStats, fetchTrend]);

  /** 粒度切换时重新加载趋势 */
  useEffect(() => {
    fetchTrend();
  }, [fetchTrend]);

  /** 导出 */
  const handleExport = async () => {
    try {
      await api.get('/energy-stats/export');
      Message.success('导出任务已创建，请到下载中心查看');
      setDownloadVisible(true);
    } catch {
      Message.error('创建导出任务失败');
    }
  };

  /** 格式化数字 */
  const fmt = (v: number | null | undefined, digits = 2): string => {
    if (v == null) return '-';
    return Number(v.toFixed(digits)).toLocaleString(undefined, {
      minimumFractionDigits: digits,
      maximumFractionDigits: digits,
    });
  };

  /** 柜子排行列定义 */
  const cabinetColumns = [
    {
      title: '柜子ID',
      dataIndex: 'abstract_id',
      width: 160,
      sorter: (a: CabinetRank, b: CabinetRank) =>
        a.abstract_id.localeCompare(b.abstract_id),
    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 160,
      render: (v: string | null) => v || '-',
    },
    {
      title: '今日能耗(kWh)',
      dataIndex: 'today_energy',
      width: 140,
      defaultSortOrder: 'descend' as const,
      sortable: true,
      sorter: (a: CabinetRank, b: CabinetRank) => a.today_energy - b.today_energy,
      render: (v: number) => fmt(v),
    },
    {
      title: '本月能耗(kWh)',
      dataIndex: 'month_energy',
      width: 140,
      sorter: (a: CabinetRank, b: CabinetRank) => a.month_energy - b.month_energy,
      render: (v: number) => fmt(v),
    },
  ];

  /** 项目统计列定义 */
  const projectColumns = [
    { title: '项目名称', dataIndex: 'name', width: 200 },
    {
      title: '柜子数',
      dataIndex: 'cabinet_count',
      width: 100,
      sorter: (a: ProjectStat, b: ProjectStat) => a.cabinet_count - b.cabinet_count,
    },
    {
      title: '今日能耗(kWh)',
      dataIndex: 'today_energy',
      width: 140,
      defaultSortOrder: 'descend' as const,
      sortable: true,
      sorter: (a: ProjectStat, b: ProjectStat) => a.today_energy - b.today_energy,
      render: (v: number) => fmt(v),
    },
    {
      title: '本月能耗(kWh)',
      dataIndex: 'month_energy',
      width: 140,
      sorter: (a: ProjectStat, b: ProjectStat) => a.month_energy - b.month_energy,
      render: (v: number) => fmt(v),
    },
  ];

  /** 自定义图表 Tooltip 样式 */
  const chartTooltipStyle = {
    backgroundColor: 'var(--color-bg-5)',
    border: '1px solid var(--color-border-2)',
    borderRadius: 6,
    padding: '8px 12px',
  };

  return (
    <Spin loading={loading} style={{ width: '100%' }}>
      {/* 顶部数据卡片 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card>
            <div style={{ textAlign: 'center', padding: '8px 0' }}>
              <div style={{ fontSize: 14, color: 'var(--color-text-2)', marginBottom: 8 }}>
                今日能耗
              </div>
              <div
                style={{
                  fontSize: 28,
                  fontWeight: 600,
                  color: 'var(--color-text-1)',
                }}
              >
                {summary ? `${fmt(summary.today_energy)} kWh` : '-'}
              </div>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ textAlign: 'center', padding: '8px 0' }}>
              <div style={{ fontSize: 14, color: 'var(--color-text-2)', marginBottom: 8 }}>
                本月能耗
              </div>
              <div
                style={{
                  fontSize: 28,
                  fontWeight: 600,
                  color: 'var(--color-text-1)',
                }}
              >
                {summary ? `${fmt(summary.month_energy)} kWh` : '-'}
              </div>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ textAlign: 'center', padding: '8px 0' }}>
              <div style={{ fontSize: 14, color: 'var(--color-text-2)', marginBottom: 8 }}>
                电费估算
              </div>
              <div
                style={{
                  fontSize: 28,
                  fontWeight: 600,
                  color: 'rgb(var(--green-6))',
                }}
              >
                {summary ? `¥${fmt(summary.estimated_cost)}` : '-'}
              </div>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <div style={{ textAlign: 'center', padding: '8px 0' }}>
              <div style={{ fontSize: 14, color: 'var(--color-text-2)', marginBottom: 8 }}>
                在线柜子
              </div>
              <div
                style={{
                  fontSize: 28,
                  fontWeight: 600,
                  color: 'var(--color-text-1)',
                }}
              >
                {summary
                  ? `${summary.online_count} / ${summary.cabinet_count}`
                  : '-'}
              </div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 柜子能耗排行 + 导出 */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={12}>
          <Card title="柜子能耗排行" extra={
            <Button icon={<IconDownload />} onClick={handleExport}>
              导出报表
            </Button>
          }>
            <Table
              rowKey="cabinet_id"
              columns={cabinetColumns}
              data={cabinetRanking}
              pagination={{ pageSize: 10, showTotal: true }}
              size="default"
            />
          </Card>
        </Col>
        <Col span={12}>
          <Card title="项目能耗统计">
            <Table
              rowKey="project_id"
              columns={projectColumns}
              data={projectStats}
              pagination={{ pageSize: 10, showTotal: true }}
              size="default"
            />
          </Card>
        </Col>
      </Row>

      {/* 趋势图 */}
      <Card
        title="能耗趋势"
        extra={
          <Select
            value={granularity}
            onChange={(val) => setGranularity(val as string)}
            style={{ width: 120 }}
            options={[
              { label: '按日', value: 'day' },
              { label: '按周', value: 'week' },
              { label: '按月', value: 'month' },
            ]}
          />
        }
      >
        <Space direction="vertical" style={{ width: '100%' }}>
          {/* 能耗折线图 */}
          <div style={{ width: '100%', height: 280 }}>
            <ResponsiveContainer>
              <LineChart
                data={trendData}
                margin={{ top: 8, right: 24, left: 8, bottom: 8 }}
              >
                <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border-2)" />
                <XAxis
                  dataKey="period"
                  tick={{ fontSize: 12 }}
                  stroke="var(--color-text-3)"
                />
                <YAxis
                  tick={{ fontSize: 12 }}
                  stroke="var(--color-text-3)"
                  label={{
                    value: 'kWh',
                    position: 'insideTopLeft',
                    offset: -4,
                    style: { fontSize: 12, fill: 'var(--color-text-3)' },
                  }}
                />
                <Tooltip
                  contentStyle={chartTooltipStyle}
                  formatter={(value) => [`${fmt(typeof value === 'number' ? value : 0)} kWh`, '能耗']}
                />
                <Legend />
                <Line
                  type="monotone"
                  dataKey="energy"
                  name="能耗(kWh)"
                  stroke="rgb(var(--primary-6))"
                  strokeWidth={2}
                  dot={{ r: 3 }}
                  activeDot={{ r: 5 }}
                />
              </LineChart>
            </ResponsiveContainer>
          </div>

          {/* 充电次数柱状图 */}
          <div style={{ width: '100%', height: 220 }}>
            <ResponsiveContainer>
              <BarChart
                data={trendData}
                margin={{ top: 8, right: 24, left: 8, bottom: 8 }}
              >
                <CartesianGrid strokeDasharray="3 3" stroke="var(--color-border-2)" />
                <XAxis
                  dataKey="period"
                  tick={{ fontSize: 12 }}
                  stroke="var(--color-text-3)"
                />
                <YAxis
                  tick={{ fontSize: 12 }}
                  stroke="var(--color-text-3)"
                  label={{
                    value: '次',
                    position: 'insideTopLeft',
                    offset: -4,
                    style: { fontSize: 12, fill: 'var(--color-text-3)' },
                  }}
                />
                <Tooltip
                  contentStyle={chartTooltipStyle}
                  formatter={(value) => [`${value ?? 0} 次`, '充电次数']}
                />
                <Legend />
                <Bar
                  dataKey="charge_count"
                  name="充电次数"
                  fill="rgb(var(--green-6))"
                  radius={[4, 4, 0, 0]}
                />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </Space>
      </Card>

      {/* 下载中心弹窗 */}
      <DownloadCenter
        visible={downloadVisible}
        onClose={() => setDownloadVisible(false)}
      />
    </Spin>
  );
}
