// @ts-nocheck
import React, { useState, useEffect, useCallback } from 'react';
import { Form, message, Row, Col } from 'antd4';
import { Phone, Captcha, Button, Check } from '@/components/form_items';
import { commonService, loginService } from '@/service';
import styles from './styles.less';
import Agreement from '@/components/agreement';

import BaseForm from '@/components/form';

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

export default (props) => {
  const { cd, lastTime } = props;

  const initialValues = {
    area_code: '+86',
  };
  const [formValues, setFormValues] = useState(initialValues);
  const [captchaEnable, setCaptchaEnable] = useState(false);

  const handleValuesChange = useCallback(
    (changed, values) => {
      if (props?.errorInfo && props?.onClearErrorInfo) {
        props?.onClearErrorInfo();
      }
      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 handleFinish = async (values) => {
    const params = {
      phone: formValues.area_code + formValues.phone,
      login_code: formValues.captcha,
    };
    if (
      typeof props.onBeforeSubmit === 'function' &&
      props?.onBeforeSubmit(values)
    ) {
      if (props?.onFinish) {
        props.onFinish(params);
      }
    }
  };

  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);
      }
      message.success('验证码发送成功，请查收!');
    } catch (e) {
      message.error('验证码发送失败，请稍候重试!');
      throw e;
    }
  }, [formValues]);

  return (
    <div className={styles.bindPhoneFormContainer}>
      <BaseForm
        initialValues={initialValues}
        onValuesChange={handleValuesChange}
        onFinish={handleFinish}
      >
        <Phone
          rules={[
            () => ({
              validator(_, value) {
                return new Promise(async (resolve, reject) => {
                  const payload = { phone: `${formValues.area_code}${value}` };
                  const result = await commonService.checkIsExistPhone(payload);
                  if (result && result?.data?.isExist) {
                    if (props?.type === 'business') {
                      reject('该手机号已被占用,请更换号码或联系商务');
                    } else {
                      reject('手机号已被占用,请更换号码');
                    }
                  } else {
                    resolve();
                  }
                });
              },
            }),
          ]}
        />
        <Captcha
          enable={captchaEnable}
          onSend={handleSendCaptcha}
          cd={cd}
          lastTime={lastTime}
        />
        <div className={styles.agreementInfoGroup}>
          {/* 是否同意Aminer授权协议 */}
          <Agreement />
        </div>
        <Button type="primary" htmlType="submit">
          确定
        </Button>

        {props?.errorInfo ? (
          <div className={styles.errorInfoGroup}>{props?.errorInfo}</div>
        ) : null}
      </BaseForm>
    </div>
  );
};
