import React from 'react';
import { connect } from 'dva';
import { Tag, Icon } from 'antd';
import FilterBox from '../common/filterBox/filterBox2';
import Filter from '../common/filterBox/filter2';
import MobileFilterList from './mobileFilterList';

class FilterBar extends React.Component {

    state = {
        visibleFilterBox: false,
        filterContentHeight: 40, // filter栏高度
        filtersOpened: false, // 展开所有filter
        filterOvered: false, // filter数量超出了一行
        toggleVisible: false,
        visibleFilterList: false
    }

    componentDidMount() {
        this.resetFilterContentHeight();
        window.addEventListener("resize", this.resetFilterContentHeight);
    }

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

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

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

    expandFilters = () => {
        let filterContent = this.filtersRef.getElementsByClassName('content')[0];
        let filterContentScrollHeight = filterContent.scrollHeight;

        this.setState({
            filtersOpened: true,
            filterContentHeight: Math.min(filterContentScrollHeight, document.body.clientHeight)
        });
        
        window.setTimeout(() => {
            this.filtersRef.style.overflow = 'auto';
        }, 300);
        document.addEventListener('click', this.closeFiltersEventListener)
    }

    closeFilters = () => {
        this.setState({
            filtersOpened: false,
            filterContentHeight: 40
        });
        this.filtersRef.style.overflow = 'hidden';
        document.removeEventListener('click', this.closeFiltersEventListener);
    }

    resetFilterContentHeight = () => {
        if(!this.filtersRef) {
            return;
        }
        
        let filterContent = this.filtersRef.getElementsByClassName('content')[0];

        window.clearTimeout(this.resetKey);
        this.resetKey = window.setTimeout(() => {
            let filterContentOffsetHeight;
            let filterContentScrollHeight;
            let obj = {};

            if(this.state.filtersOpened) {
                this.filtersRef.style.height = 'auto';
                filterContentOffsetHeight = filterContent.offsetHeight;
                filterContentScrollHeight = filterContent.scrollHeight

                if(filterContentScrollHeight === 40) {
                    obj.filterOvered = false;
                    obj.filtersOpened = false;
                }
                obj.filterContentHeight = Math.min(filterContentScrollHeight, document.body.clientHeight);
            }else {
                filterContentOffsetHeight = filterContent.offsetHeight;
                filterContentScrollHeight = filterContent.scrollHeight
                obj.filterOvered = filterContentScrollHeight > filterContentOffsetHeight;
            }

            this.setState(obj);
        }, 1000);
    }

    setToggleVisible = (visible) => {
        this.setState({
            toggleVisible: visible
        });
    }

    closeFiltersEventListener = e => {
        let viewContent = document.getElementsByClassName('dashboard-viewcontent')[0];
        let sider = document.getElementsByClassName('config-sider')[0];
        let header = document.getElementsByClassName('dashboarddesigner-header')[0];

        if(this.isParent(e.target, viewContent) || this.isParent(e.target, sider) || this.isParent(e.target, header) ) {
            this.closeFilters();
        }
    }

    createFilters = (filters) => {
        const { dispatch, afterRefresh } = this.props;
        dispatch({ type: 'dashboardDesigner/changeFilters', filters }).then(() => {
            afterRefresh && typeof afterRefresh === 'function' && afterRefresh()
        }).then(this.resetFilterContentHeight);
    }

    changeFilterValue = (filter) => {
        const { dispatch, afterRefresh } = this.props;
        dispatch({ type: 'dashboardDesigner/changeFilter', filter }).then(() => {
            afterRefresh && typeof afterRefresh === 'function' && afterRefresh()
        });
    }

    isParent = (obj, parentObj) => {
        while (obj !== undefined && obj !== null && obj.tagName.toUpperCase() !== 'BODY'){
            if (obj === parentObj){
                return true;
            }
            obj = obj.parentNode;
        }
        return false;
    }

    render() {
        const { filters, contentSize, esMobile, isOwner, editMode, isShareView, isShareKeyView,
            isViewMode, dataSources, relationColumns } = this.props;
        const { visibleFilterBox, filterContentHeight, filtersOpened, filterOvered } = this.state;

        return <div ref = {node => this.filtersRef = node} className={`filters`} style={{ height: `${filterContentHeight}px`, width: `${contentSize.width + (contentSize._scroll ? 10 : 0)}px` }}>
            <div key={filters.length} className={`content${esMobile ? ' es-mobile' : ''}`}>
                {isOwner && editMode && !isShareView && !isShareKeyView && !isViewMode && <Tag
                    onClick={this.showFilterBox}
                    className={`filter-tag filter-tag-add`}
                >
                    <Icon type="filter" theme="outlined" />
                </Tag>}
                {!esMobile && filters.map(f => (
                    <Filter
                        key={f.key}
                        filter={f}
                        changeFilterValue={this.changeFilterValue}
                    />
                ))}
                {
                    esMobile && <MobileFilterList
                        filters={filters}
                        filtersOpened={filtersOpened}
                        closeFilters={this.closeFilters}
                        expandFilters={this.expandFilters}
                        setToggleVisible={this.setToggleVisible}
                        changeFilterValue={this.changeFilterValue}
                    />
                }
            </div>
            {!esMobile && <div className='right' style={{ display: filters.length > 0 && filterOvered ? 'block' : 'none' }}>
                <Icon title={filtersOpened ? '收起' : '展开'} type={filtersOpened ? 'caret-down' : 'caret-up'} onClick={() => {
                    filtersOpened ? this.closeFilters() : this.expandFilters();
                }}/>
            </div>}
            {visibleFilterBox && <FilterBox key={Math.random()} dataSources={dataSources} relationColumns={relationColumns} filterData={filters} visibleFilterBox={visibleFilterBox} showFilterBox={this.showFilterBox} hideFilterBox={this.hideFilterBox} createFilters={this.createFilters} />}
        </div>
    }
}

export default connect()(FilterBar);