import React from "react"
import "./viewLayout.less"
import ReactGridLayout from 'react-grid-layout'
import { Icon, Input } from 'antd'
import { connect } from 'dva'
import ChartView from './chartView'
import EmptyContent from '../common/emptyContent/index'
import DataPreview from '../common/dataPreview/dataPreview'

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
        });
    }

    modifyItem = (item) => {
        const { dispatch } = this.props;
        dispatch({ type: 'dashboardDesigner/modifyItem', item });
    }

    createElement = (item, isPreview, reload) => {
        const { dispatch, main, dashboardDesigner } = this.props;
        const { editingKey, richTextReadOnly } = this.state;
        const { currentUser } = main;
        const { editMode, minLayoutHeight } = dashboardDesigner;
        const { code, name, viewType, layout, chartCode, chartOption } = item;
        const iconCls = editMode ? 'visible-icon' : '';

        return (
            <div className={`chartview${ isPreview ? ' chartview-preview' : (editMode ? ' chartview-edit' : '')}`} key={code} data-grid={layout}>
                <div className='chartview-toolbar mover'>
                    <div className='chart-title'>
                        {editingKey && editingKey === code ? <Input width={200} ref={node => this['inputRef-' + code] = node} defaultValue={name} onBlur={(e) => {
                            let value = e.target.value
                            this.setState({
                                editingKey: null,
                                richTextReadOnly: false,
                            }, () => {
                                !!value.trim() && this.modifyItem({ ...item, name: value });
                            });
                        // TODO 这里使用onPressEnter在存在富文本类型时会出问题
                        // }} onPressEnter={(e) => {
                        //     let value = e.target.value
                        //     this.setState({
                        //         editingKey: null,
                        //         // richTextReadOnly: false,
                        //     }, () => {
                        //         !!value.trim() && this.modifyItem({ ...item, name: value });
                        //     });
                        }}/> : <span>{name}</span>}
                        <div className='tools'>
                            {editMode && (!editingKey || editingKey !== code) && <Icon type='edit' title='修改' style={{ cursor: 'pointer', marginLeft: '8px' }} onClick={() => {
                                this.setState({
                                    editingKey: code,
                                    richTextReadOnly: true,
                                }, () => {
                                    this['inputRef-' + code].focus();
                                })
                            }}/>}
                        </div>
                    </div>
                    <div className='chart-tools'>
                        {viewType !== 'richText' && <Icon className={iconCls} type="reload" theme="outlined" onClick={() => {
                            let page = chartOption ? chartOption.page : 1;
                            let pageSize = chartOption ? chartOption.pageSize : (~~((layout.h * minLayoutHeight + (layout.h - 1) * 12 - 20 - 40 - 24 - 8 * 2)/38) + 1)
                            dispatch({ type: 'dashboardDesigner/fetchChartData', item, mandatory: true, page, pageSize });
                        }}/>}
                        {!isPreview && viewType !== 'richText' && <Icon className={iconCls} type="arrows-alt" onClick={() => this.showPreviewBox(item)}/>}
                        {editMode && !isPreview && (item.creatorCode === currentUser.code || currentUser.role === 'superAdmin') && viewType !== 'richText' &&  <Icon className={iconCls} type='edit' onClick={() => {
                            dispatch({ type: 'dashboard/remoteModify',hideMessage:true });
                            dispatch({ type: 'dashboardDesigner/reset' });
                            dispatch({ type: 'main/redirect', path: '/chart/' + chartCode });
                        }}/>}
                        {!isPreview && editMode && <Icon className={iconCls} type='delete' onClick={() => {
                            dispatch({ type: 'dashboardDesigner/deleteItem', item });
                        }} />}
                        {isPreview && <Icon className={iconCls} type="close" onClick={this.hidePreviewBox}/>}
                    </div>
                </div>
                <ChartView chartRef={'chartRef-' + code} minLayoutHeight={minLayoutHeight} readOnly={richTextReadOnly} editMode={isPreview ? false : editMode} item={{...item}} reload={reload}/>
            </div>
        )
    }

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

    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, lastContentSize, dispatch } = this.props;
        const { editingKey } = this.state;
        const { editMode, minLayoutHeight } = dashboardDesigner;
        const { visiblePreviewBox, previewItem } = this.state;
        const children = dashboardDesigner.items.map((item) => this.createElement(item, false, !item.chartOption));
        return (<div className='dashboard-viewcontent'>
            <ReactGridLayout
                width={ contentSize.width ? contentSize.width : lastContentSize.width }
                autoSize={true}
                cols={12}
                margin = {editMode ? [12, 12] : [12, 12]}
                rowHeight = {minLayoutHeight}
                isDraggable={editMode && !editingKey}
                isResizable={editMode && !editingKey}
                draggableHandle='.mover'
                onLayoutChange={this.onLayoutChange}
                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 && <DataPreview
                title={previewItem.name}
                visibleBox={visiblePreviewBox}
                hideBox={this.hidePreviewBox}
                fetchFunction={(page, pageSize) => {
                    dispatch({ type: 'dashboardDesigner/fetchDataList', item: previewItem, mandatory: true, page, pageSize });
                }}
            />}
        </div>);
    }
}

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