import React, { useState } from 'react';
import { 
  Button, Form, Select, Card, Typography, DatePicker
} from 'antd';
import { 
  useQuery,
} from '@tanstack/react-query';
import dayjs from 'dayjs';
import { Column} from "@ant-design/plots";
import 'dayjs/locale/zh-cn';

import { MonitorChartsAPI } from './api/index.ts';

// 在线设备数量图表页面
export const OnlineDevicesChartPage = () => {
    const [timeRange, setTimeRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
      dayjs().subtract(7, 'day'),
      dayjs()
    ]);
    const [dimension, setDimension] = useState<'hour' | 'day' | 'month'>('day');
  
    const { data: onlineRateData, isLoading, refetch } = useQuery({
      queryKey: ['adminZichanOnlineRate', timeRange, dimension],
      queryFn: async () => {
        const params = {
          created_at_gte: timeRange[0].format('YYYY-MM-DD HH:mm:ss'),
          created_at_lte: timeRange[1].format('YYYY-MM-DD HH:mm:ss'),
          dimension
        };
        
        // const res = await axios.get<OnlineRateChartData[]>(`${API_BASE_URL}/big/zichan_online_rate_chart`, { params });
        const res = await MonitorChartsAPI.fetchOnlineRateData(params);
        return res;
      }
    });
  
    const { Title } = Typography;
    const { RangePicker } = DatePicker;
  
    const handleSearch = () => {
      refetch();
    };
  
    return (
      <div>
        <Title level={2}>在线设备数量变化</Title>
        
        <Card>
          <Form layout="inline" style={{ marginBottom: '16px' }}>
            <Form.Item label="时间范围">
              <RangePicker 
                value={timeRange} 
                onChange={(dates) => dates && setTimeRange(dates as [dayjs.Dayjs, dayjs.Dayjs])} 
              />
            </Form.Item>
            <Form.Item label="时间维度">
              <Select 
                value={dimension} 
                onChange={setDimension}
                options={[
                  { label: '小时', value: 'hour' },
                  { label: '天', value: 'day' },
                  { label: '月', value: 'month' }
                ]}
                style={{ width: '100px' }}
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={handleSearch}>查询</Button>
            </Form.Item>
          </Form>
          
          <div style={{ height: '500px' }}>
            {!isLoading && onlineRateData && (
              <Column
                data={onlineRateData}
                xField="time_interval"
                yField="total_devices"
                color="#36cfc9"
                label={{
                  position: 'top',
                  style: {
                    fill: '#000',
                  },
                  text: (items: Record<string, any>) => {
                    let content = items['time_interval'];
                    content += `\n(${(items['total_devices'])})`;
                    return content;
                  },
                }}
                xAxis={{
                  label: {
                    style: {
                      fill: '#000',
                    },
                  },
                }}
                yAxis={{
                  label: {
                    style: {
                      fill: '#000',
                    },
                  },
                }}
                autoFit={true}
                interaction={{
                  tooltip: false
                }}
              />
            )}
          </div>
        </Card>
      </div>
    );
  };