//时间选择
import Tabs from '@/components/Tabs';
import { dateMapEnum } from '@/utils/comm';
import { DatePicker, DatePickerProps, Flex, Space } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import { useState } from 'react';
interface DateSelectProps {
  dateOptions?: any[];
  defaultPickerType?: DatePickerProps['picker']; //默认
  defaultTime?: string; //默认事件
  onSelectedDate: ({ time, type }: { time: string; type: string }) => void; //选择的时间
}
const DateSelect: React.FC<DateSelectProps> = ({
  defaultPickerType = 'month',
  defaultTime = '',
  dateOptions = [
    {
      label: '年',
      value: 'year',
    },
    {
      label: '月',
      value: 'month',
    },
    {
      label: '日',
      value: 'date',
    },
  ],
  onSelectedDate,
}) => {
  const [selectedDate, setSelectedDate] = useState<{
    time: string;
    type: string | number;
    date?: Dayjs | null;
  }>({
    time: defaultTime,
    type: '',
    date: dayjs(),
  });
  const [pickerType, setPickerType] = useState<DatePickerProps['picker']>(
    defaultPickerType as any,
  ); //时间类型
  let timeObj: Record<'month' | 'date' | string, string> = {
    year: dayjs().format('YYYY'),
    month: dayjs().format('YYYY-MM'),
    week: dayjs().format('YYYY-w'),
    quarter: dayjs().format('YYYY-Q'),
    date: dayjs().format('YYYY-MM-DD'),
  };
  //切换时间类型
  const handleDateChange = (type: any) => {
    if (type === '') {
      //选择全部
      setSelectedDate({
        time: '',
        type: '',
        date: null,
      });
      onSelectedDate?.({
        time: '',
        type: '',
      });
    } else {
      setSelectedDate({
        time: timeObj[type],
        type: type,
        date: dayjs(),
      });
      onSelectedDate?.({
        time: timeObj[type],
        type: String(dateMapEnum[type]),
      });
    }
    setPickerType(type);
  };

  //日历选择
  const handleTimeChange: DatePickerProps['onChange'] = (date, dateString) => {
    setSelectedDate({
      time: dateString as string,
      type: pickerType as string,
      date: date,
    });
    onSelectedDate?.({
      time: dateString as string,
      type: pickerType ? String(dateMapEnum[pickerType]) : ('0' as string),
    });
  };
  return (
    <>
      <Space size="middle">
        <Tabs
          items={dateOptions}
          defaultValue={defaultPickerType}
          itemkey={'value'}
          onChange={(val) => handleDateChange(val)}
          style={{ background: '#123d66' }}
        />
        {pickerType && (
          <Flex align="center">
            <DatePicker
              size="large"
              value={selectedDate?.date}
              style={{
                border: 0,
                borderRadius: '28px',
                // width: '175px',
                background: '#326FA7',
              }}
              allowClear={false}
              onChange={handleTimeChange}
              picker={pickerType}
            />
          </Flex>
        )}
      </Space>
    </>
  );
};

export default DateSelect;
