import React, { Component } from 'react';
import PropTypes from 'prop-types';
import loadScripts from 'dt2react/lib/utils/loadScripts';
import { GlobalConfig, Event } from '@gm/graphmod-utils';
/**
 * 加载第三方js
 */
export default function connectThreePartyScripts({ scripts } = {}) {
  return function (WrappedComponent) {
    class WrapperComponent extends Component {
      constructor(props) {
        super(props);
        this.state = {
          loaded: false
        };

      }

      componentDidMount() {
        this.init();
        Event.addEventListener('_gmloadedScriptMap', () => {
          let _scripts = scripts || this.props.scripts;
          _scripts = _scripts.filter(e => GlobalConfig._gmloadedScriptMap[e.url] !== 2);
          if (_scripts.length === 0) {
            this.setState({
              loaded: true
            });
          }
        });
      }

      init = () => {
        let _scripts = scripts || this.props.scripts;
        if (_scripts) {
          GlobalConfig._gmloadedScriptMap = GlobalConfig._gmloadedScriptMap ? GlobalConfig._gmloadedScriptMap : {};
          _scripts = _scripts.filter(e => !GlobalConfig._gmloadedScriptMap[e.url]);
          if (_scripts.length > 0) {
            _scripts.filter(e => GlobalConfig._gmloadedScriptMap[e.url] = 1);
            loadScripts.loadAllByPromise(_scripts).then(
              () => {
                _scripts.forEach(e => GlobalConfig._gmloadedScriptMap[e.url] = 2);
                Event.dispatchEvent('_gmloadedScriptMap', _scripts);
              }
            ).catch(() => {
              _scripts.forEach(e => GlobalConfig._gmloadedScriptMap[e.url] = undefined);
            });
          }
        }
      }

      render() {
        const { loaded } = this.state;
        return (
          <WrappedComponent {...this.props} loaded={loaded}>
            {this.props.children}
          </WrappedComponent>
        );
      }
    }

    WrapperComponent.propTypes = {
      children: PropTypes.any,
      scripts: PropTypes.array
    };

    return WrapperComponent;
  };
}
