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

export default (props) => {
  const initialValues = {
    area_code: '+86',
  };

  const { isShowRegisterAccount } = props;

  const [loginSmsForm] = Form.useForm();
  const [isDisabledSubmit, setIsDisabledSubmit] = useState(true);
  const [formValues, setFormValues] = useState(initialValues);
  const [captchaEnable, setCaptchaEnable] = useState(false);

  const [lastTime, setLastTime] = useState();

  const checkIsDisableSubmit = useCallback(async () => {
    try {
      const result = await loginSmsForm.validateFields();
      setIsDisabledSubmit(false);
    } catch (e) {
      setIsDisabledSubmit(true);
    }
    // return false;
  }, [formValues]);

  const autoCompletePhone = (phone) => {
    if (phone.indexOf('+') == -1) {
      return `+86${phone}`;
    } else {
      return phone;
    }
  };

  const phoneCheck = (area, phone) => {
    if (
      (area == '+86' && phone && phone.length == 11) ||
      (area != '+86' && phone && phone.length >= 7 && phone.length <= 12)
    ) {
      return true;
    } else {
      return false;
    }
  };

  const handleValuesChange = useCallback(
    (changed, values) => {
      // checkIsDisableSubmit();
      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 handleRegisterClick = () => {
    if (props?.onRegisterClick) {
      props.onRegisterClick('phone');
    }
  };

  const handleResetPwdClick = () => {
    if (props?.onResetPwdClick) {
      props.onResetPwdClick('phone');
    }
  };

  const handleFinish = useCallback(
    async (values) => {
      const params = {
        grant_type: 'password',
        login_type: 'verify',
        kind: 3,
        username: formValues.area_code + formValues.phone,
        login_code: formValues.captcha,
      };
      if (
        typeof props.onBeforeSubmit === 'function' &&
        props?.onBeforeSubmit(values)
      ) {
        const loginRes = await loginService.loginByParams(params);
        if (loginRes?.error) {
          if (props?.isShowMsg) {
            message.error(loginRes?.msg || '登录失败');
          }
          if (props?.onFailed) {
            props?.onFailed(loginRes);
          }
          return;
        }
        if (props?.onSuccess) {
          if (props?.isShowMsg) {
            message.success('登录成功');
          }
          props.onSuccess(loginRes);
        }
      }
    },
    [formValues],
  );

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

  return (
    <div className={styles.smsLoginFormContainer}>
      <BaseForm
        form={loginSmsForm}
        initialValues={initialValues}
        onValuesChange={handleValuesChange}
        onFinish={handleFinish}
      >
        <Phone form={loginSmsForm} />
        <Captcha
          enable={captchaEnable}
          onSend={handleSendCaptcha}
          lastTime={lastTime}
        />
        <Button type="primary" htmlType="submit">
          登录
        </Button>
        <div className={styles.agreementInfoGroup}>
          {/* 是否同意Aminer授权协议 */}
          <Agreement />
        </div>
        <Row
          gutter={24}
          style={{
            height: '24px',
          }}
        >
          <Col span={12}>
            <Check>保持登录状态</Check>
          </Col>
          <Col span={12} className={styles.registerAndResetPwdGroup}>
            <a onClick={handleResetPwdClick}>忘记密码？</a>
            {isShowRegisterAccount ? (
              <a onClick={handleRegisterClick}>注册</a>
            ) : null}
          </Col>
        </Row>
      </BaseForm>
    </div>
  );
};
