import { useRef, useState, useEffect } from 'react';
import { ConfigProvider, Flex, Space, Modal, message, Image, Row, Col, Spin, Card, DatePicker, Radio } from 'antd';
import {
  PieChartOutlined,
  HomeOutlined,
  UserOutlined,
  MailOutlined,
  PropertySafetyOutlined,
} from '@ant-design/icons';

import * as echarts from 'echarts';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { PostJobseekerList, PostCompanyViplist, GetCompanyJobList, getCompanyList } from '@/apis/api';

const HomePage: React.FC = () => {
  const chartRef = useRef(null);
  const [companyAllTotal, setCompanyAllTotal] = useState<number>(0)
  const [jobseekerAllTotal, setJobseekerAllTotal] = useState<number>(0)
  const [postAllTotal, setPostAllTotal] = useState<number>(0)
  const [vipAllTotal, setVipAllTotal] = useState<number>(0)
  const [timeRadio, setTimeRadio] = useState<number>(0)
  const [timeRange, setTimeRange] = useState<[Date, Date] | [String, String] | null>(null);


  const [data, setData] = useState<number[]>([])

  useEffect(() => {
    getCompanyList().then(res => {
      setCompanyAllTotal(res.data.total ? res.data.total : 0)
    })
    PostJobseekerList().then(res => {
      setJobseekerAllTotal(res.data.total ? res.data.total : 0)
    })
    GetCompanyJobList().then(res => {
      setPostAllTotal(res.data.total ? res.data.total : 0)
    })
    PostCompanyViplist().then(res => {
      setVipAllTotal(res.data.total ? res.data.total : 0)
    })
  }, [])

  const [loading, setLoading] = useState<boolean>(false);
  const [companyTotal, setCompanyTotal] = useState<number>(0)
  const [jobseekerTotal, setJobseekerTotal] = useState<number>(0)
  const [postTotal, setPostTotal] = useState<number>(0)
  const [vipTotal, setVipTotal] = useState<number>(0)
  useEffect(() => {
    fetchData();
  }, [timeRange]);

  const fetchData = () => {
    setLoading(true);
    let params = timeRange ? { start_date: timeRange[0], end_date: timeRange[1] } : {};
    if (timeRadio == 5) {
      params = timeRange ? { start_date: timeRange[0], end_date: timeRange[1] } : {};
    } else {
      params = timeRange ? { start_date: formatDate(timeRange[0]), end_date: formatDate(timeRange[1]) } : {};
    }
    Promise.all([
      getCompanyList(params).then(res => setCompanyTotal(res.data.total ? res.data.total : 0)),
      PostJobseekerList(params).then(res => setJobseekerTotal(res.data.total ? res.data.total : 0)),
      GetCompanyJobList(params).then(res => setPostTotal(res.data.total ? res.data.total : 0)),
      PostCompanyViplist(params).then(res => setVipTotal(res.data.total ? res.data.total : 0)),
    ]).finally(() => {
      setLoading(false);
    });

  };

  const handleTimeChange = (e) => {
    setTimeRadio(e.target.value);
    const today = new Date();
    let start_date, end_date;

    switch (e.target.value) {
      case 0:
        setTimeRange(null);
      
        break;
      case 1:
        start_date = new Date(today);
        start_date.setDate(today.getDate() - 3);
        end_date = today;
        setTimeRange([start_date, end_date]);
        break;
      case 2:
        start_date = new Date(today);
        start_date.setDate(today.getDate() - 7);
        end_date = today;
        setTimeRange([start_date, end_date]);
        break;
      case 3:
        start_date = new Date(today);
        start_date.setDate(today.getDate() - 15);
        end_date = today;
        setTimeRange([start_date, end_date]);
        break;
      case 4:
        start_date = new Date(today);
        start_date.setDate(today.getDate() - 30);
        end_date = today;
        setTimeRange([start_date, end_date]);
        break;
      case 5:
        setTimeRange(null);
        break;
      default:
        setTimeRange(null);
    }

  };



  const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  useEffect(() => {
    const chartDom = chartRef.current;
    const myChart = echarts.init(chartDom);
    const option = {
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        show: true,
      },
      xAxis: {
        type: 'category',
        data: ['企业数', '求职者', '职位数', '企业VIP'],
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          type: 'bar',
          barWidth: "60%",
          data: [
            {
              name: '企业数',
              label: {
                show: true,
                verticalAlign: 'middle',
                position: 'insideBottom',
                distance: 15,
                formatter: companyTotal,
                fontSize: 16,
                rich: {
                  name: {}
                }
              },
              value: companyTotal,
              itemStyle: {
                color: '#BF7FF1'
              }
            },
            {
              name: '求职者',
              label: {
                show: true,
                verticalAlign: 'middle',
                position: 'insideBottom',
                distance: 15,
                formatter: jobseekerTotal,
                fontSize: 16,
                rich: {
                  name: {}
                }
              },
              value: jobseekerTotal,
              itemStyle: {
                color: '#3FAAF6'
              }
            },
            {
              name: '职位数',
              value: postTotal,
              label: {
                show: true,
                verticalAlign: 'middle',
                position: 'insideBottom',
                distance: 15,
                formatter: postTotal,
                fontSize: 16,
                rich: {
                  name: {}
                }
              },
              itemStyle: {
                color: '#EA667B'
              }
            },
            {
              name: '企业VIP',
              value: vipTotal,
              label: {
                show: true,
                verticalAlign: 'middle',
                position: 'insideBottom',
                distance: 15,
                formatter: vipTotal,
                fontSize: 16,
                rich: {
                  name: {}
                }
              },
              itemStyle: {
                color: '#19be6e'
              }
            },
          ]
        }
      ]
    };
    myChart.setOption(option);
    return () => {

      myChart.dispose();
    };
  }, [companyTotal, jobseekerTotal, postTotal, vipTotal]);



  return (
    <>
      <Row gutter={[20, 20]}>
        <Col span={18}>
          <Space direction='vertical' size={30} style={{ width: '100%' }}>
            <Flex vertical>
              <h3>数据概览</h3>
              <Row gutter={[20, 20]}>
                <Col span={6}>
                  <Flex justify='space-around' align='center' style={{ background: 'linear-gradient(to right, #5470FF,#BF7FF1)', height: 100, borderRadius: 10 }}>
                    <Flex vertical justify='space-around' align='stretch' style={{ height: 80, color: '#ffffff' }}>
                      <div style={{ fontSize: 20 }}>企业数</div>
                      <div style={{ fontWeight: 'bold', fontSize: 32 }}>{companyAllTotal}</div>
                    </Flex>
                    <Flex vertical justify='space-between'>
                      <HomeOutlined style={{ fontSize: 48, color: 'rgb(225,202,252)' }} />
                    </Flex>
                  </Flex>
                </Col>
                <Col span={6}>
                  <Flex justify='space-around' align='center' style={{ background: 'linear-gradient(to right, #3FAAF6,#767BFA)', height: 100, borderRadius: 10 }}>
                    <Flex vertical justify='space-around' align='stretch' style={{ height: 80, color: '#ffffff' }}>
                      <div style={{ fontSize: 20 }}>求职者</div>
                      <div style={{ fontWeight: 'bold', fontSize: 32 }}>{jobseekerAllTotal}</div>
                    </Flex>
                    <Flex vertical justify='space-between'>
                      <UserOutlined style={{ fontSize: 48, color: 'rgb(225,202,252)' }} />
                    </Flex>
                  </Flex>
                </Col>
                <Col span={6}>
                  <Flex justify='space-around' align='center' style={{ background: 'linear-gradient(to right, #EA667B,#F4A060)', height: 100, borderRadius: 10 }}>
                    <Flex vertical justify='space-around' align='stretch' style={{ height: 80, color: '#ffffff' }}>
                      <div style={{ fontSize: 20 }}>职位数</div>
                      <div style={{ fontWeight: 'bold', fontSize: 32 }}>{postAllTotal}</div>
                    </Flex>
                    <Flex vertical justify='space-between'>
                      <MailOutlined style={{ fontSize: 48, color: 'rgb(225,202,252)' }} />
                    </Flex>
                  </Flex>
                </Col>
                <Col span={6}>
                  <Flex justify='space-around' align='center' style={{ background: 'linear-gradient(to right,#A4E164,#19be6e)', height: 100, borderRadius: 10 }}>
                    <Flex vertical justify='space-around' align='stretch' style={{ height: 80, color: '#ffffff' }}>
                      <div style={{ fontSize: 20 }}>企业VIP</div>
                      <div style={{ fontWeight: 'bold', fontSize: 32 }}>{vipAllTotal}</div>
                    </Flex>
                    <Flex vertical justify='space-between'>
                      <PropertySafetyOutlined style={{ fontSize: 48, color: 'rgb(225,202,252)' }} />
                    </Flex>
                  </Flex>
                </Col>
              </Row>
            </Flex>

            <Row>
              <Col span={12}>
                {/* 柱状图 */}
                <Spin spinning={loading}>
                  <Space direction='vertical' style={{ width: '100%', background: '#ffffff', padding: '20px', borderRadius: 10 }}>
                    <Flex justify='space-between' align='center' >
                      <Space style={{ fontSize: 16, fontWeight: 'bold' }}><PieChartOutlined />使用情况</Space>
                      <Space direction='vertical'>
                        <Radio.Group value={timeRadio} defaultValue={0} size='small' onChange={async (e) => {
                          handleTimeChange(e)
                        }}>
                          <Radio.Button value={0}>全部</Radio.Button>
                          <Radio.Button value={1}>3天</Radio.Button>
                          <Radio.Button value={2}>7天</Radio.Button>
                          <Radio.Button value={3}>15天</Radio.Button>
                          <Radio.Button value={4}>30天</Radio.Button>
                          <Radio.Button value={5}>自定义</Radio.Button>
                        </Radio.Group>
                        {timeRadio == 5 ? <Space direction='vertical' align='end' style={{ width: '100%' }}>
                          <DatePicker.RangePicker size='small' onChange={(date, dateString) => {
                            setCompanyTotal(0)
                            setJobseekerTotal(0)
                            setPostTotal(0)
                            setVipTotal(0)
                            setTimeRange([dateString[0], dateString[1]]);
                          }} />
                        </Space> : ''}
                      </Space>
                    </Flex>
                    <div className="echarts-container" >
                      <div ref={chartRef} style={{ height: '400px', width: '100%' }} />
                    </div>
                  </Space>
                </Spin>

              </Col>
            </Row>

          </Space>

        </Col>
      </Row >

    </>
  );
};

export default HomePage;
