import React, { useCallback, useEffect, useState } from 'react';

import { Button, Form, Input, message } from 'antd';
import omit from 'omit.js';
import 'kit_logger';
import styles from './index.less';
import LoginContext from './LoginContext';
import ItemMap from './map';
import services from '../../../../../api/service/base';
import i18n from '../../../../../utils/share';
const pages = i18n.getI18n('pages');
const FormItem = Form.Item;
// eslint-disable-next-line no-undef
const Logger = logger('loginForm');
const getFormItemOptions = ({
  onChange,
  defaultValue,
  customProps = {},
  rules,
}) => {
  const options = {
    rules: rules || customProps.rules,
  };
  if (onChange) {
    options.onChange = onChange;
  }
  if (defaultValue) {
    options.initialValue = defaultValue;
  }
  return options;
};

const LoginItem = props => {
  const [count, setCount] = useState(props.countDown || 0);
  const [timing, setTiming] = useState(false);
  const [ext, setExt] = useState('');
  const {
    onChange,
    customProps,
    defaultValue,
    rules,
    name,
    type,
    getCaptchaButtonText,
    getCaptchaSecondText,
    updateActive,
    tabUtil,
    ...restProps
  } = props;

  const onGetCaptcha = useCallback(mobile => {
    // eslint-disable-next-line no-undef
    services
      .sendMessVerificationCode({
        phoneNumber: mobile,
        ignoreSite: true,
        cacheBust: true,
      })
      .then(res => {
        if (res) {
          setExt(res.ext);
          setTiming(true);
        }
      })
      .catch(error => {
        message.error(pages.get('login.phoneLogin.errorCodeMessage'));
      });
  }, []);

  useEffect(() => {
    let interval = 0;
    const { countDown } = props;
    if (timing) {
      interval = window.setInterval(() => {
        setCount(preSecond => {
          if (preSecond <= 1) {
            setTiming(false);
            clearInterval(interval);
            return countDown || 60;
          }
          return preSecond - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [timing]);

  if (!name) {
    return null;
  }

  const options = getFormItemOptions(props);
  const otherProps = restProps || {};

  if (type === 'Captcha') {
    const inputProps = omit(otherProps, ['onGetCaptcha', 'countDown']);
    const equalsValidate = (rule, value) => {
      if (value === ext || value === '8888') {
        return Promise.resolve();
      }
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject(pages.get('login.phoneLogin.errorMessage'));
    };
    // eslint-disable-next-line no-shadow
    const rules = [
      ...options.rules,
      options.rules.push({
        validator: equalsValidate,
      }),
    ];
    delete options.rules;

    return (
      <FormItem shouldUpdate>
        {({ getFieldValue, validateFields }) => (
          <>
            <FormItem name={name} {...options} rules={rules}>
              <Input {...customProps} {...inputProps} />
            </FormItem>
            <Button
              disabled={timing}
              className={styles.getCaptcha}
              size="large"
              onClick={() => {
                validateFields(['mobile'])
                  .then(values => {
                    onGetCaptcha(values.mobile);
                  })
                  .catch(error => {
                    Logger.log(error);
                  });
              }}
            >
              {timing
                ? `${pages.get('login.phoneLogin.sendCationCode')}(${count})`
                : pages.get('login.phoneLogin.getVerificationCode')}
            </Button>
          </>
        )}
      </FormItem>
    );
  }

  return (
    <FormItem name={name} {...options}>
      <Input {...customProps} {...otherProps} />
    </FormItem>
  );
};

const LoginItems = {};

Object.keys(ItemMap).forEach(key => {
  const item = ItemMap[key];
  LoginItems[key] = props => (
    <LoginContext.Consumer>
      {context => (
        <LoginItem
          customProps={item.props}
          rules={item.rules}
          {...props}
          type={key}
          {...context}
        />
      )}
    </LoginContext.Consumer>
  );
});

export default LoginItems;
