import 'kit_utils/lib/format';

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

import { Modal } from 'antd';
// eslint-disable-next-line import/no-unresolved
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 } from '@wisdom-utils/runtime';
import { actionCreators } from '@/containers/App/store';
import Cookies from 'js-cookie';
import defaultSetting from '@/../config/defaultSetting';
import { defaultApp } from '@/micro';
import LoginAction from '../../login';
import styles from './style.less';
import useRenderQcode from '../../js/useRenderQcode';
import Account from '../../js/useAccount';
import IotComponent from '../../js/useIOTComponent';
const Login = forwardRef((props, _ref) => {
  const videoRef = useRef();
  const loginRef = useRef();
  const timeRef = useRef();
  const titleRef = useRef();
  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 [currentDate, setCurrentDate] = useState({});
  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 [showVideo, setShowVideo] = useState(false);
  let { ddCode } = props.global;
  const loginMode = Cookies.get('loginMode') || null;
  if (loginMode && loginMode === 'iotWechat') ddCode = null;
  // useEffect(() => {
  //   action.globalConfig = props.global;
  // }, [props.global]);

  const GetParams = params => {
    const obj = {};
    if (params && params.length) {
      params.forEach(ele => {
        if (ele && ele.includes('=')) {
          const [temp1, temp2] = ele.split('=');
          obj[temp1] = temp2;
        }
      });
    }
    return obj;
  };

  const paramsObj = GetParams(props.loginParams);

  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(() => {
    // if (props.loginMode === LOGIN_WAY.WeChart) {
    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]);

  let loginTimeInterval = null;
  let videoTimeout = null;
  useEffect(() => {
    if (loginTimeInterval)
      clearInterval(loginTimeInterval), (loginTimeInterval = null);
    loginTimeInterval = setInterval(() => {
      const date = new Date();
      const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      const time = `${date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()
        }:${date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()
        }:${date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()
        }`;
      setCurrentDate({
        time,
        dayofweek: weekday[date.getDay()],
        date: date.pattern('yyyy/MM/dd'),
      });
    }, 1000);
    return () => {
      loginTimeInterval && clearInterval(loginTimeInterval);
    };
  }, []);

  useEffect(() => {


    return () => {
      videoTimeout && clearTimeout(videoTimeout);
      videoRef && videoRef.current && videoRef.current.removeEventListener('ended', () => { });
    };
  }, [videoRef]);
  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,
    };
    switch (template) {
      case 'DarkCloud.html':
      case 'Dark.html':
        return <Account {...params} />;
      case 'Dark - IOTMultiLogin.html':
        return <IotComponent {...params} />;
      default:
        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}>

        <div className={classNames(styles.inner, styles.noEffect)}>
          <div
            className={classNames(styles.loginTime, styles.loginTimeShow)}
            ref={loginRef}
          >
            <img
              role="logo"
              src={props.global && props.global.transformDevAssetsBaseURL && props.global.transformDevAssetsBaseURL(props.global.logo)}
            />
            <div
              className={classNames(
                styles.titleCase,
                'animated',
              )}
              ref={titleRef}
            >
              <span className={styles.title}>{props.global.title}</span>
              <span className={styles.subtitle}>
                {window.globalConfig && window.globalConfig.subtitle}
              </span>
            </div>
          </div>
          <span
            className={classNames(
              styles.divider,
              'animate__animated',
            )}
          />
          <div
            className={classNames(
              styles.timeCase,
              'animate__animated',
            )}
            ref={timeRef}
          >
            <span className={styles.time}>{currentDate.time}</span>
            <span className={styles.dayofweek}>{currentDate.dayofweek}</span>
            <span className={styles.date}>{currentDate.date}</span>
          </div>
          <div
            className={classNames(
              styles['login-block'],
              'animate__animated',
            )}
            ref={loginFormRef}
          >
            <div>
              <img src={require('@/assets/images/login/dark/login.png')} />
            </div>
            <div className={styles['login-form']}>{renderPlatform()}</div>
          </div>
        </div>
        <div
          className={classNames(
            styles.footerCase,
            'animate__animated',
          )}
          ref={footerRef}
        >
          <div className={classNames(styles.quickMark)}>{renderAddons}</div>
          {
            (paramsObj && !paramsObj.noCopyright) &&
            <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="https://beian.miit.gov.cn">
                沪ICP备18045097号-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,
)((Login));