// @ts-nocheck
import React, { useState, useCallback } from 'react';
import styles from './styles.less';

import { loginService, commonService } from '@/service';

import { Form, Button, message } from 'antd4';

import BaseForm from '@/components/form';

import {
  Phone,
  Captcha,
  Input,
  Password,
  Email,
} from '@/components/form_items';

const RegisterByEmailForm = (props) => {
  const [registerByEmailForm] = Form.useForm();

  const email_pattern = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
  const [formValues, setFormValues] = useState({});
  const [captchaEnable, setCaptchaEnable] = useState(false);

  const [lastTime, setLastTime] = useState();

  const handleFormFinish = (values) => {
    const payload = {
      username: values.username,
      code: values.captcha,
      email: values.email,
      password: values.password,
    };
    if (props?.onFinish) {
      props.onFinish(payload);
    }
  };

  const handleValuesChange = (changed, values) => {
    if (changed.email) {
      let email_enable = email_pattern.test(changed.email);
      if (email_enable && !captchaEnable) {
        setCaptchaEnable(true);
      } else if (!email_enable && captchaEnable) {
        setCaptchaEnable(false);
      }
    }
    setFormValues(values);
  };

  const handleCaptchaSend = async () => {
    try {
      const payload = { email: formValues.email };
      const data = await loginService.sendCaptchaByEmailToRegister(payload);
      if (data?.error) {
        throw new Error(data?.msg);
      }
      setLastTime(new Date().getTime());
      message.success('验证码发送成功，请查收!');
    } catch (e) {
      if (e?.message === '60秒内不能发送多次验证码') {
        message.error(e?.message);
      } else {
        message.error('验证码发送失败，请稍候重试!');
      }

    }
  };

  return (
    <BaseForm
      form={registerByEmailForm}
      name="registerByEmail"
      onFinish={handleFormFinish}
      onValuesChange={handleValuesChange}
    >
      <Email
        isShowMask
        rules={[
          { required: true, message: '邮箱不能为空' },
          {
            pattern: email_pattern,
            message: '请输入正确的邮箱',
          },
          () => ({
            validator(_, value) {
              return new Promise(async (resolve, reject) => {
                if (!email_pattern.test(value)) {
                  resolve();
                } else {
                  const payload = { email: value };
                  const data = await commonService.checkIsExistEmail(payload);
                  if (data && data.error) {
                    reject(new Error('用户已存在'));
                  } else {
                    resolve();
                  }
                }
              });
            },
          }),
        ]}
      />

      <Captcha
        isShowMask
        enable={captchaEnable}
        onSend={handleCaptchaSend}
        lastTime={lastTime}
      />

      <Password
        isShowMask
        placeholder={'请输入密码，建议六位以上带有特殊符号'}
      />

      <Password
        isShowMask
        name="confirm"
        dependencies={['password']}
        placeholder={'请再次输入密码'}
        rules={[
          {
            required: true,
            message: '请再次输入密码',
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('两次密码输入不一致'));
            },
          }),
        ]}
      />

      <Input name={'username'} placeholder={'请输入昵称'} />

      <Button type="primary" htmlType="submit">
        注册并登录
      </Button>
    </BaseForm>
  );
};

export default RegisterByEmailForm;
