import React, { memo, useContext, useEffect } from 'react';
import GridLayout, { ItemCallback } from 'react-grid-layout';
import DynamicEngine from 'editorCore/DynamicEngine';
import styles from './viewRender.less';
import { useDispatch } from 'react-redux';
import { dooringContext } from '../layouts';

interface PointDataItem {
  id: string;
  item: Record<string, any>;
  point: Record<string, any>;
}

interface ViewProps {
  pointData: Array<PointDataItem>;
  pageData?: any;
  width?: number;
  dragStop?: ItemCallback;
  onDragStart?: ItemCallback;
  onResizeStop?: ItemCallback;
}

const ViewRender = memo((props: ViewProps) => {
  const { pointData, pageData, width, dragStop, onDragStart, onResizeStop } = props;
  const dispatch = useDispatch()
  console.log(
    pointData.map((item) => item.point),
    '显示数据111',
    pointData,
  );
  const context = useContext(dooringContext);
  useEffect(() => {
    pointData.forEach((p, index) => {
      if (p.item.type === 'PhotoAds') {
        p.item?.config?.imgList?.forEach((i, idx) => {
          context.addImageLoadingNum(`${index}-${idx}`)
        })
      }
    })
  }, [])
  return (
    <GridLayout
      cols={24}
      rowHeight={2}
      width={width}
      margin={[0, 0]}
      onDragStop={dragStop}
      onDragStart={onDragStart}
      onResizeStop={onResizeStop}
      layout={pointData.map((item) => item.point) || null}
      onLayoutChange={(layout) => {
        if(!layout) return
        dispatch({
          type: 'editorModal/updateLayout',
          payload: { layout },
        });
      }}
      style={{
        backgroundColor: pageData && pageData.bgColor,
        backgroundImage:
          pageData && pageData.bgImage ? `url(${pageData.bgImage[0].url})` : 'initial',
        backgroundSize: 'contain',
        backgroundRepeat: 'no-repeat',
      }}
    >
      {pointData.map((value: PointDataItem, index) => {
        
        return (
          <div
            id={value.id}
            key={value.id}
            data-grid={{ ...value.point }}
            className={styles.dragItem}
            style={
              value.item.type === 'CouponTemplate'
                ? { fontSize: `${((width / 10 / 24) * value.point.w).toFixed(0)}px` } // 宽 / 缩小倍数（方便计算em的值） / 栅格数 / 转rem系数（wap编辑器宽是750px的，生成的样式转换成rem要/100）
                : {}
            }
          >
            <DynamicEngine {...(value.item as any)} isTpl={false} index={index} />
          </div>
        );
      })}
    </GridLayout>
  );
});

export default ViewRender;
