import { createElement, Fragment } from '__RAX_OR_REACT__';
import classNames from 'classnames';
import { string, func, object, arrayOf } from 'prop-types';

function getStyle(axisProps) {
  const [col, row] =
    axisProps.length > 1
      ? axisProps.map(({ options }) => options.length + 1)
      : [2, axisProps[0].options.length + 1];

  return {
    gridTemplate: `repeat(${row}, auto)/100px repeat(${
      col - 1
    }, minmax(min-content, 1fr))`,
  };
}

function Block(props) {
  const { name, title, axisProps, render, groupOption, theme } = props;

  const isOneDimensional = axisProps.length === 1; // 是否只有一个维度

  const _title = title || name;

  function renderGrid() {
    if (isOneDimensional) {
      const { name, options } = axisProps[0];

      return options.map(({ label, value }, index) => {
        return (
          <Fragment key={index}>
            <div className='y-row grid-cell'>{label}</div>
            <div className='grid-cell'>
              {render({
                [name]: value,
                ...groupOption,
                blockName: name,
                theme,
              })}
            </div>
          </Fragment>
        );
      });
    } else {
      const options = [];
      const [xOptions, yOptions] = axisProps.map(({ options }) => [
        null,
        ...options,
      ]);

      yOptions.forEach(y => xOptions.forEach(x => options.push([x, y])));

      return options.map(([x, y], index) => {
        const clsNames = classNames({
          'grid-cell': true,
          'y-row': !x && y,
        });

        return (
          <div className={clsNames} key={index}>
            {x && y
              ? render(
                  {
                    [axisProps[0].name]: x.value,
                    [axisProps[1].name]: y.value,
                    ...groupOption,
                    blockName: name,
                    theme,
                  },
                  index
                )
              : _.get(x || y, 'label')}
          </div>
        );
      });
    }
  }

  return (
    <div key={name} className='comp-block'>
      {_title ? <div className='headline3'>{_title}</div> : null}
      <div className='comp-container' style={getStyle(axisProps)}>
        {renderGrid()}
      </div>
    </div>
  );
}

Block.propTypes = {
  name: string,
  title: string,
  theme: arrayOf(object),
  render: func,
  groupOption: object,
  axisProps: arrayOf(object),
};

export default Block;
