import React, { useEffect, useRef } from 'react';
import { Row, Col } from 'antd';
import { getNodeStyle } from '../utils/style';
import { guid, mergeObject, SysModel } from '../utils';
import { plugin } from './jscss';
import { PREFIX_CLS } from '../config';
import './style/index';

const prefixCls = `${PREFIX_CLS}-grid`;
export default options => {
  const ref = useRef();
  const { model, data, dispatch, children = [] } = options;
  const { style, props } = mergeObject(plugin, data);
  const { gutter, rowCells = 1 } = props;
  const span = 24 / rowCells;
  const onLoad = () => {
    const { cells = [] } = props;
    const values = cells.map(() => {
      return {
        type: 'VerLayout',
        id: guid(),
        style: {
          width: '100%',
        },
        props: {},
        pid: data.id,
        children: [],
      };
    });
    if (data.children.length === 0) {
      dispatch({
        type: 'tree/updateByKey',
        payload: {
          key: 'children',
          value: values,
          id: data.id,
          createHistory: false,
        },
      });
      dispatch({
        type: 'tree/select',
        payload: {
          data: { ...data, children: values },
        },
      });
    }
  };
  useEffect(() => {
    if (model === SysModel.DEV) {
      onLoad();
    }
  }, []);
  return (
    <div style={getNodeStyle(style)} className={`${prefixCls}`} ref={ref}>
      <Row gutter={gutter}>
        {children.map((child, index) => {
          return (
            <Col key={index.toString()} span={span}>
              {child}
            </Col>
          );
        })}
      </Row>
    </div>
  );
};
