import auth from '@/services/auth';
import { Captcha, CheckCaptchaProps } from '@chageable/components';
import React, { useEffect, useState } from 'react';

interface ICaptchaModalProps {
	visible: boolean;
	setVisible: (visible: boolean) => void;
	onFinish: (token: string) => void;
}

const CaptchaModal: React.FC<ICaptchaModalProps> = (props) => {
	const { visible, setVisible, onFinish } = props;
	const [size, setSize] = useState<'default' | 'big' | 'large'>('default');
	const resizeUpdate = () => {
		// 通过事件对象获取浏览器窗口的宽度
		const w = window.innerWidth;
		if (w < 480) setSize('default');
		else if (w < 980) setSize('big');
		else setSize('large');
	};

	useEffect(() => {
		resizeUpdate();
		// 页面变化时获取浏览器窗口的大小
		window.addEventListener('resize', resizeUpdate);

		return () => {
			// 组件销毁时移除监听事件
			window.removeEventListener('resize', resizeUpdate);
		};
	}, []);

	const onSuccess = (token: any) => {
		console.log('token:', token);
		setVisible(false);
		onFinish(token);
	};

	return (
		<Captcha
			title="验证码"
			tips="将滑动块向右滑动"
			refreshText="刷新验证码"
			show={visible}
			onSuccess={onSuccess}
			size={size}
			hide={() => setVisible(false)}
			getPicture={() =>
				auth.captcha
					.get({ captchaType: 'blockPuzzle' })
					.then((res) => res.repData)
			}
			checkCaptcha={(data: CheckCaptchaProps) =>
				auth.captcha
					.check({ ...data, captchaType: 'blockPuzzle' })
					.then((res) => res.repData)
			}
		/>
	);
};

export default CaptchaModal;
