import React from 'react'
import { Layout, Tabs, Switch, Button } from 'antd'
import BaseConfigForm from './sections/baseConfigForm'
import AggregateTableConfigForm from './sections/aggregateTableConfigForm'
import DataViewConfigForm from './sections/dataViewConfigForm'
import BarConfigForm from './sections/barConfigForm'
import PieConfigForm from './sections/pieConfigForm'
import LineConfigForm from './sections/lineConfigForm'
import ScatterConfigForm from './sections/scatterConfigForm'
import IndicatorConfigForm from './sections/indicatorConfigForm'
import StyleConfigForm from './sections/style/index'
import OtherConfigForm from './sections/otherConfigForm'
import TableView from './charts/tableView'
import EchartsView from './charts/echartsView'
import AggregateTableView from './charts/aggregateTableView'
import IndicatorView from './charts/indicatorView'
import ToolBar from './sections/toolbar'
import { connect } from 'dva'
import EmptyContent from '../common/emptyContent/index'
import Thumbnail from '../common/echarts/thumbnail'
import { hashcode } from '../../utils/baseUtils'
import themes from './sections/style/theme/index'
import './content.less'
const { Header, Sider, Content, Footer } = Layout
const { TabPane } = Tabs

class ChartDesignerContent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isOwner: false,
            autoRefresh: true,
            collapsed: false,
        }
    }

    static getDerivedStateFromProps(nextProps, nextState) {
        const { chartDesigner, main } = nextProps;
        const isOwner = chartDesigner.creatorCode === main.currentUser.code || main.currentUser.role === 'superAdmin';
        if(chartDesigner.code !== nextState.code) {
            return {
                code: chartDesigner.code,
                isOwner: isOwner,
                collapsed: !isOwner,
            };
        }else {
            return null;
        }
    }

    onCollapse = () => {
        this.setState({
            collapsed: !this.state.collapsed,
        }, () => {
            window.setTimeout(() => {
                var e = document.createEvent("Event");
                e.initEvent("resize", true, true);
                window.dispatchEvent(e);
            }, 500);
        })
    }

    render() {
        const { chartDesigner, dispatch } = this.props;
        const { isOwner, autoRefresh } = this.state;
        const { code, baseConfig, chartOption, theme: themeName, styleConfig } = chartDesigner;
        const { viewType } = baseConfig;

        let configForm, chartView;
        let t = themes.find(t => t.name === themeName);
        let theme = t ? t.config : themes[0].config;

        if(viewType === 'aggregateTable') {
            configForm = (<AggregateTableConfigForm autoRefresh={autoRefresh}/>);
            chartView = (<AggregateTableView key={hashcode(chartOption)} chartOption={chartOption}/>);
        }else if(viewType === 'dataView') {
            configForm = (<DataViewConfigForm autoRefresh={autoRefresh}/>);
            chartView = (<TableView
                key={hashcode(chartOption)}
                chartOption={chartOption}
                viewRef={`tableview-${code}`}
                columns={chartOption.columns}
                dataSource={chartOption.dataSource}
                themeConfig={chartOption.themeConfig}
                styleConfig={styleConfig.dataView}
                pagination={{
                    simple: false,
                    current: chartOption.page,
                    pageSize: chartOption.pageSize || 25,
                    total: chartOption.total,
                    showTotal: (total, range) => {
                        return `第${range[0]}到第${range[1]}条数据，共${total}条数据`;
                    },
                    onChange: (page, pageSize) => {
                        dispatch({ type: 'chartDesigner/fetchDataViewData', page, pageSize });
                    }
                }}
                />);
        }else if(viewType === 'line') {
            configForm = (<LineConfigForm autoRefresh={autoRefresh}/>);
            // optionConfig 可以用来放替换属性(已做深拷贝替换)
            chartView = (<EchartsView key={hashcode(chartOption)} chartOption={chartOption} />);
        }else if(viewType === 'bar') {
            configForm = (<BarConfigForm autoRefresh={autoRefresh}/>);
            chartView = (<EchartsView key={hashcode(chartOption)} chartOption={chartOption} />);
        }else if(viewType === 'pie') {
            configForm = (<PieConfigForm autoRefresh={autoRefresh}/>);
            chartView = (<EchartsView key={hashcode(chartOption)} chartOption={chartOption} />);
        }else if(viewType === 'scatter') {
            configForm = (<ScatterConfigForm autoRefresh={autoRefresh}/>);
            chartView = (<EchartsView key={hashcode(chartOption)} chartOption={chartOption} />);
        }else if(viewType === 'indicator') {
            configForm = (<IndicatorConfigForm autoRefresh={autoRefresh}/>);
            chartView = (<IndicatorView key={hashcode(chartOption)} chartOption={chartOption} />);
        }else {
            chartView = <EmptyContent />
        }

        return (
            <Layout className='chartdesigner'>
                <Sider className={`sider-left${this.state.collapsed ? ' sider-left-collapsed' : ''}`} width={isOwner ? 300 : 0} >
                    <Button className='collapse-toggle' style={{ display: isOwner? 'block' : 'none' }} shape='circle' size='small' icon={`${this.state.collapsed?'right':'left'}`} onClick={this.onCollapse} />
                    <Tabs className='sider-tabs'>
                        <TabPane className='chartconfig' tab='图表设置' key='1'>
                            <BaseConfigForm/>
                            { configForm }
                        </TabPane>
                        <TabPane className='styleconfig' tab='样式设置' key='2'>
                            <StyleConfigForm viewType={viewType}/>
                        </TabPane>
                        <TabPane className='otherconfig' tab='其他设置' key='3'>
                            <OtherConfigForm/>
                        </TabPane>
                    </Tabs>
                    {!this.state.collapsed && <Footer className='sider-footer'>
                        <div className='fresh-bar'>
                            <Switch defaultChecked={autoRefresh} checkedChildren='自动刷新' unCheckedChildren='手动刷新' onChange={(checked) => {
                                // 自动刷新后立即请求一次数据
                                if(checked) {
                                    let page = chartOption.page || 1;
                                    let pageSize = chartOption.pageSize || ~~((document.getElementsByClassName('content-body')[0].offsetHeight - 12 * 2 - 40 - 24 - 8 * 2)/38) + 1;
                                    dispatch({ type: 'chartDesigner/fetchChartData', page, pageSize });
                                }
                                this.setState({
                                    autoRefresh: checked
                                });
                                // dispatch({ type: 'chartDesigner/silentSetField', name: 'autoRefresh', value: checked })
                            }}/>
                            <Button style={{ display: autoRefresh ? 'none' : 'block' }} size='small' onClick={() => {
                                let page = chartOption.page || 1;
                                let pageSize = chartOption.pageSize || ~~((document.getElementsByClassName('content-body')[0].offsetHeight - 12 * 2 - 40 - 24 - 8 * 2)/38) + 1;
                                dispatch({ type: 'chartDesigner/fetchChartData', page, pageSize})
                            }}
                            >立即刷新</Button>
                        </div>
                    </Footer> }
                </Sider>
                <Content className='view-content' >
                    <Layout>
                        <Header className='content-header'>
                            <ToolBar className='header-toolbar' autoRefresh={autoRefresh} isOwner={isOwner}/>
                        </Header>
                        <Content className='content-body' style={{ backgroundColor: theme.base.backgroundColor }}>
                            {/* 创建一个隐藏echarts容器用于截缩略图 */}
                            <Thumbnail
                                style={{ position: 'absolute', display: 'none', top: 0, left: 0 }}
                                key={`thumbnail-${hashcode(chartOption)}`}
                                option={chartOption}
                            />
                            { chartView }
                        </Content>
                    </Layout>
                </Content>
            </Layout>
        )
    }
}

export default connect(({ present:{ main, chartDesigner } }) => ({ main, chartDesigner }))(ChartDesignerContent);