import { ConfigProvider, DatePicker } from 'antd';
import classNames from 'classnames';
import dayjs from 'dayjs';
import { isEqual } from 'lodash';
import React, { memo, useEffect, useMemo, useState } from 'react';
import styles from './index.less';

export interface BaseDate {
  label: string;
  value: {
    start: string;
    end: string;
  };
}

interface PropsType {
  value?: BaseDate;
  defaultValue?: BaseDate;
  onChange: (value: BaseDate) => void;
  /** today 今日 | week 本周 | month 本月 | year 本年 | last_month 近一月 | custom 自定义 | last_year 上一年 */
  dateRange: (
    | 'today'
    | 'week'
    | 'month'
    | 'year'
    | 'last_month'
    | 'yesterday'
    | 'prev_year'
  )[];
  /** 自定义模式 */
  // datePickerMode?: 'date' | 'month' | 'year' | 'dateRange';
  /** showCustom 是否显示区域选择 */
  showRangePicker?: boolean;
}

/**
 *
 * 对照表
 * @description 在任意地方获取相同值时，可以从这里获取初始值
 * @exports
 *  */
const DATE_MAPPING = {
  today: {
    label: '今日',
    get: () => ({
      start: dayjs().format('YYYY-MM-DD'),
      end: dayjs().format('YYYY-MM-DD'),
    }),
  },
  yesterday: {
    label: '昨日',
    get: () => ({
      start: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
      end: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
    }),
  },
  week: {
    label: '本周',
    get: () => ({
      start: dayjs().startOf('week').format('YYYY-MM-DD'),
      end: dayjs().endOf('week').format('YYYY-MM-DD'),
    }),
  },
  month: {
    label: '本月',
    get: () => ({
      start: dayjs().startOf('month').format('YYYY-MM-DD'),
      end: dayjs().endOf('month').format('YYYY-MM-DD'),
    }),
  },
  year: {
    label: '本年',
    get: () => ({
      start: dayjs().startOf('year').format('YYYY-MM-DD'),
      end: dayjs().endOf('year').format('YYYY-MM-DD'),
    }),
  },
  last_month: {
    label: '近一月',
    get: () => ({
      start: dayjs().subtract(1, 'month').format('YYYY-MM-DD'),
      end: dayjs().format('YYYY-MM-DD'),
    }),
  },

  prev_year: {
    label: '上一年',
    get: () => ({
      start: dayjs().subtract(1, 'year').startOf('year').format('YYYY-MM-DD'),
      end: dayjs().subtract(1, 'year').endOf('year').format('YYYY-MM-DD'),
    }),
  },
};

/**
 * 创建时间
 * @see DATE_MAPPING 查询key
 * @example
 * const date = createDate('today');
 *
 *  */
export function createDate(key: keyof typeof DATE_MAPPING): BaseDate {
  return { label: DATE_MAPPING[key].label, value: DATE_MAPPING[key].get() };
}

/** 
 * 通用时间选择器
 * @example
 *  <BaseDatePicker
     dateRange={['yesterday', 'month']}
     value={date}
     onChange={(val) => {setDate(val);}}
    />
 * 
 *  */
const BaseDatePicker: React.FC<PropsType> = memo((props) => {
  const {
    value,
    defaultValue,
    dateRange = ['today', 'yesterday', 'week', 'last_month', 'month', 'year'],
    showRangePicker = true,
    onChange,
  } = props;

  /** 当前的时间 */
  const [curVal, setCurVal] = useState(defaultValue);

  const options = useMemo(() => {
    return dateRange
      .map((item) => {
        if (item && item in DATE_MAPPING) {
          return createDate(item);
        }

        return undefined;
      })
      .filter((item) => item !== undefined);
  }, [dateRange]);

  useEffect(() => {
    if (!isEqual(value, curVal)) {
      setCurVal(value);
    }
  }, [value]);

  const clickHandle = (item: any) => {
    setCurVal(item);
    onChange && onChange(item);
  };

  const renderRangePicker = () => {
    const isSelected = curVal?.label === 'dateRange';

    const rangeValue = isSelected
      ? ([dayjs(curVal?.value?.start), dayjs(curVal?.value?.end)] as any)
      : undefined;
    return (
      <ConfigProvider
        theme={{
          components: {
            DatePicker: {
              colorBgContainer: 'transparent',
              colorTextPlaceholder: 'rgb(116, 157, 223)',
            },
          },
        }}
      >
        <div
          className={classNames(styles.rangeContainer, {
            [styles.selected]: isSelected,
          })}
        >
          <DatePicker.RangePicker
            variant="borderless"
            allowClear={false}
            value={rangeValue}
            onChange={(dates) => {
              const start = dates?.[0]?.format('YYYY-MM-DD');
              const end = dates?.[1]?.format('YYYY-MM-DD');
              const newV = {
                label: 'dateRange',
                value: {
                  start,
                  end,
                },
              } as BaseDate;
              setCurVal(newV);
              onChange && onChange(newV);
            }}
            format={'YYYY-MM-DD'}
          />
        </div>
      </ConfigProvider>
    );
  };

  return (
    <div className={styles.container}>
      {options?.map((item) => {
        const isSelected = curVal?.label === item.label;
        return (
          <div
            key={item.label}
            className={classNames(styles.item, {
              [styles.selected]: isSelected,
            })}
            onClick={() => clickHandle(item)}
          >
            {item.label}
          </div>
        );
      })}

      {showRangePicker && renderRangePicker()}
    </div>
  );
});

export default BaseDatePicker;
