import React from 'react'
import { connect } from 'dva'
import { Icon, Layout, Spin } from 'antd'
import './layout.less'
import DashboardDesignerHeader from './header'
import DashboardDesignerContent from './content'
const { Header, Content } = Layout


class DashboardDesigner extends React.Component {

    constructor(props) {
        super(props);
        props.dispatch({ type: 'dashboardDesigner/reset' });
    }

    componentDidMount() {
        const { code, dispatch, isShareView, isShareKeyView, afterLoad, config } = this.props;
        
        let url;
        if (code !== 'create') {
            url = isShareView ? 'dashboard/remoteShareDetail' : ( isShareKeyView ? 'dashboard/remoteShareKeyDetail' : 'dashboard/remoteDetail');
        }
        if(config) { // 首页打开的报表会保存报表配置，不需要后台再请求
            let fields = [];
            for(let key in config) {
                fields.push({
                    name: key,
                    value: config[key]
                })
            }
            dispatch({ type: 'dashboardDesigner/silentSetFields', fields: fields });
        }else {
            dispatch({ type: url, code: code }).then((data) => {
                if(afterLoad && typeof afterLoad === 'function') {
                    afterLoad(data)
                }
            });
        }
    }


    isOwner = () => {
        const { dashboardDesigner, main } = this.props;
        const { creatorCode } = dashboardDesigner;
        const { currentUser } = main;
        return currentUser.code === creatorCode;
    }

    render() {
        const { dashboardDesigner, isShareView, isShareKeyView, isViewMode, afterRefresh } = this.props;
        const { loading } = dashboardDesigner;
        return <Layout className='dashboarddesigner-layout'>
            {!isShareView && !isShareKeyView && !isViewMode && <Header>
                <DashboardDesignerHeader updateThumbnail={this.updateThumbnail} />
            </Header>}
            <Content>
                <DashboardDesignerContent isOwner={this.isOwner()} isShareView={isShareView} isShareKeyView={isShareKeyView} isViewMode={isViewMode} afterRefresh={afterRefresh}/>
            </Content>
            <div style={{ display: loading ? 'block' : 'none', position: 'absolute', height: '100%', width: '100%', zIndex: '4', background: 'rgba(51,51,51,.1)' }}>
                <Spin style={{ display: 'inline-block', position: 'absolute', top: '50%', left: '50%', margin: '-10px' }} indicator={<Icon type="loading" style={{ fontSize: 24 }} spin />} />
            </div>
        </Layout>
    }

}

function mapStateToProps(state) {
    const { main } = state.present;
    return { main }
}

export default connect(mapStateToProps)(DashboardDesigner)