import { DatePicker, Radio } from 'antd';
import React, { useState } from 'react';
import moment from 'moment';
import styles from './index.less';

const { RangePicker } = DatePicker;

export interface TimeRangeProps {
  startTime: number;
  setStartTime: (time: number) => void;
  endTime: number;
  setEndTime: (time: number) => void;
  style?: React.CSSProperties;
  value?: [number, number];
  onChange?: (value: [number, number]) => void;
}
const TimeRange = (props: TimeRangeProps) => {
  const preWeak = Date.now() - 6 * 24 * 60 * 60 * 1000;
  const preMonth = Date.now() - 29 * 24 * 60 * 60 * 1000;

  const {
    value,
    onChange,
    startTime,
    setStartTime,
    endTime,
    setEndTime,
    ...rest
  } = props;

  // day / week / month
  const [date, setDate] = useState<string>('week');

  // 时间切换
  const changeTime = (dates: any, formatString: [string, string]) => {
    const [start, end] = dates;
    setStartTime(
      moment(start)
        .startOf('day')
        .valueOf(),
    );
    setEndTime(
      moment(end)
        .endOf('day')
        .valueOf(),
    );
    onChange?.([
      moment(start)
        .startOf('day')
        .valueOf(),
      moment(end)
        .endOf('day')
        .valueOf(),
    ]);
    setDate('');
  };

  const changeDate = (e: any) => {
    const current = e.target.value;
    setDate(current);

    const dayEnd = moment()
      .endOf('day')
      .valueOf();
    let currentStart = moment()
      .startOf('day')
      .valueOf();
    if (current === 'month') {
      currentStart = moment(preMonth)
        .startOf('day')
        .valueOf();
    } else if (current === 'week') {
      currentStart = moment(preWeak)
        .startOf('day')
        .valueOf();
    }

    setStartTime(currentStart);
    setEndTime(dayEnd);
    onChange?.([currentStart, dayEnd]);
  };

  return (
    <div className={styles.timeRangerContainer} {...rest}>
      <div className={styles.date}>
        <Radio.Group value={date} onChange={changeDate}>
          <Radio.Button value="day">今天</Radio.Button>
          <Radio.Button value="week">近7天</Radio.Button>
          <Radio.Button value="month">近30天</Radio.Button>
        </Radio.Group>
      </div>
      <RangePicker
        className={styles.time}
        value={[moment(value?.[0]), moment(value?.[1])]}
        onChange={changeTime}
        disabledDate={(current: any) => {
          return moment().endOf('day') < moment(current).endOf('day');
        }}
      />
    </div>
  );
};

export default TimeRange;
