import { ButtonAccess, SafeModal } from '@/components';
import { business } from '@/services';
import { aesEncrypt } from '@/utils/aes';
import { formLayout } from '@/utils/formLayout';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import React, { useState } from 'react';

interface IRestPasswordProps {
	permission: string;
	onFinish: () => void;
	employeeId: BusinessAPI.EmployeeVO['employeeId'];
}

const RestPassword: React.FC<IRestPasswordProps> = (props) => {
	const { permission, onFinish, employeeId } = props;
	const [openSafeModal, setOpenSafeModal] = useState<boolean>(false);
	return (
		<>
			<SafeModal
				open={openSafeModal}
				onVisibleChange={(openSafeModal) => setOpenSafeModal(openSafeModal)}
			/>
			<ModalForm<BusinessAPI.EmployeeRestPasswordCmd>
				title="重置密码"
				{...formLayout()}
				grid={true}
				trigger={
					<ButtonAccess permission={permission} type={'link'}>
						重置密码
					</ButtonAccess>
				}
				autoFocusFirstInput
				modalProps={{
					destroyOnHidden: true,
				}}
				submitTimeout={2000}
				request={async () => {
					const { data } = await business.employee.showEmployee({
						employeeShowQry: { employeeId: employeeId },
					});
					return {
						userId: data?.userId ?? '',
						password: '',
					};
				}}
				onFinish={async (values) => {
					const { success, errCode } =
						await business.employee.restEmployeePassword({
							...values,
							password: aesEncrypt(values.password),
						});
					if (success && errCode === '401') {
						setOpenSafeModal(true);
						return false;
					}
					onFinish();
					return true;
				}}
			>
				<ProFormText hidden={true} name={'userId'} />
				<ProFormText
					name={'password'}
					label={'密码'}
					placeholder="请输入密码"
					required={true}
					rules={[
						{
							required: true,
							message: '请输入密码',
						},
					]}
					fieldProps={{
						type: 'password',
					}}
					transform={(password) => {
						return {
							password: aesEncrypt(password),
						};
					}}
				/>
			</ModalForm>
		</>
	);
};

export default RestPassword;
