import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import Loading from 'components/Loading';
import Title from 'components/Title';
import { useSizeByDomId } from 'components/easyUse';
import ScreenContainer from './ScreenContainer';
import { getData } from 'models/panel-detail';
import styles from './index.less';

function PanelDetail({ match, loading, name, config, getData }) {
  const { width: windowWidth = 0, height: windowHeight = 0 } = useSizeByDomId();

  useEffect(() => {
    const { params } = match;
    const { screenId, panelId, stateId } = params;
    getData({
      screenId: +screenId,
      panelId: +panelId,
      stateId: +stateId,
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (loading) {
    return <Loading />;
  }

  const { width, height } = config;
  const scaleX = windowWidth / width;
  const scaleY = windowHeight / height;
  const minScale = Math.min(scaleX, scaleY);
  const scale = minScale > 1 ? 1 : minScale;
  const top = (windowHeight - scale * height) / 2;
  const left = (windowWidth - scale * width) / 2;

  return (
    <div className={styles.container}>
      <Title title={name} />
      <div
        className={styles.wrap}
        style={{
          transform: `scale(${scale})`,
          top,
          left,
        }}>
        <ScreenContainer />
      </div>
    </div>
  );
}

const mapStateToProps = ({ panelDetail }) => {
  const { loading, name, config } = panelDetail;

  return {
    loading,
    name,
    config,
  };
};

const mapDispatchToProps = {
  getData,
};

const PanelDetailPage = connect(mapStateToProps, mapDispatchToProps)(PanelDetail);

export default PanelDetailPage;
