/**
 * 充电记录页面
 * - 顶部过滤：柜子/仓板/通道级联下拉 + 时间范围
 * - 列表：分页展示充电记录
 * - 导出：异步导出 + 下载中心弹窗
 */

import { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Select,
  DatePicker,
  Tag,
  Message,
} from '@arco-design/web-react';
import { IconDownload, IconSearch } from '@arco-design/web-react/icon';
import { api } from '@/api/request';
import DownloadCenter from './DownloadCenter';

const { RangePicker } = DatePicker;

/** 充电记录项 */
interface ChargeRecord {
  id: number;
  cabinet_id: number;
  cabinet_name: string | null;
  cabin_board_id: number;
  board_id: number;
  compartment_id: number;
  channel_id: number;
  start_time: string | null;
  end_time: string | null;
  energy: number | null;
  max_temperature: number | null;
  status: number;
  status_text: string;
}

/** 下拉选项 */
interface Option {
  id: number;
  name?: string;
  abstract_id?: string;
  board_id?: number;
  channel_id?: number;
}

/** 状态标签颜色 */
const STATUS_COLOR: Record<number, string> = {
  0: 'green',
  1: 'red',
  2: 'orange',
};

export default function ChargeRecords() {
  // 过滤条件
  const [cabinetId, setCabinetId] = useState<number | undefined>();
  const [cabinBoardId, setCabinBoardId] = useState<number | undefined>();
  const [compartmentId, setCompartmentId] = useState<number | undefined>();
  const [timeRange, setTimeRange] = useState<string[]>([]);

  // 下拉数据
  const [cabinets, setCabinets] = useState<Option[]>([]);
  const [cabinBoards, setCabinBoards] = useState<Option[]>([]);
  const [compartments, setCompartments] = useState<Option[]>([]);

  // 列表数据
  const [data, setData] = useState<ChargeRecord[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const pageSize = 20;

  // 下载中心
  const [downloadVisible, setDownloadVisible] = useState(false);

  /** 加载柜子下拉 */
  useEffect(() => {
    api.get<Option[]>('/cabinets/options')
      .then((res) => setCabinets(res.data || []))
      .catch(() => {});
  }, []);

  /** 加载仓板下拉（依赖柜子） */
  useEffect(() => {
    setCabinBoardId(undefined);
    setCompartments([]);
    setCompartmentId(undefined);
    if (!cabinetId) {
      setCabinBoards([]);
      return;
    }
    api.get<Option[]>(`/cabin-boards/options?cabinet_id=${cabinetId}`)
      .then((res) => setCabinBoards(res.data || []))
      .catch(() => {});
  }, [cabinetId]);

  /** 加载仓体下拉（依赖仓板） */
  useEffect(() => {
    setCompartmentId(undefined);
    if (!cabinBoardId) {
      setCompartments([]);
      return;
    }
    api.get<Option[]>(`/compartments/options?cabin_board_id=${cabinBoardId}`)
      .then((res) => setCompartments(res.data || []))
      .catch(() => {});
  }, [cabinBoardId]);

  /** 构建查询参数 */
  const buildQuery = useCallback(() => {
    const params = new URLSearchParams();
    if (cabinetId) params.set('cabinet_id', String(cabinetId));
    if (cabinBoardId) params.set('cabin_board_id', String(cabinBoardId));
    if (compartmentId) params.set('compartment_id', String(compartmentId));
    if (timeRange[0]) params.set('start_time', timeRange[0]);
    if (timeRange[1]) params.set('end_time', timeRange[1]);
    params.set('page', String(page));
    params.set('page_size', String(pageSize));
    return params.toString();
  }, [cabinetId, cabinBoardId, compartmentId, timeRange, page]);

  /** 加载列表数据 */
  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<{
        list: ChargeRecord[];
        total: number;
      }>(`/charge-records?${buildQuery()}`);
      setData(res.data.list || []);
      setTotal(res.data.total || 0);
    } catch {
      Message.error('加载充电记录失败');
    } finally {
      setLoading(false);
    }
  }, [buildQuery]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  /** 查询按钮 */
  const handleSearch = () => {
    setPage(1);
    fetchData();
  };

  /** 导出 */
  const handleExport = async () => {
    try {
      const params = new URLSearchParams();
      if (cabinetId) params.set('cabinet_id', String(cabinetId));
      if (timeRange[0]) params.set('start_time', timeRange[0]);
      if (timeRange[1]) params.set('end_time', timeRange[1]);

      await api.get(`/charge-records/export?${params.toString()}`);
      Message.success('导出任务已创建，请到下载中心查看');
      setDownloadVisible(true);
    } catch {
      Message.error('创建导出任务失败');
    }
  };

  /** 表格列定义 */
  const columns = [
    {
      title: '柜子',
      dataIndex: 'cabinet_name',
      width: 140,
      render: (val: string | null, record: ChargeRecord) =>
        val || `柜#${record.cabinet_id}`,
    },
    { title: '仓板', dataIndex: 'board_id', width: 70 },
    { title: '通道', dataIndex: 'channel_id', width: 70 },
    { title: '开始时间', dataIndex: 'start_time', width: 170 },
    { title: '结束时间', dataIndex: 'end_time', width: 170 },
    {
      title: '充电量(kWh)',
      dataIndex: 'energy',
      width: 110,
      render: (val: number | null) => (val != null ? val.toFixed(2) : '-'),
    },
    {
      title: '最高温度(°C)',
      dataIndex: 'max_temperature',
      width: 110,
      render: (val: number | null) => (val != null ? val.toFixed(1) : '-'),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 90,
      render: (status: number, record: ChargeRecord) => (
        <Tag color={STATUS_COLOR[status] || 'gray'}>
          {record.status_text}
        </Tag>
      ),
    },
  ];

  return (
    <Card>
      {/* 过滤区域 */}
      <Space wrap style={{ marginBottom: 16 }}>
        <Select
          placeholder="选择柜子"
          allowClear
          style={{ width: 200 }}
          value={cabinetId}
          onChange={(val) => setCabinetId(val || undefined)}
          options={cabinets.map((c) => ({
            label: c.name || c.abstract_id || `柜#${c.id}`,
            value: c.id,
          }))}
        />
        <Select
          placeholder="选择仓板"
          allowClear
          style={{ width: 140 }}
          value={cabinBoardId}
          onChange={(val) => setCabinBoardId(val || undefined)}
          options={cabinBoards.map((b) => ({
            label: `仓板#${b.board_id}`,
            value: b.id,
          }))}
          disabled={!cabinetId}
        />
        <Select
          placeholder="选择通道"
          allowClear
          style={{ width: 140 }}
          value={compartmentId}
          onChange={(val) => setCompartmentId(val || undefined)}
          options={compartments.map((c) => ({
            label: `通道#${c.channel_id}`,
            value: c.id,
          }))}
          disabled={!cabinBoardId}
        />
        <RangePicker
          onChange={(dateString) => {
            setTimeRange(dateString as string[]);
          }}
        />
        <Button type="primary" icon={<IconSearch />} onClick={handleSearch}>
          查询
        </Button>
        <Button icon={<IconDownload />} onClick={handleExport}>
          导出
        </Button>
        <Button onClick={() => setDownloadVisible(true)}>
          下载中心
        </Button>
      </Space>

      {/* 数据表格 */}
      <Table
        rowKey="id"
        columns={columns}
        data={data}
        loading={loading}
        pagination={{
          current: page,
          total,
          pageSize,
          onChange: setPage,
          showTotal: true,
        }}
        size="default"
      />

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