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 useTime from '../../../js/useTime';

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 currentDate = useTime(); // 计时时间

  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,
    };
    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.loginCenter}>
        <div className={styles.loginCtop}>
          <div className={styles.loginCTleft}>
            <img src={props.global &&
            props.global.transformDevAssetsBaseURL &&
            props.global.transformDevAssetsBaseURL("assets/images/login/江水置换/小logo@2x.png")} alt="" />
            <p>平乡县水务局智慧水务综合管控平台</p>
          </div>
          <div className={styles.loginCTright}>
            <p className={styles.time}>{currentDate.time}</p>
            <div className={styles.dateBox}>
              <p className={styles.week}>{currentDate.dayofweek}</p>
              <p className={styles.date}>{currentDate.date}</p>
            </div>
          </div>
        </div>

        <div className={styles.loginCcenter}>
          <img src={props.global &&
            props.global.transformDevAssetsBaseURL &&
            props.global.transformDevAssetsBaseURL("assets/images/login/江水置换/形状 559@2x.png")} alt="" className={styles.loginCCtitleImg} />
          <div className={styles.loginCCbottomBox}>
            <img src={props.global &&
            props.global.transformDevAssetsBaseURL &&
            props.global.transformDevAssetsBaseURL("assets/images/login/江水置换/图@2x.png")} alt="" className={styles.loginCCbigImg} />
            <div className={styles.loginCCright} ref={loginFormRef}>
              <img src={props.global &&
            props.global.transformDevAssetsBaseURL &&
            props.global.transformDevAssetsBaseURL("assets/images/login/江水置换/大logo@2x.png")} alt="" className={styles.loginCCRtitleImg} />
              <div className={styles.loginForm}>{renderPlatform()}</div>
            </div>
            <div className={styles.loginCcode}>
              <img src={props.global &&
            props.global.transformDevAssetsBaseURL &&
            props.global.transformDevAssetsBaseURL("assets/images/login/石家庄/小程序@2x.png")} alt="" />
              <div className={styles.codeBig}>{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));