import React from 'react'
import { findDOMNode } from 'react-dom'
import { Layout, Tooltip, Tag, Icon } from 'antd'
import { connect } from 'dva'
import ViewLayout from './viewLayout'
import ChooseChartBox from './chooseChartBox'
import FilterBox from '../common/filterBox/filterBox'
import ConfigForm from './configForm'
import moment from 'moment'
const { Header, Content, Sider } = Layout

class DashboardDesignerContent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            contentSize: {
                scroll: false,
                width: 0,
                height: 0,
            },
            visibleChooseChartBox: false,
            visibleFilterBox: false,
        };
    }

    componentDidMount() {
        // 这里延迟等待页面渲染结束，也许有更好的办法。
        window.setTimeout(() => {
            this.refreshContentSize(true);
        }, 1500);
        window.addEventListener("resize", () => {
            this.refreshContentSize(true);
        });
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.onWindowResize);
    }

    showBox = (o) => {
        this.setState({
            visibleChooseChartBox: true
        });
    }

    hideBox = (o) => {
        this.setState({
            visibleChooseChartBox: false
        });
    }

    showFilterBox = (e) => {
        this.setState({
            visibleFilterBox: true
        });
    }

    hideFilterBox = (e) => {
        this.setState({
            visibleFilterBox: false,
        });
    }

    /**
     * 重设容器宽度
     */
    refreshContentSize = (flag) => {
        let contentEl = findDOMNode(this.refs.contentEl);
        if(!contentEl) {
            return; 
        }
        let _scroll = contentEl.scrollHeight > contentEl.clientHeight;

        if(!flag && this.state.contentSize.scroll === _scroll) { // 如果滚动条没有变化则直接退出
            return;
        }
        this.setState({
            contentSize: {
                scroll: _scroll,
                width: contentEl.offsetWidth - (_scroll ? 28 : 10), // 有滚动条时需要减去滚动条的宽度
                height: contentEl.clientHeight
            }
        });
    }

    getRelationFilterColumns = () => {
        const { dashboardDesigner } = this.props;
        const { relationColumns } = dashboardDesigner;
        return relationColumns.filter(r => r.relations.length > 0).map(r => ({
            name: r.code,
            label: r.name,
            type: r.relations[0].column.type
        }));
    }

    createFilters = (filters) => {
        const { dispatch } = this.props;
        dispatch({ type: 'dashboardDesigner/changeFilters', filters });
        this.hideFilterBox()
    }

    /**
     * 生成过滤规则文本
     */
    createFilterLabel = (filter) => {
        let { label, operator, operatorLabel, type, value1, value2 } = filter;
        let filterLabel;

        if(type === 'string' || type === 'index') {
            if(operator === 'null' || operator === 'notNull') {
                filterLabel = `${label} ${operatorLabel}`;
            }else {
                filterLabel = `${label} ${operatorLabel} ${value1}`;
            }
        }else if(type === 'scale') {
            if(operator === 'null' || operator === 'notNull') {
                filterLabel = `${label} ${operatorLabel}`;
            }else if(operator === 'between') {
                filterLabel = `${label} ${operatorLabel} ${value1} ~ ${value2}`; 
            }else {
                filterLabel = `${label} ${operatorLabel} ${value1}`; 
            }
        }else if(type === 'time') {
            value1 = moment(value1).format('YYYY/MM/DD');
            value2 = moment(value2).format('YYYY/MM/DD');

            if(operator === 'null' || operator === 'notNull') {
                filterLabel = `${label} ${operatorLabel}`;
            }else if(operator === 'between') {
                filterLabel = `${label} ${operatorLabel} ${value1} ~ ${value2}`;
            }else {
                filterLabel = `${label} ${operatorLabel} ${value1}`;
            }
        }else if(type === 'categorical') {
            if(operator === 'null' || operator === 'notNull') {
                filterLabel = `${label} ${operatorLabel}`;
            }else {
                filterLabel = `${label} ${operatorLabel} ${value1}`;
            }
        }else {
            filterLabel = '错误条件';
        }
        return filterLabel;
    }

    filterUsingChange = (e) => {
        const key = e.target.dataset.key;
        const { dashboardDesigner, dispatch } = this.props;
        const filters = dashboardDesigner.filters;
        dispatch({ type: 'dashboardDesigner/changeFilters', filters: filters.map( f => {
            if(+f.key === +key) {
                f = { ...f, using: f.type ? !f.using : false}
            }
            return f;
        }) });
    }

    render() {
        const { dashboardDesigner, dispatch, isOwner } = this.props;
        const { code, editMode, filters } = dashboardDesigner;
        const { contentSize, visibleChooseChartBox, visibleFilterBox } = this.state;

        let tags = filters.map((f, i)=>{
            return {
                key: f.key,
                label: this.createFilterLabel(f),
                using: f.type ? f.using : false
            }
        });

        return <Layout className='content'>
            <Header>
                <div className='filters'>
                    <div style={{ margin: '0 8px 0 10px' }}>筛选:</div>
                        {tags.map(tag => (
                            <Tag
                                className={`filter-tag ${tag.using?'filter-tag-using':''}`}
                                key={tag.key}
                                closable={false}
                                onClick={this.filterUsingChange}
                                data-key={tag.key}
                            >
                                {tag.label}
                            </Tag>
                        ))}
                        <Tag
                            onClick={this.showFilterBox}
                            className={`filter-tag filter-tag-add`}
                        >
                            <Icon type="filter" theme="outlined" />
                        </Tag>
                    </div>
                    {visibleFilterBox && <FilterBox type='dashboard' code={code} columns={this.getRelationFilterColumns()} filterData={filters} visibleFilterBox={visibleFilterBox} showFilterBox={this.showFilterBox} hideFilterBox={this.hideFilterBox} createFilters={this.createFilters} />}
                {isOwner && <div className='viewtype'>
                    <Tooltip title="图表">
                        <Icon className='viewtype-icon' type="area-chart" theme="outlined" onClick={(item) => {
                            this.showBox("create");
                        }}/>
                    </Tooltip >
                    <Tooltip title="富文本">
                        <Icon className='viewtype-icon' type="book" theme="outlined" onClick={() => {
                            dispatch({ type: 'dashboardDesigner/addRichText' });
                        }}/>
                    </Tooltip>
                    {visibleChooseChartBox && <ChooseChartBox visibleBox={visibleChooseChartBox} hideBox={this.hideBox} />}
                </div>}
            </Header>
            <Content className='dashboard-content'>
                <Layout className='content-layout'>
                    <Content className='viewlayout' ref='contentEl'>
                        <ViewLayout contentSize={contentSize} reset={this.refreshContentSize} editMode={editMode}/>
                    </Content>
                    <Sider className='config-sider' width={(isOwner && editMode) ? 380 : 0}>
                        <ConfigForm/>
                    </Sider>
                </Layout>
            </Content>
        </Layout>
    }
}

export default connect(({ present: { dashboardDesigner } }) => ({ dashboardDesigner }))(DashboardDesignerContent);