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

const Register: React.FC = () => {
  const [form] = Form.useForm();
  const [spinning, setSpinning] = useState(false);
  const [messageApi, messageHolder] = message.useMessage();
  const [countdown, setCountdown] = useState(0); // 倒计时状态

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

  // 发送邮箱验证码
  const sendVerificationCode = async () => {
    try {
      debugger;
      const email = form.getFieldsValue().email;
      if (!email) {
        messageApi.warning('请先填写邮箱');
        return;
      }

      // 验证邮箱格式
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(email)) {
        messageApi.warning('请输入有效的邮箱格式');
        return;
      }

      // 开始请求发送的接口

      let res = await request<ApiResponse.SuccessItem<string>>(`/lms/User/SendVerificationCode`, {
        method: 'POST',
        data: { email }
      });
      if (res.code != 1) {
        throw new Error(res.message);
      }
      // 设置倒计时
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prevCountdown) => {
          if (prevCountdown <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prevCountdown - 1;
        });
      }, 1000);

      messageApi.success('验证码已发送，请查收邮箱');
    } catch (error: any) {
      messageApi.error(error.message || '发送验证码失败');
    } finally {

    }
  };

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

    // 开始注册
    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="verificationCode"
              rules={[{ required: true, message: '请输入邮箱验证码！' }]}
            >
              <Row gutter={8}>
                <Col flex="auto">
                  <Input placeholder='邮箱验证码' />
                </Col>
                <Col>
                  <Button
                    type="primary"
                    onClick={sendVerificationCode}
                    disabled={countdown > 0}
                    style={{
                      width: '100px',
                      background: countdown > 0 ? '#f0f0f0' : '#1890ff',
                      borderColor: countdown > 0 ? '#d9d9d9' : '#1890ff',
                      color: countdown > 0 ? '#595959' : '#fff',
                      fontWeight: 500,
                      borderRadius: '4px',
                    }}
                  >
                    {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                  </Button>
                </Col>
              </Row>
            </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;