import React, { Fragment, useRef, useState, useEffect } from 'react';
import { history, useAccess } from '@umijs/max';
import { getCmsJobList, getJobTrend } from '@/services/Management/list';
import { Button, DatePicker, FormInstance, message, Space, Card } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { AlignLeftOutlined } from '@ant-design/icons';
import { Line } from '@ant-design/charts';
import dayjs from 'dayjs';
import { getDictValueEnum } from '@/services/system/dict';

import DictTag from '@/components/DictTag';
import DetailModal from './detail';

const { RangePicker } = DatePicker;

function JobStatistics() {
  const access = useAccess();
  const formTableRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();

  const [chartData, setChartData] = useState<any[]>([]);
  const [currentRow, setCurrentRow] = useState<API.ManagementList.Manage>();
  const [detailVisible, setDetailVisible] = useState<boolean>(false);

  const [educationEnum, setEducationEnum] = useState<any>([]);
  const [experienceEnum, setExperienceEnum] = useState<any>([]);
  const [areaEnum, setAreaEnum] = useState<any>([]);
  const [isPublishEnum, setIsPublishEnum] = useState<any>([]);

  const [params, setParams] = useState({
    beginTime: dayjs().subtract(13, 'day').format('YYYY-MM-DD'),
    endTime: dayjs().format('YYYY-MM-DD'),
  });

  const getPickerValue = () => {
    return [dayjs(params.beginTime), dayjs(params.endTime)];
  };

  const disabledDate = (current: dayjs.Dayjs) => {
    const now = dayjs();
    return current.isAfter(now.endOf('day'));
  };

  // 初始化图表数据
  useEffect(() => {
    getChartData();
  }, [params.beginTime, params.endTime]);

  useEffect(() => {
    getDictValueEnum('education', true, true).then((data) => {
      setEducationEnum(data);
    });
    getDictValueEnum('experience', true, true).then((data) => {
      setExperienceEnum(data);
    });
    getDictValueEnum('area', true, true).then((data) => {
      setAreaEnum(data);
    });
    getDictValueEnum('is_publish', true).then((data) => {
      setIsPublishEnum(data);
    });
  }, []);

  const handleDateRangeChange = (dates: any, dateStrings: [string, string]) => {
    if (dates && dates[0] && dates[1]) {
      setParams(() => ({
        beginTime: dateStrings[0],
        endTime: dateStrings[1],
      }));
    }
  };
  async function getChartData() {
    let { data } = await getJobTrend(params);
    setChartData(data); // 暂时使用模拟数据
  }

  // 图表配置
  const chartConfig = {
    data: chartData,
    xField: 'storageTime',
    yField: 'insertCount',
    style: {
      columnWidthRatio: 0.6,
    },
    xAxis: {
      label: {
        autoHide: true,
        autoRotate: false,
      },
    },
    point: {
      size: 4,
      shape: 'circle',
    },
    line: {
      size: 3,
      style: {
        lineCap: 'round',
      },
    },
    tooltip: {
      items: [
        {
          field: 'insertCount',
          name: '录入数量',
          valueFormatter: (v) => `${v}个`,
          title: '日期',
        },
      ],
    },
  };

  const columns: ProColumns<API.ManagementList.Manage>[] = [
    {
      title: '岗位采集日期',
      dataIndex: 'collectionDate1',
      hideInTable: true,
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            beginTime: value[0],
            endTime: value[1],
          };
        },
      },
    },
    {
      title: '岗位名称',
      dataIndex: 'jobTitle',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '最小薪资(元/月)',
      dataIndex: 'minSalary',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '最大薪资(元/月)',
      dataIndex: 'maxSalary',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '单位名称',
      dataIndex: 'companyName',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '学历要求',
      dataIndex: 'education',
      valueType: 'select',
      align: 'center',
      valueEnum: educationEnum,
      render: (_, record) => {
        return <DictTag enums={educationEnum} value={record.education} />;
      },
      hideInSearch: true,
    },
    {
      title: '经验要求',
      dataIndex: 'experience',
      valueType: 'select',
      align: 'center',
      valueEnum: experienceEnum,
      render: (_, record) => {
        return <DictTag enums={experienceEnum} value={record.experience} />;
      },
      hideInSearch: true,
    },
    {
      title: '是否发布',
      dataIndex: 'isPublish',
      valueType: 'select',
      align: 'center',
      valueEnum: isPublishEnum,
      render: (_, record) => {
        return <DictTag enums={isPublishEnum} value={record.isPublish} />;
      },
      hideInSearch: true,
    },
    {
      title: '招聘人数',
      dataIndex: 'vacancies',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '浏览量',
      dataIndex: 'view',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      hideInSearch: true,
      align: 'center',
      dataIndex: 'jobId',
      width: 100,
      render: (jobId, record) => (
        <Button
          type="link"
          size="small"
          icon={<AlignLeftOutlined />}
          onClick={() => {
            setCurrentRow(record);
            setDetailVisible(true);
          }}
        >
          查看详情
        </Button>
      ),
    },
  ];

  return (
    <Fragment>
      <Card
        title={<span>📊 采集趋势分析</span>}
        style={{
          marginBottom: 16,
        }}
        extra={
          <div>
            <span>统计日期范围：</span>
            <RangePicker
              picker="date"
              value={getPickerValue()}
              onChange={handleDateRangeChange}
              disabledDate={disabledDate}
            />
          </div>
        }
      >
        <div style={{ height: 300 }}>
          <Line {...chartConfig} />
        </div>
      </Card>

      <div style={{ background: '#fff', padding: 24, borderRadius: 8 }}>
        <ProTable<API.ManagementList.Manage>
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="jobId"
          key="jobStatisticsList"
          columns={columns}
          request={(params) => {
            return getCmsJobList(params as API.ManagementList.ListParams).then((res) => {
              const result = {
                data: res.rows,
                total: res.total,
                success: true,
              };
              return result;
            });
          }}
          search={{
            labelWidth: 120,
          }}
          toolBarRender={false}
          pagination={{
            pageSize: 10,
          }}
        />
      </div>

      <DetailModal
        open={detailVisible}
        onCancel={() => {
          setDetailVisible(false);
          setCurrentRow(undefined);
        }}
        values={currentRow}
      />
    </Fragment>
  );
}

export default JobStatistics;
