import React from "react"
import "./viewLayout.less"
import ReactGridLayout from 'react-grid-layout'
import { Modal } from 'antd'
import { connect } from 'dva'
import EmptyContent from '../common/emptyContent/index'
import DataPreview from '../common/dataPreview/dataPreview'
import ViewLayoutItem from './viewLayoutItem';

class ViewLayout extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            previewItem: null,
            visiblePreviewBox: false,
            screenWidth: document.documentElement.clientWidth || document.body.clientWidth,
            screenHeight: document.documentElement.clientHeight || document.body.clientHeight,
            editingKey: null,
            richTextReadOnly: false,
        };
    }

    componentDidMount() {
        window.addEventListener('resize', this.onWindowResize);
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.onWindowResize);
    }

    onWindowResize = () => {
        this.setState({
            screenWidth: document.documentElement.clientWidth || document.body.clientWidth,
            screenHeight: document.documentElement.clientHeight || document.body.clientHeight
        });
    }

    createElement = (item, isPreview, reload) => {
        const { code, layout } = item;

        return <div key={code} data-grid={layout}>
            <ViewLayoutItem item={item} isPreview={isPreview} reload={reload}/>
        </div>
    }

    onLayoutChange = (layout) => {
        const { dispatch } = this.props;
        if(!(layout.length === 1 && layout[0].i === 'default-chartview')) {
            dispatch({ type: 'dashboardDesigner/changeLayout', layout });
        }
    }

    onResize = (Layout, oldItem, newItem, placeholder, e, element) => {
        const viewContentRef = this.viewContentRef;
        let box = viewContentRef.getBoundingClientRect();
        let bottomY = box.y + box.height;
        if(bottomY - e.clientY <= 5) { // 鼠标接近容器底部时滚动条滚到底
            window.clearTimeout(this.scrollToBottomKey);
            this.scrollToBottomKey = window.setTimeout(this.scrollToBottom, 50);
        }
    }

    scrollToBottom = () => {
        const viewContentRef = this.viewContentRef;
        viewContentRef.scrollTo && viewContentRef.scrollTo(0, viewContentRef.scrollHeight - viewContentRef.clientHeight)
    }

    showPreviewBox = (item) => {
        this.setState({
            previewItem: item,
            visiblePreviewBox: true,
            lastViewCode: item.code,
            lastPage: item.chartOption ? item.chartOption.page : 1,
            lastPageSize: item.chartOption ? item.chartOption.pageSize : 0,
        });
    }

    hidePreviewBox = () => {
        const { dashboardDesigner, dispatch } = this.props;
        const { lastViewCode, lastPage, lastPageSize } = this.state;
        let item = dashboardDesigner.items.find(x => x.code === lastViewCode)
        this.setState({
            previewItem: null,
            visiblePreviewBox: false
        });
        if(item.chartOption) {
            dispatch({ type: 'setItemFields', code: lastViewCode, fields: [
                { name: 'chartOption', value: { ...item.chartOption, page: lastPage, pageSize: lastPageSize } }
            ] });
        }
    }

    render() {
        const { dashboardDesigner, contentSize, dispatch } = this.props;
        const { editingKey } = this.state;
        const { editMode, minLayoutHeight, layoutMargin, theme: themeName } = dashboardDesigner;
        const { visiblePreviewBox, previewItem } = this.state;
        const children = dashboardDesigner.items.map((item) => this.createElement(item, false, !item.chartOption));
        console.log(contentSize);
        return (<div className={`dashboard-viewcontent ${themeName}`} ref={node => this.viewContentRef = node}>
            <ReactGridLayout
                width={ contentSize.width }
                autoSize={true}
                cols={12}
                margin = {editMode ? layoutMargin : layoutMargin}
                rowHeight = {minLayoutHeight}
                isDraggable={editMode && !editingKey}
                isResizable={editMode && !editingKey}
                draggableHandle='.mover'
                onLayoutChange={this.onLayoutChange}
                onResize={this.onResize}
                verticalCompact={true}
                compactType='vertical'
            >
                {(children.length === 0) ? <div key='default-chartview' className='default-chartview' data-grid={{ x: 0, y: 0, w: 12, h: 2, minW: 12, maxW: 12, minH: 2, maxH: 2, static: true }}>
                    <EmptyContent />
                </div> : children}
            </ReactGridLayout>
            {visiblePreviewBox && previewItem.chartType === 'dataView' && <DataPreview
                title={previewItem.name}
                visibleBox={visiblePreviewBox}
                hideBox={this.hidePreviewBox}
                fetchFunction={(page, pageSize) => {
                    dispatch({ type: 'dashboardDesigner/fetchDataList', item: previewItem, mandatory: true, page, pageSize });
                }}
            />}
            {visiblePreviewBox && previewItem.chartType !== 'dataView' && <Modal
                className='previewbox'
                width='80%'
                height='80%'
                visible={visiblePreviewBox}
                onCancel={this.hidePreviewBox}
                footer={null}
                keyboard={true}
                maskClosable={true}
                >
                {!!previewItem && this.createElement(dashboardDesigner.items.find(item => item.code === previewItem.code), true, false)}
            </Modal>}
        </div>);
    }
}

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