import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { getShowedComponents } from 'utils/layer';
import { define } from 'utils/define';
import LoadingProgress from 'components/LoadingProgress';

function LoadingContainer({ id, tenantId, screensById, panelsById, componentsById, coverImg, children }) {
  const [components] = useState<any[]>(() => {
    const showedComponents = getShowedComponents({ id, screensById, panelsById });
    const ids = Array.from(new Set(showedComponents.map((d) => d.id)));
    return ids.map((d) => showedComponents.find((e) => e.id === d));
  });
  const [complete, setComplete] = useState(0);

  useEffect(() => {
    // 加载组件js
    components.map((d) => {
      const component = componentsById[d.id];
      if (component) {
        define(
          `com_${d.id}_${d.moduleName}`,
          [d.moduleName + '@' + component.base.version],
          (com) => {
            !window.component && (window.component = {});
            window.component[d.moduleName + '@' + component.base.version] = com;
            setComplete((prev) => prev + 1);
          },
          component.from ? tenantId : undefined
        );
      } else {
        setComplete((prev) => prev + 1);
      }
    });
  }, [tenantId, components]);

  const percent = Math.floor((complete / components.length) * 100);

  const finish = percent >= 100;

  return (
    <>
      <LoadingProgress percent={percent} coverImg={coverImg} />
      {finish ? children : null}
    </>
  );
}

const mapStateToProps = ({ screenDetail, screensById, panelsById, componentsById }) => {
  const { id, tenantId } = screenDetail;

  return {
    id,
    tenantId,
    screensById,
    panelsById,
    componentsById
  };
};

export default connect(mapStateToProps)(LoadingContainer);
