import '@wisdom-utils/utils/lib/helpers/format';
import { params } from '@wisdom-utils/utils/lib/helpers';
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import { useHistory } from '@wisdom-utils/runtime';
import { actionCreators } from '@/containers/App/store';
import LoginAction from './login';
import { defaultApp } from '../../../micro';
const Login = forwardRef((props, _ref) => {
  const history = useHistory();
  const [action, setAction] = useState(
    () =>
      new LoginAction(Object.assign({}, props, { history }), () => {}, false),
  );
  const [redirect] = useState(() => {
    const param = params.getParams('redirect')?.replaceAll(';', '&');
    return param ? decodeURIComponent(escape(param)) : null;
  });

  // 需要在 GetGateWay 和 GetConfig 之后再执行登录。避免信息错落乱
  const hasLogin = useRef();
  useEffect(() => {
    action.globalConfig = props.global;
    if (props.global && props.global.hasOwnProperty('products') && hasLogin.current !== true) {
      hasLogin.current = true;
      action.init();
    }
  }, [action.globalConfig, props.global]);

  useEffect(() => {
    action &&
      action.events.on('loginSuccess', event => {
        // http://127.0.0.1:8080/civbase/civweb4/
        //   props.updateConfig(Object.assign({}, props.global, {
        //       homepage:  params.getParams('redirect')
        //   }));
        // props.history.push('/' + params.getParams('redirect'))
        props.history.push(
          `/?client=${props.global.client}`,
        );
        // window.share.event.emit('triggerMicro', props.global);
        // initMicroApps();
        defaultApp(redirect);
      });
      return () => {
        action && action.events && action.events.removeAllListeners('loginSuccess');
      }
  }, [action, props.global.client, props.global.generateType, props.history]);

  return <div>{props.children}</div>;
});

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);