import React from 'react'
import '../../models/dashboardDesigner'
import { Modal, Checkbox, Row, Col, Table, message } from 'antd'
import { connect } from 'dva'
import moment from 'moment'
import ListFilter from '../common/listFilter/index'
import EllipsisTooltip from '../common/ellipsisTooltip/index'
import './chooseChartBox.less'
import CHART_TYPE from '../chartDesigner/sections/chartType'

class ChooseChartBox extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            filterLabel: '',
            filterItem: { name: 'name', label: '图表名称', type: 'string' },
            selectedRecord: -1,
            selectedRecords: [],
            tableBodyWidth: 0,
            tableBodyHeight: 0
        };
    }

    componentDidMount() {
        const { dispatch } = this.props;
        dispatch({ type: 'chart/fetchList' }).then(() => {
            this.onWindowResize();
        });
        window.addEventListener('resize', this.onWindowResize);
    }

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

    onWindowResize = () => {
        const boxEl = document.getElementsByClassName('choosechart-box')[0];
        if(!boxEl) {
            return;
        }
        const bodyEl = boxEl.getElementsByClassName('ant-modal-body')[0];
        const bodyBox = bodyEl.getBoundingClientRect();
        this.setState({
            tableBodyWidth: bodyBox.width - 36 * 2,
            tableBodyHeight: bodyBox.height - 56 - 42 - 54
        });
    }

    changeSelected = (record) => {
        const { dashboardDesigner } = this.props;
        const { selectedRecords } = this.state;
        let idx = selectedRecords.findIndex(s => s.code === record.code);
        if(dashboardDesigner.items.findIndex(i => i.chartCode===record.code) === -1) {
            if(idx === -1) {
                selectedRecords.push(record);
            }else {
                selectedRecords.splice(idx, 1);
            }
            this.setState({
                selectedRecords: selectedRecords
            });
        }
    }

    okHandler = () => {
        const { selectedRecords } = this.state;
        const { dispatch, hideBox } = this.props;
        if(selectedRecords.length > 0) {
            dispatch({ type: 'dashboardDesigner/addCharts', charts: selectedRecords });
            hideBox();
            window.setTimeout(() => {
                // 滚动到最底部
                let viewScrollContent = document.querySelector('.viewlayout');
                viewScrollContent.scrollTo && viewScrollContent.scrollTo(0, viewScrollContent.scrollHeight - viewScrollContent.clientHeight);
                var e = document.createEvent("Event");
                e.initEvent("resize", true, true);
                window.dispatchEvent(e);
            }, 500);
        }else {
            message.warning('请选择需要添加的图表');
        }
    }

    onSearch = (list) => {
        const { filterItem, filterLabel: stateFilterLabel } = this.state;
        const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符
        let filterLabel = stateFilterLabel ? (stateFilterLabel + '').replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') : ''; // 添加转义符号
        let filterReg = new RegExp('('+ filterLabel +'){1}', 'ig');

        return list.map(l => {
            let o = Object.assign({}, l);

            if(filterItem.type === 'date') {
                if(filterLabel===""){
                    return o;
                }else if(filterLabel.indexOf('#')>-1){
                    let start = filterLabel.split('#')[0]
                    let end = filterLabel.split('#')[1]
                    let nowTime = new Date(o[filterItem.name]).getTime();
                    if(nowTime>=start && nowTime<=end){
                        return o;
                    }
                    return null 
                }else{
                    return null 
                }
            }else {
                let arr = filterItem.name.split('.');
                let v = o;
                for(let i = 0; i < arr.length; i++) {
                    v = v[arr[i]]
                }
                return ((v + '').search(filterReg) > -1) ? o : null
            }
        }).filter(a => a!==null);
    }

    onSort = (list) => {
        return list.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
    }

    render() {
        const { visibleBox, hideBox, dashboardDesigner, chart, loading } = this.props;
        const { selectedRecords, tableBodyWidth, tableBodyHeight, filterItem, filterLabel: stateFilterLabel } = this.state;
        const tableRowHeight = 38;
        const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符
        let filterLabel = stateFilterLabel ? (stateFilterLabel + '').replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') : ''; // 添加转义符号
        const columns = [{
            title: '选择',
            key: 'selected',
            width: 50,
            render: (text, record) => {
                // return <Checkbox checked={dashboardDesigner.items.findIndex(i => i.chartCode===record.code)!==-1 || selectedRecord.findIndex(s => s.code === record.code) !== -1 } disabled={dashboardDesigner.items.findIndex(i => i.chartCode===record.code)!==-1}/>
                return <Checkbox checked={dashboardDesigner.items.findIndex(i => i.chartCode===record.code)!==-1 || selectedRecords.findIndex(s => s.code === record.code) !== -1 } disabled={dashboardDesigner.items.findIndex(i => i.chartCode===record.code)!==-1}/>
                // return <Radio
                //     checked={dashboardDesigner.items.findIndex(i => i.chartCode===record.code)!==-1 || selectedRecord.code === record.code }
                //     disabled={dashboardDesigner.items.findIndex(i => i.chartCode===record.code)!==-1}
                // />
            }
        }, {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: 200,
            render: (text, record) => {
                return <div>
                    <div>
                        <span>
                            { filterLabel && filterItem.name === 'name' ?
                                (text.split(new RegExp(`(${filterLabel})`, 'i')).map((fragment, i) => {
                                    return (
                                        fragment.toLowerCase().replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') === filterLabel.toLowerCase() ?
                                        <span key={i} style={{fontWeight: 'bold', color: 'red'}} className="highlight">{fragment}</span> :
                                        fragment
                                    )
                                }
                                )) : text
                            }
                        </span>
                    </div>
                </div>
            }
        }, {
            title: '图形类别',
            dataIndex: 'type',
            key: 'type',
            width: 100,
            render: text => text ? CHART_TYPE.find(t => t.type === text).label : '无'
        }, {
            title: '数据源',
            dataIndex: 'dataSourceName',
            key: 'dataSourceName',
            width: 200,
        }, {
            title: '创建人',
            dataIndex: 'creatorName',
            key: 'creatorName',
            width: 100,
            render: (text, record) => {
                return <div>
                    <div>
                        <span>
                            { filterLabel && filterItem.name === 'creatorName' ?
                                (text.split(new RegExp(`(${filterLabel})`, 'i')).map((fragment, i) => {
                                    return (
                                        fragment.toLowerCase().replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') === filterLabel.toLowerCase() ?
                                        <span key={i} style={{fontWeight: 'bold', color: 'red'}} className="highlight">{fragment}</span> :
                                        fragment
                                    )
                                }
                                )) : text
                            }
                        </span>
                    </div>
                </div>
            }
        }, {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 120,
            render: (text) => moment(text).format('YYYY-MM-DD')
        }, {
            title: '备注',
            dataIndex: 'description',
            key: 'description',
            onCell: () => {
                return {
                    style: {
                        whiteSpace: 'nowrap',
                        maxWidth: 150,
                    }
                }
            },
            render: text => {
                return <EllipsisTooltip title={text}>
                    <span>
                        { filterLabel && filterItem.name === 'description' ?
                            ((text || '').split(new RegExp(`(${filterLabel})`, 'i')).map((fragment, i) => {
                                return (
                                    fragment.toLowerCase().replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') === filterLabel.toLowerCase() ?
                                    <span key={i} style={{fontWeight: 'bold', color: 'red'}} className="highlight">{fragment}</span> :
                                    fragment
                                )
                            }
                            )) : text
                        }
                    </span>
                </EllipsisTooltip>
            }
        }]
        return (
            <Modal
                className='choosechart-box'
                width='80%'
                height='80%'
                title='选择图表'
                visible={visibleBox}
                onOk={this.okHandler}
                onCancel={hideBox}
                maskClosable={false}
                destroyOnClose={true}
            >
                <div>
                    <Row type='flex' justify='end' style={{ padding: '12px 0' }}>
                        <Col>
                            <ListFilter
                                modelName={null}
                                model={{
                                    filterItems: chart.filterItems,
                                    filterItem,
                                    filterLabel: stateFilterLabel,
                                }}
                                onChangeFilterItem={(filterItem) => {
                                    this.setState({
                                        filterItem
                                    });
                                }}
                                onChangeFilterValue={(filterLabel) => {
                                    this.setState({
                                        filterLabel
                                    });
                                }}
                            />
                        </Col>
                    </Row>
                    <Table
                        loading={loading}
                        className='choosechart-table'
                        columns={columns}
                        dataSource={this.onSort(this.onSearch(chart.list)).map((d, i) => ({ ...d, key: i }))}
                        size='small'
                        scroll={{ x: columns ? columns.length * 100 : tableBodyWidth, y: tableBodyHeight }}
                        pagination={{ pageSize: Math.ceil(tableBodyHeight/tableRowHeight) }}
                        onRow={(record) => {
                            return {
                                onClick: () => {
                                    this.changeSelected(record);
                                }
                            };
                        }}
                    />
                </div>
            </Modal>
        )
    } 
}

function mapStateToProps({ dashboardDesigner, chart, loading: stateLoading }) {
    let loading = stateLoading.effects['chart/fetchList'];
    return { dashboardDesigner, chart, loading };
}

export default connect(mapStateToProps)(ChooseChartBox)