// @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 { FM } from '@/locales';
import { commonService, loginService } from '@/service';
import {
  phoneCheck,
  autoCompletePhone,
  checkPhoneByPhonePattern,
  phonePattern,
} from '@/utils/phone';

import styles from './styles.less';
import Agreement from '@/components/agreement';

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

  const { isShowRegisterAccount } = props;

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

  const [lastTime, setLastTime] = useState();
  const [errorInfo, setErrorInfo] = useState('');

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

  // 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 handleValuesChange = useCallback(
    (changed, values) => {
      setErrorInfo('');
      if (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) => {
      setLoading(true);
      const params = {
        grant_type: 'password',
        login_type: 'register',
        // 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);
        setLoading(false);
        if (loginRes?.error) {
          // if (props?.isShowMsg) {
          //   message.error(loginRes?.msg || '登录失败');
          // }
          setErrorInfo(loginRes?.msg || '登录失败');
          if (props?.onFailed) {
            props?.onFailed(loginRes);
          }
          return;
        }
        if (props?.onSuccess) {
          if (props?.isShowMsg) {
            message.success('登录成功');
          }
          props.onSuccess(loginRes);
        }
      }
    },
    [formValues],
  );

  const sendCaptchaByPhone = async (formValuesPhone) => {
    try {
      const phone = autoCompletePhone(formValuesPhone || '');
      let data = await loginService.sendRegisterLoginCaptchaByPhone({
        phone,
      });
      if (data.error) {
        throw new Error(data?.msg);
      } else {
        setLastTime(() => new Date().getTime());
        message.success('验证码发送成功，请查收!');
      }
    } catch (e) {
      if (e?.message === '60秒内不能发送多次验证码') {
        message.error(e?.message);
      } else {
        message.error('验证码发送失败，请稍候重试!');
      }
    }
  };

  const checkPhoneIsRegistered = async (formValuesPhone) => {
    const payload = { phone: autoCompletePhone(formValuesPhone) };
    const result = await commonService.checkIsExistPhone(payload);
    if (result && result.data) {
      if (!result.data.isExist) {
        loginSmsForm.setFields([
          {
            name: 'phone',
            errors: ['登录的手机需要先注册'],
          },
        ]);
      }
      return result.data.isExist;
    } else {
      loginSmsForm.setFields([
        {
          name: 'phone',
          errors: ['手机号校验异常'],
        },
      ]);
      return false;
    }
  };

  const handleSendCaptcha = useCallback(async () => {
    // 首先check -> sendCaptchaByPhone
    try {
      if (
        checkPhoneByPhonePattern(formValues?.phone)
        // && (await checkPhoneIsRegistered(formValues?.phone))
      ) {
        await sendCaptchaByPhone(formValues?.phone);
      } else {
        setCaptchaEnable(false);
      }
    } catch (e) {
      setCaptchaEnable(false);
    }
  }, [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) {
  //     if (e?.message === '60秒内不能发送多次验证码') {
  //       message.error(e?.message);
  //     } else {
  //       message.error('验证码发送失败，请稍候重试!');
  //     }
  //   }
  // }, [formValues]);

  return (
    <div className={styles.smsLoginFormContainer}>
      <BaseForm
        form={loginSmsForm}
        initialValues={initialValues}
        onValuesChange={handleValuesChange}
        onFinish={handleFinish}
        onFieldsChange={(_, allFields) => {
          setFormValidate(
            allFields
              .slice(1, 3)
              .every(({ touched, errors }) => touched && errors?.length === 0),
          );
        }}
      >
        <Phone form={loginSmsForm} />
        <Captcha
          enable={captchaEnable}
          onSend={handleSendCaptcha}
          lastTime={lastTime}
        />
        <Button
          type="primary"
          htmlType="submit"
          loading={loading}
          disabled={!formValidate}
        >
          <FM id="common.login.btn.title" defaultMessage="Login" />
        </Button>
        <div className={styles.agreementInfoGroup}>
          {/* 是否同意Aminer授权协议 */}
          <Agreement />
        </div>
        <Row
          gutter={24}
          style={{
            height: '24px',
          }}
        >
          <Col span={9}>
              <Check name={'keep_login'}>
                <FM
                  id="common.keep.login.status.title"
                  defaultMessage="Keep me logged in"
                />
              </Check>
          </Col>
          <Col span={15} className={styles.registerAndResetPwdGroup}>
            <a onClick={handleResetPwdClick}>
              <FM
                id="common.pwd.login.forget.pwd.title"
                defaultMessage="Forget the password?"
              />
            </a>
            {isShowRegisterAccount ? (
              <a onClick={handleRegisterClick}>
                <FM
                  id="common.sign.up.account.title"
                  defaultMessage="Register"
                />
              </a>
            ) : null}
          </Col>
        </Row>
        {errorInfo ? (
          <div className={styles.errorInfoGroup}>{errorInfo}</div>
        ) : null}
      </BaseForm>
    </div>
  );
};
