import React, { useEffect, useMemo } from 'react';
import { Utils } from '@easyv/react-gui';
import { pathnameIsSpaceShip } from 'utils/spaceship';

const { reduceConfig } = Utils;

export default function useScreenStyle(config, { width, height }) {
  const reducedConfig: any = reduceConfig(config);
  const { dimension = {}, component = {}, style = {} } = reducedConfig;
  const { zoom } = component;
  const { backgroundColor = '#313239' } = style;

  useEffect(() => {
    document.body.style.backgroundColor = backgroundColor;
  }, [backgroundColor]);

  const containerStyle = useMemo(() => {
    const isMergespaceShipConfig = pathnameIsSpaceShip();
    const zoomY = height / dimension.height;
    const zoomX = width / dimension.width;
    let transform;
    let top = 0;
    let left = 0;
    if (zoom === '0') {
      // 按屏幕比例适配
      const scale = Math.min(zoomX, zoomY);
      const marginLeft = (width - dimension.width * scale) / 2;
      const marginTop = (height - dimension.height * scale) / 2;
      transform = isMergespaceShipConfig ? `scale(${scale}) translate(-50%, -50%)` : `scale(${scale})`;
      left = marginLeft < 0 ? 0 : marginLeft;
      top = marginTop < 0 ? 0 : marginTop;
    } else if (zoom === '1') {
      // 强制铺满
      transform = `scale(${zoomX}, ${zoomY})`;
      if (isMergespaceShipConfig) {
        const scale = Math.min(zoomX, zoomY);
        const marginLeft = (width - dimension.width * scale) / 2;
        const marginTop = (height - dimension.height * scale) / 2;
        left = marginLeft < 0 ? 0 : marginLeft;
        top = marginTop < 0 ? 0 : marginTop;
        transform = `scale(${scale}) translate(-50%, -50%)`;
      }
    } else if (zoom === '2') {
      // 原比例展示溢出滚动
      const scale = Math.max(zoomX, zoomY);
      const marginLeft = (width - dimension.width * scale) / 2;
      const marginTop = (height - dimension.height * scale) / 2;
      transform = isMergespaceShipConfig ? `scale(${scale}) translate(-50%, -50%)` : `scale(${scale})`;
      left = marginLeft < 0 ? 0 : marginLeft;
      top = marginTop < 0 ? 0 : marginTop;
    }

    return {
      width: dimension.width,
      height: dimension.height,
      transform,
      top,
      left
    };
  }, [width, height, dimension.width, dimension.height]);

  return containerStyle;
}
