import React, { useState, useRef, useEffect } from 'react';
import { Button } from 'antd';
import { ButtonProps } from 'antd/lib/button';
type Iprops = {
	handleSend: () => Promise<void>;
};
const button: React.FC<ButtonProps & Iprops> = ({ ...props }) => {
	const [disabled, changeDisbaled] = useState(false);
	const ref = useRef<HTMLButtonElement>(null);
	const timeref = useRef<{
		freeTime: number;
		timeInstance: NodeJS.Timeout | null;
	}>({
		timeInstance: null,
		freeTime: 60,
	});
	const handleClickSendButton = () => {
		if (props.handleSend) {
			props.handleSend().then(() => {
				changeDisbaled(true);
				timeref.current.timeInstance = setInterval(() => {
					if (timeref.current.freeTime === 0) {
						return resetFn();
					}
					if (ref.current) {
						ref.current.innerText = `倒计时${timeref.current.freeTime--}s`;
					}
				}, 1000);
			});
		}
	};
	const resetFn = () => {
		if (timeref.current.timeInstance) {
			clearInterval(timeref.current.timeInstance);
		}
		if (ref.current) {
			ref.current.innerText = '发送验证码';
		}
		changeDisbaled(false);
		timeref.current.freeTime = 60;
	};

	return (
		<Button
			style={{ width: '100%' }}
			{...props}
			type='primary'
			ref={ref}
			onClick={handleClickSendButton}
			disabled={disabled}>
			发送验证码
		</Button>
	);
};
export default button;
