import { queryChangePassWord } from '@/services/user';
import { useModel, useNavigate } from '@umijs/max';
import { Form, Input, Button, message } from 'antd';
import { useState } from 'react';

const ChangePassWord = () => {
  const {
    initialState: { user },
  } = useModel('@@initialState');
  const navigate = useNavigate();

  const onFinish = async (values) => {
    const res = await queryChangePassWord({
      ID: user.ID,
      Password: values.password,
    });
    if (res?.code === 200 && res?.msg === 'ok') {
      message.success('修改密码成功');
      navigate('/login');
    }
  };

  return (
    <div style={{ margin: 'auto' }}>
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ width: 600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="请输入密码："
          name="password"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input.Password autoComplete="false" />
        </Form.Item>
        <Form.Item
          label="请再一次输入密码："
          name="password2"
          rules={[
            {
              required: true,
              message: '请再一次输入密码!',
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入的密码不一致!'));
              },
            }),
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default ChangePassWord;
