import React from "react"
import "./viewLayout.less"
import ReactGridLayout from 'react-grid-layout'
import { connect } from 'dva'
import ChartView from './chartView'

class ViewLayout extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            items: [0, 1, 2, 3, 4].map(function (i, key, list) {
                return {
                    i: i.toString(),
                    x: i * 2,
                    y: 0,
                    w: i + 1,
                    h: 2,
                    add: i === (list.length - 1).toString()
                };
            }),
            newCounter: 0,
            width: 1100,
            editMode: true
        };
    }

    createElement = (item) => {
        const { dispatch } = this.props;
        const { code, layout, chartCode } = item;
        const removeStyle = {
            position: "absolute",
            right: "2px",
            top: 0,
            cursor: "pointer"
        };
        return (
            <div key={code} data-grid={{...layout, i: code}}>
                <ChartView chartCode={chartCode}/>
                <span className="remove" style={removeStyle} onClick={() => {
                    dispatch({ type: 'dashboardDesigner/delete', item: item });
                }}>x</span>
            </div>
        );
    }

    onLayoutChange = (layout) => {
        const { dispatch } = this.props;
        dispatch({ type: 'dashboardDesigner/changeLayout', layout });
    }

    render() {
        const { width, editMode } = this.state;
        const { dashboardDesigner } = this.props;
        const { items } = dashboardDesigner;
        const children = items.map(item => this.createElement(item));
        return (
            <div>
                <ReactGridLayout
                    width={width}
                    cols={12}
                    margin = {editMode ? [2, 2] : [0, 0]}
                    rowHeight = {100}
                    isDraggable={editMode}
                    isResizable={editMode}
                    onLayoutChange={this.onLayoutChange}
                    onBreakpointChange={this.onBreakpointChange}
                    verticalCompact={true}
                    compactType='vertical'
                >
                    {children}
                </ReactGridLayout>
            </div>
        );
    }
}

export default connect(({ present: { dashboardDesigner } }) => ({ dashboardDesigner }))(ViewLayout);
