// @ts-nocheck
import React, { useCallback, useState } from 'react';
import { FM, FormattedMessage } from '@/locales';
import Agreement from '@/components/agreement';

import styles from './styles.less';

import { Form, Button, message, Row, Col } from 'antd4';
import { DownOutlined, UpOutlined } from '@ant-design/icons';

import BaseForm from '@/components/form';

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

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

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

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

  const phone_pattern = /^[0-9]{7,12}$/g;

  const [formValues, setFormValues] = useState({});
  const [captchaEnable, setCaptchaEnable] = useState(false);
  const [formValidate, setFormValidate] = useState(false);
  const [loading, setLoading] = useState(false);
  const [isExpand, setIsExpand] = useState(false);
  const [lastTime, setLastTime] = useState();
  const { positions, subjects } = props;

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

  const handleSendCaptcha = useCallback(async () => {
    let phone = formValues.area_code + formValues.phone;
    let data = await loginService.sendCodeToPhoneUnRegistered({
      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,
      nickname: values.nickname,
      title: values.title || '',
      subject: values.subject || '',
    };
    if (props?.onFinish) {
      props.onFinish(payload, setLoading);
    }
  };

  return (
    <BaseForm
      initialValues={initialValues}
      form={registerByPhoneForm}
      name="registerByPhone"
      onFinish={handleFormFinish}
      onValuesChange={handleValuesChange}
      onFieldsChange={(_, allFields) => {
        setFormValidate(
          allFields
            .slice(1, 5) //TODO 手动排除区号 后面再改更好的写法
            .every(({ touched, errors }) => touched && errors?.length === 0),
        );
      }}
    >
      <Phone
        isShowMask
        name={'phone'}
        rules={[
          () => ({
            validator(_, value) {
              return new Promise(async (resolve, reject) => {
                if (!phone_pattern.test(value)) {
                  resolve();
                } else {
                  const payload = { phone: '+86' + value };
                  const data = await commonService.checkIsExistPhone(payload);
                  if (data && data.error) {
                    reject(
                      new Error(
                        FormattedMessage({
                          id: 'common.sign.up.phone.input.exist.message',
                          defaultMessage: 'Phone already exists',
                        }),
                      ),
                    );
                  } else {
                    resolve();
                  }
                }
              });
            },
          }),
        ]}
      />
      <Captcha
        isShowMask
        enable={captchaEnable}
        onSend={handleSendCaptcha}
        lastTime={lastTime}
      />
      <Password
        isShowMask
        placeholder={FormattedMessage({
          id: 'common.sign.up.account.pwd.input.placement',
          defaultMessage: 'Please enter the password',
        })}
        // rules={[
        //   {
        //     required: true,
        //     message: FormattedMessage({
        //       id: 'common.reset.pwd.repeat.pwd.input.placement',
        //       defaultMessage: 'Please enter the password again',
        //     }),
        //   },
        // ]}
      />
      <Password
        isShowMask
        name="confirm"
        dependencies={['password']}
        placeholder={FormattedMessage({
          id: 'common.reset.pwd.repeat.pwd.input.placement',
          defaultMessage: 'Please enter the password again',
        })}
        rules={[
          {
            required: true,
            message: FormattedMessage({
              id: 'common.reset.pwd.repeat.pwd.input.placement',
              defaultMessage: 'Please enter the password again',
            }),
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('password') === value) {
                return Promise.resolve();
              }
              return Promise.reject(
                new Error(
                  FormattedMessage({
                    id: 'common.reset.pwd.repeat.pwd.input.noteq',
                    defaultMessage: 'The two passwords are inconsistent',
                  }),
                ),
              );
            },
          }),
        ]}
      />

      <div
        style={{
          fontSize: '12px',
          color: '#1679ff',
          cursor: 'pointer',
          marginTop: '-12px',
          marginBottom: '5px',
        }}
        onClick={() => setIsExpand((isExpand) => !isExpand)}
      >
        {isExpand ? (
          <>
            <FM id="common.less" />
            <UpOutlined />
          </>
        ) : (
          <>
            <FM id="common.tip" />
            <DownOutlined />
          </>
        )}
      </div>
      {isExpand ? (
        <>
          <Input
            name={'nickname'}
            placeholder={FormattedMessage({
              id: 'common.sign.up.account.nickname.input.placement',
              defaultMessage: 'Please enter nickname',
            })}
          />

          <Row gutter={10}>
            <Col span={12}>
              <Select
                placeholder={FormattedMessage({
                  id: 'common.sign.up.account.title.input.placement',
                  defaultMessage: 'Please enter title',
                })}
                name={'title'}
                key={'email'}
                optionList={positions}
              />
            </Col>
            <Col span={12}>
              <Select
                placeholder={FormattedMessage({
                  id: 'common.sign.up.account.subject.input.placement',
                  defaultMessage: 'Please enter subject',
                })}
                name={'subject'}
                key={'email'}
                optionList={subjects}
              />
            </Col>
          </Row>
        </>
      ) : null}

      <Button
        type="primary"
        htmlType="submit"
        loading={loading}
        disabled={!formValidate}
      >
        <FM id="common.sign.up.account.title" defaultMessage="Register" />
      </Button>
      <div className={styles.agreementInfoGroup}>
        <Agreement />

        <div className={styles.goLoginGroup}>
          <span>
            <FM
              id="common.sign.up.account.back.title"
              defaultMessage="Already have an AMiner account"
            />
          </span>
          <a onClick={props?.handleGoLoginGroup} style={{ marginLeft: '5px' }}>
            <FM
              id="common.sign.up.account.login.title"
              defaultMessage="log in directly"
            />
          </a>
        </div>
      </div>
    </BaseForm>
  );
};

export default RegisterByPhoneForm;
