import {
	FormInstance,
	ProFormDateTimePicker,
} from '@ant-design/pro-components';
import type { ProFormFieldItemProps } from '@ant-design/pro-form/es/typing';
import { type DatePickerProps, Input, message, Space, Typography } from 'antd';
import dayjs from 'dayjs';

interface IBizProFormDateTimePickerProps
	extends ProFormFieldItemProps<DatePickerProps> {
	form: FormInstance;
	dateTime?: string;
}

export default function BizProFormDateTimePicker(
	props: IBizProFormDateTimePickerProps,
) {
	const { name, form, dateTime, ...rest } = props;
	return (
		<ProFormDateTimePicker
			name={name}
			{...rest}
			rules={rest.rules}
			fieldProps={{
				...rest.fieldProps,
				format: 'YYYY-MM-DD HH:mm',
				onOpenChange: (open) => {
					if (open && !dateTime) {
						form.setFieldValue(name, dayjs());
					}
				},

				renderExtraFooter: () => {
					return (
						// 输入框格式化时间，并写入
						<Space>
							<Typography.Text>快捷输入</Typography.Text>
							<Input
								onInput={(e) => {
									//@ts-ignore
									const value = e.target.value;
									const date = dayjs(value).format('YYYY-MM-DD HH:mm');
									if (!dayjs(date, 'YYYY-MM-DD HH:mm', true).isValid()) {
										message.error('请输入正确的时间格式');
										return;
									}

									form.setFieldValue(name, date);
								}}
							/>
						</Space>
					);
				},
				onBlur: (e) => {
					//@ts-ignore
					const value = e.target.value;
					if (!value) {
						return;
					}

					const date = dayjs(value).format('YYYY-MM-DD HH:mm');
					if (date && !dayjs(date, 'YYYY-MM-DD HH:mm', true).isValid()) {
						message.error('请输入正确的时间格式');
						return;
					}

					form.setFieldValue(name, date);
				},
			}}
			addonAfter={<a onClick={() => form.setFieldValue(name, dayjs())}>此刻</a>}
		/>
	);
}
