import { encrptRsa, validatePasswordComplexity, validatePasswordComplexityInititalValue, ValidatePasswordComplexityType } from '@/common/helper';
import { MovableModalForm, PasswordComplexityValidation } from '@/components';
import SysUserController from '@/services/apis/SysUserController';
import type { ProFormInstance } from '@ant-design/pro-components';
import { App, Form, Input } from 'antd';
import { useRef, useState } from 'react';

interface ChangePasswordProps {
    onClose: () => void;
}
const ChangePassword: React.FC<ChangePasswordProps> = ({ onClose }) => {
    const [visible, setVisible] = useState<boolean>(true);
    const handleClose = () => { setVisible(false); setTimeout(onClose, 300); };
    const formRef = useRef<ProFormInstance>();

    const { minLen, maxLen, special } = validatePasswordComplexityInititalValue;
    const [passwordValid, setPasswordValid] = useState<ValidatePasswordComplexityType>({ minLen, maxLen, special });

    const { message } = App.useApp();

    return (
        <MovableModalForm<{
            oldPassword: string;
            newPassword: string;
            newPasswordConfirm: string;
        }>
            title="修改密码"
            width={480}
            open={visible}
            formRef={formRef}
            modalProps={{
                centered: true,
                maskClosable: false,
                onCancel: handleClose,
            }}
            onFinish={async (values) => {
                const hide = message.loading('提交中...', 0);
                const { oldPassword, newPassword } = values;
                const params = {
                    oldPassword: encrptRsa(oldPassword) || '',
                    newPassword: encrptRsa(newPassword) || '',
                };
                try {
                    await SysUserController.changePassword(params);
                    message.success('修改成功');
                    handleClose();
                }
                catch {
                    message.error('修改失败');
                }
                finally {
                    hide();
                }
            }}
        >
            <Form.Item label="原密码" name="oldPassword" rules={[{ required: true }]}>
                <Input.Password showCount minLength={6} maxLength={32} autoComplete="new-password" />
            </Form.Item>
            <Form.Item
                label="新密码"
                name="newPassword"
                required
                rules={[
                    () => ({
                        validator: (_, value) => {
                            const r = validatePasswordComplexity(value);
                            setPasswordValid(r);
                            if (!r.isValid) {
                                return Promise.reject('新密码不符合密码规则要求');
                            }
                        },
                    }),
                ]}
            >
                <Input.Password showCount minLength={6} maxLength={32} autoComplete="new-password" />
            </Form.Item>
            <PasswordComplexityValidation result={passwordValid} />
            <Form.Item
                label="确认新密码"
                name="newPasswordConfirm"
                rules={[
                    { required: true },
                    ({ getFieldValue }) => ({
                        validator: (_, value) => {
                            const np = getFieldValue('newPassword');
                            if (np === value) {
                                return Promise.resolve();
                            }
                            return Promise.reject('两次输入新密码不一致！');
                        },
                    }),
                ]}
            >
                <Input.Password showCount minLength={6} maxLength={32} autoComplete="new-password" />
            </Form.Item>
        </MovableModalForm>
    );
};

export default ChangePassword;
