import React, { forwardRef, useEffect, useRef, useState } from 'react';

import { Modal } from 'antd';
import { Helmet, HelmetProvider } from 'react-helmet-async';
import { connect } from 'react-redux';
import { useHistory, withRouter } from '@wisdom-utils/runtime';
import { actionCreators } from '@/containers/App/store';
import defaultSetting from '../../../../../../../config/defaultSetting';
import LoginAction from '../../../login';
import styles from './index.less';
import Account from '../../../js/useAccount';
import { defaultApp } from '../../../../../../micro';
import QRCode from 'qrcode.react';
import classnames from 'classnames';

const renderQRCode = props => {
  const qrcodes = props.qrcode.split('|') || [];
  if (qrcodes.length > 0 && qrcodes[0]) {
    let value = qrcodes[0].replace(/{ip}/gi, props.ip || window.location.host).split('=')[1];
    return <QRCode value={value} />;
  }
  return <span>手持APP下载未配置</span>;
};

const Login = forwardRef((props, _ref) => {
  const sliVerify = useRef();
  const loginFormRef = useRef();
  const formRef = useRef(null);
  const [status, setStatus] = useState('normal');

  const [autoLogin, setAutoLogin] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [type, setType] = useState('Account');
  const [visible, setVisible] = useState(false);
  const history = useHistory();
  const [action, setAction] = useState(() => new LoginAction(Object.assign({}, props, { history }), setVisible, false));

  const handleSubmit = values => {
    /* eslint-disable */
    action &&
      (type === 'Account'
        ? action.loginHandler(values.userName, values.password, null, autoLogin, sliVerify)
        : type === 'Mobile'
        ? action.phoneLoginFormHandler(values.mobile, values.captcha)
        : null);

    setSubmitting(true);
    props.updateCurrentIndex && props.updateCurrentIndex(-1);
  };

  useEffect(() => {
    action &&
      action.events.on('loginSuccess', event => {
        setSubmitting(false);
        props.updateCurrentIndex && props.updateCurrentIndex(0);
        props.history.push(`/?client=${props.global.client}`);
        // window.share.event.emit('triggerMicro', props.global);
        // initMicroApps();
        defaultApp();
      });
    action &&
      action.events.on('loginError', event => {
        setVisible(false);
        setSubmitting(false);
      });
    action &&
      action.events.on('loginVisible', status => {
        setVisible(status);
      });
    return () => {
      action && action.events && action.events.removeAllListeners('loginSuccess');
      action && action.events && action.events.removeAllListeners('loginError');
      action && action.events && action.events.removeAllListeners('loginVisible');
    };
  }, [props.loginMode]);

  useEffect(() => {
    setSubmitting(false);
  }, [visible]);

  const renderPlatform = () => {
    const template = props.global.loginTemplate;
    const params = {
      fromRef: formRef,
      type,
      setType,
      status,
      submitting,
      autoLogin,
      setAutoLogin,
      action,
      onSubmit: handleSubmit,
      loginMode: props.loginMode,
      updateLoginMode: props.updateLoginMode,
      welcome: null,
    };
    return <Account {...params} />;
  };
  /* eslint-disable */


  return (
    <HelmetProvider>
      <Helmet>
        <title>{props.global.title || defaultSetting.title}</title>
        <meta name="description" content={props.global.title || defaultSetting.title} />
      </Helmet>
      <div className={styles.login}>
        <div className={styles['inner-wrapper']}>
          <div className={styles['inner-center']}>
            <div className={styles['img-wrapper']} />
            <div className={classnames(styles['inner-bg'], styles['login-part'])} ref={loginFormRef}>
              {renderPlatform()}
            </div>
            <div className={styles['APPcodeBox']}>
              <p className={styles['APPCtext']}>查看二维码,扫码下载APP</p>
              <div className={styles['APPCimg']}>{renderQRCode(props.global)}</div>
            </div>
          </div>
        </div>

        <Modal centered visible={visible} width={340} footer={null} closable={false} bodyStyle={{ padding: '15px' }}>
          <div ref={sliVerify} />
        </Modal>
      </div>
    </HelmetProvider>
  );
});

const mapStateToProps = state => ({
  global: state.getIn(['global', 'globalConfig']),
  loginMode: state.getIn(['global', 'loginMode']),
});

const mapDispatchToProps = dispatch => ({
  updateConfig(config) {
    dispatch(actionCreators.getConfig(config));
  },
  createContext(data) {
    dispatch(actionCreators.createContext(data));
  },
  updateLoginMode(mode) {
    dispatch(actionCreators.changeLoginMode(mode));
  },
  updateCurrentIndex(index) {
    dispatch(actionCreators.updateCurrentIndex(index));
  },
});
export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(withRouter(Login));