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

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

import BaseForm from '@/components/form';

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

import { loginService } from '@/service';

import { phoneCheck } from '@/utils/phone';

const RegisterByPhoneForm = (props: any) => {
  const [registerByPhoneForm] = Form.useForm();

  const [formValues, setFormValues] = useState({});
  const [captchaEnable, setCaptchaEnable] = useState(false);

  const [lastTime, setLastTime] = useState();

  const initialValues = {
    area_code: '+86',
  };

  const handleSendCaptcha = useCallback(async () => {
    let phone = formValues.area_code + formValues.phone;
    let data = await loginService.sendCaptchaByPhone({
      phone,
    });
    try {
      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('验证码发送失败，请稍候重试!');
      }

    }
  }, [formValues]);

  const handleValuesChange = useCallback(
    (changed, values) => {
      if (changed.area_code || changed.phone) {
        let phone_enable = phoneCheck(values.area_code, values.phone);
        if (phone_enable && !captchaEnable) {
          setCaptchaEnable(true);
        } else if (!phone_enable && captchaEnable) {
          setCaptchaEnable(false);
        }
      }
      setFormValues(values);
    },
    [captchaEnable],
  );

  const handleFormFinish = (values) => {
    const payload = {
      phone: `${values.area_code}${values.phone}`,
      code: values.captcha,
      password: values.password,
    };
    if (props?.onFinish) {
      props.onFinish(payload);
    }
  };

  return (
    <BaseForm
      initialValues={initialValues}
      form={registerByPhoneForm}
      name="registerByPhone"
      onFinish={handleFormFinish}
      onValuesChange={handleValuesChange}
    >
      <Phone isShowMask name={'phone'} />
      <Captcha
        isShowMask
        enable={captchaEnable}
        onSend={handleSendCaptcha}
        lastTime={lastTime}
      />
      <Password
        isShowMask
        placeholder={'请输入密码，建议六位以上带有特殊符号'}
        rules={[
          {
            required: true,
            message: '请再次输入密码',
          },
        ]}
      />
      <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
        isShowMask={false}
        name={'nickname'}
        placeholder={'请输入昵称'}
        // rules={[
        //   {
        //     required: true,
        //     message: '昵称不为空',
        //   },
        // ]}
      />

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

export default RegisterByPhoneForm;
