import 'kit_utils/lib/format';

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

import { Modal } from 'antd';
import classNames from 'classnames';
import { dom } from '@wisdom-utils/utils/lib/helpers';
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 useRenderQcode from '../../js/useRenderQcode';
import Account from '../../js/useAccount';
import IotComponent from '../../js/useIOTComponent';
import { defaultApp } from '../../../../../micro';
import QRCode from 'qrcode.react';

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 footerRef = useRef();
  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 renderAddons = useRenderQcode(props.global);
  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.main}>
        <video
          class={styles.layer1}
          src={
            props.global &&
            props.global.transformDevAssetsBaseURL &&
            props.global.transformDevAssetsBaseURL('assets/videos/water.mp4')
          }
          muted={true}
          poster={
            props.global &&
            props.global.transformDevAssetsBaseURL &&
            props.global.transformDevAssetsBaseURL('/assets/videos/water.png')
          }
          autoPlay={true}
          loop={true}
        />
        <div className={styles.layer2}>
          <div class={styles['title-block']}>
            <img
              role="logo"
              src={
                props.global &&
                props.global.transformDevAssetsBaseURL &&
                props.global.transformDevAssetsBaseURL(props.global.logo)
              }
            />
            <h1>{props.global.title}</h1>
            <h2>{window.globalConfig && window.globalConfig.subtitle}</h2>
          </div>
          <div className={classNames(styles['login-block'], styles.caseHide, 'animate__animated')} ref={loginFormRef}>
            <div className={styles['login-form']}>{renderPlatform()}</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>

        <div className={classNames(styles.footerCase, 'animate__animated')} ref={footerRef}>
          <div className={classNames(styles.quickMark)}>{renderAddons}</div>
          <span className={classNames(styles.copyright)}>
            Copyright ©
            <a target="_blank" href="https://panda-water.cn">
              熊猫智慧水务
            </a>
            {new Date().getFullYear()} All Rights Reserved{' '}
            <a target="_blank" id="IndexCaseNumber" href="">
              沪ICP备11036640-1
            </a>
            <span className="addons">
              <span className="split" />
              <a id="qrcode">
                <span className="glyphicon glyphicon-qrcode" role="button" title="手持APP下载" />
              </a>
            </span>
          </span>
        </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));