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 { hashcode } from '../../utils/baseUtils';
import RotateTarget from './rotateTarget.js';
import ViewLayoutItem from './viewLayoutItem';

class ViewLayout extends React.Component {
    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, contentSize, esMobile) => {
        const { dashboardDesigner } = this.props;
        const { maxLayoutW } = dashboardDesigner;
        const { code, layout } = item;
        return <div key={code} data-grid={esMobile ? { x:0, y:50, w: maxLayoutW, h:8, minW: maxLayoutW, maxW: maxLayoutW, minH:8, maxH:8 } : layout} style={{ height: '100%' }}>
            <ViewLayoutItem
                item={item}
                esMobile={esMobile}
                isPreview={isPreview}
                reload={reload}
                showPreviewBox={this.showPreviewBox}
                hidePreviewBox={this.hidePreviewBox}
                contentSize={contentSize}
            />
        </div>
    }

    onLayoutChange = (layout) => {
        const { dashboardDesigner, dispatch } = this.props;
        if(!(layout.length === 1 && layout[0].i === 'default-chartview')) {
            if(hashcode(layout.map(l => ({
                x: l.x, y: l.y, w: l.w, h: l.h, maxW: l.maxW, maxH: l.maxH, minW: l.minW, minH: l.minH
            }))) === hashcode(dashboardDesigner.items.map(t => {
                let l = t.layout;
                return { x: l.x, y: l.y, w: l.w, h: l.h, maxW: l.maxW, maxH: l.maxH, minW: l.minW, minH: l.minH }
            } ))) {
                // 若未发生位置变化
                return;
            }
            dispatch({ type: 'dashboardDesigner/changeLayout', layout });
            window.clearTimeout(this.layoutChangeKey);
            this.layoutChangeKey = window.setTimeout(() => {
                var e = document.createEvent("Event");
                e.initEvent("resize", true, true);
                window.dispatchEvent(e);
            }, 500);
        }
    }

    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 <= 10) { // 鼠标接近容器底部时滚动条滚到底
            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, esMobile } = this.props;
        const { editingKey } = this.state;
        const { editMode, minLayoutHeight, maxLayoutW, layoutMargin, theme: themeName } = dashboardDesigner;
        const { visiblePreviewBox, previewItem } = this.state;
        const children = dashboardDesigner.items.map((item) => this.createElement(item, false, !item.chartOption, contentSize, esMobile));
        return (<div className={`dashboard-viewcontent ${themeName}`} ref={node => this.viewContentRef = node}>
            <ReactGridLayout
                width={ contentSize.width }
                autoSize={true}
                cols={maxLayoutW}
                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-${((contentSize.height - 8) / 48)}`} className='default-chartview' data-grid={{ x: 0, y: 0, w: maxLayoutW, h: Math.max((contentSize.height - 8) / 48, 2) , minW: maxLayoutW, maxW: maxLayoutW, static: true }}> */}
                {(children.length === 0) ? <div key='default-chartview' className='default-chartview' data-grid={{ x: 0, y: 0, w: maxLayoutW, h: 2, minW: maxLayoutW, maxW: maxLayoutW, minH: 2, maxH: 2, static: true }}>
                    <EmptyContent />
                </div> : children}
            </ReactGridLayout>
            {visiblePreviewBox && <Modal
                className={`previewbox ${themeName} ${esMobile ? 'es-mobile' : ''}`}
                width={'100%'}
                height={'100%'}
                visible={visiblePreviewBox}
                onCancel={this.hidePreviewBox}
                footer={null}
                keyboard={true}
                maskClosable={true}
                >
                    {esMobile && <RotateTarget />}
                    {!!previewItem && this.createElement(dashboardDesigner.items.find(item => item.code === previewItem.code), true, false, {width: document.body.offsetWidth-36*2, height:document.body.offsetHeight - 40}, esMobile)}
            </Modal>}
        </div>);
    }
}

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