import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Spin, message } from 'antd';
import { UserRegistr } from '@/services/services/login';
import { set } from 'lodash';
import { history } from '@umijs/max';

const Register: React.FC = () => {
  const [form] = Form.useForm();
  const [spinning, setSpinning] = useState(false);
  const [messageApi, messageHolder] = message.useMessage();

  useEffect(() => {
    // 检查当前网址是不是包含query，并且?aff=后面有6位数字
    const urlParams = new URLSearchParams(window.location.search);
    const affiliateCode = urlParams.get('aff');
    if (affiliateCode) {
      form.setFieldsValue({ affiliateCode });
    }
  }, []);

  const onFinish = async (values: UserModel.UserRegisterParams) => {
    // 判断两次密码是否一致
    if (values.password !== values.confirm) {
      messageApi.warning('两次密码不一致！');
      return;
    }

    // 开始注册
    setSpinning(true);
    try {
      await UserRegistr(values);
      messageApi.success('注册成功，即将跳转到登录界面');
      // 注册成功后，跳转到登录页面
      setTimeout(() => {
        history.push('/user/login');
      }, 3000);
    }
    catch (error: any) {
      messageApi.error(error.message);
    }
    finally {
      setSpinning(false);
    }


  };

  return (
    <Spin spinning={spinning} tip="注册中。。。">
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <div style={{ maxWidth: '400px', width: '100%' }}>
          <h2>注册</h2>
          <Form
            form={form}
            size='large'
            name="register"
            onFinish={onFinish}
            scrollToFirstError
          >
            <Form.Item
              name="userName"
              rules={[{ required: true, message: '请输入你的用户名！' }]}
            >
              <Input placeholder='用户名' />
            </Form.Item>

            <Form.Item
              name="email"
              rules={[
                {
                  type: 'email',
                  message: '你的输入不是一个有效的邮箱号!',
                },
                {
                  required: true,
                  message: '请输入邮箱号!',
                },
              ]}
            >
              <Input placeholder='邮箱号' />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: '请输入密码!',
                },
              ]}
              hasFeedback
            >
              <Input.Password placeholder='密码，包含大小写英文，汉字和特殊字符' />
            </Form.Item>

            <Form.Item
              name="confirm"
              dependencies={['password']}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: '请输入确认密码!',
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致!'));
                  },
                }),
                {
                  pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?.&.])[A-Za-z\d@$!%*?.&]{8,}$/,
                  message: '密码必须包含至少八位，必须包含大小写字母，数字，特殊字符 @$!%*?.&. ',
                },
              ]}
            >
              <Input.Password placeholder='确认密码' />
            </Form.Item>

            <Form.Item
              name="affiliateCode"
              rules={[
                { required: true, message: '请输入邀请码！' },
                { pattern: /^\d{6}$/, message: '邀请码必须是六位数字！' }
              ]}
            >
              <Input placeholder='邀请码' />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit">
                注册
              </Button>
            </Form.Item>
          </Form>
        </div>
        {messageHolder}
      </div>
    </Spin>
  );
};

export default Register;