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 || currentUser.role === 'superAdmin';
    }

    render() {
        const { dashboardDesigner, isShareView, isShareKeyView, isViewMode, afterRefresh } = this.props;
        const { code, loading } = dashboardDesigner;

        return <Layout
            key={code} // 这个key值很重要，因为不同报表中可能引用相同的图表，如果不在报表这一级加上key值区分的话，会造成首页展示切换不同报表时图表位置错误的问题
            className='layout-dashboarddesigner'
        >
            {!isShareView && !isShareKeyView && !isViewMode && <Header className='dashboarddesigner-header'>
                <DashboardDesignerHeader />
            </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;
    return { main }
}

export default connect(mapStateToProps)(DashboardDesigner)