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

import {
  Button,
  Form,
  Input,
} from 'antd';
import omit from 'omit.js';

import styles from './index.less';
import LoginContext from './LoginContext';
import ItemMap from './map';

const FormItem = Form.Item;

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) => {
    Http.sendMessVerificationCode({
      phoneNumber: mobile
    }, {
      ignoreSite: true,
      cacheBust: true
    }).then(res => {
      if(res) {
        setExt(res.ext);
        setTiming(true);
      }
    }).catch(error => {
      message.error("获取验证码失败")
    })
  }, []);
  
  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();
      }
      return Promise.reject('验证码填写错误，请重新获取');
    };
    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 => {
                      console.log(error)
                    })
                  }}
                >
                  {timing ? `验证码已发送(${count})` : '获取短信验证码'}
                </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;
