import { BizCalenderProps } from '@/components';
import { ProCard } from '@ant-design/pro-components';
import { Calendar, CalendarProps } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import { useImperativeHandle, useState } from 'react';

export default function BizCalender<
	BizVO extends Record<string, any>,
	BizPageQry extends Record<string, any>,
	Func extends Record<string, any>,
>(props: BizCalenderProps<BizVO, BizPageQry, Func>) {
	const { method, func, methodUpper, fieldProps } = props;
	const { cardProps, detailRender, rowName } = fieldProps;

	// 当日
	const [value, setValue] = useState(() => dayjs());
	const [dataSource, setDataSource] = useState<BizVO>();

	const init = async (value: Dayjs) => {
		//获取当前月份开始时间
		const startTime = dayjs(value)
			.subtract(1, 'month')
			.startOf('month')
			.format('YYYY-MM-DD 00:00:00');
		const endTime = dayjs(value)
			.add(2, 'month')
			.startOf('month')
			.format('YYYY-MM-DD 23:59:59');

		const { data } = await func?.[`list${methodUpper}`]({
			[`${method}ListQry`]: {
				[`${rowName}`]: [startTime, endTime],
			},
		});
		setDataSource(data);
	};

	const onSelect = (newValue: Dayjs, { source }: any) => {
		// 判断是否是同一个月
		setValue(newValue);
		if (
			source === 'date' &&
			dayjs(value).month() === dayjs(newValue).month() &&
			dayjs(value).year() === dayjs(newValue).year()
		) {
		} else {
			init(value).then();
		}
	};

	const onPanelChange = (newValue: Dayjs) => {
		setValue(newValue);
	};

	const dateCellRender = (value: Dayjs) => {
		return (
			<ul className="events">
				{dataSource?.map((item: BizVO, index: number) => (
					<li key={index}>{detailRender?.(item, value)}</li>
				))}
			</ul>
		);
	};

	const cellRender: CalendarProps<Dayjs>['cellRender'] = (current, info) => {
		if (info.type === 'date') return dateCellRender(current);
		return info.originNode;
	};

	useImperativeHandle(fieldProps.actionRef, () => ({
		reload: async () => {
			await init(value);
		},
	}));

	return (
		<ProCard size={'small'} {...cardProps}>
			{dataSource && (
				<Calendar
					value={value}
					onSelect={onSelect}
					onPanelChange={onPanelChange}
					validRange={[dayjs('2025-01-01'), dayjs('2035-01-01')]}
					cellRender={cellRender}
				/>
			)}
		</ProCard>
	);
}
