import React from 'react'
import { Modal, Table, Radio, message, Row, Col } from 'antd'
import { connect } from 'dva'
import './chooseDataSourceBox.less'
import { dateFormat } from '../../utils/baseUtils'
import ListFilter from '../common/listFilter/index'

class ChooseDataSourceBox extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            filterItem: { name: 'name', label: '名称', type: 'string' },
            filterLabel: '',
            selectedRecord: null,
            screenWidth: document.documentElement.clientWidth || document.body.clientWidth,
            screenHeight: document.documentElement.clientHeight || document.body.clientHeight
        }
    }

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

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

    onWindowResize = () => {
        this.setState({
            screenWidth: document.documentElement.clientWidth || document.body.clientWidth,
            screenHeight: document.documentElement.clientHeight || document.body.clientHeight
        });
    }

    changeSelected = (record) => {
        this.setState({
            selectedRecord: Object.assign({}, record)
        });
    }

    okHandler = (model) => {
        const { selectedRecord } = this.state;
        const { dispatch, hideBox } = this.props;
        if(selectedRecord) {
            dispatch({ type: 'chartDesigner/remoteQucikAdd', dataSource: selectedRecord });
            hideBox();
        }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 = 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);
    }

    render() {
        const { dataSource, visibleChooseDataSourceBox, hideBox } = this.props
        const { filterItem, filterLabel: stateFilterLabel, selectedRecord, screenWidth, screenHeight } = this.state;
        const tableBodyWidth = screenWidth * 0.8 - 10 - 10 - 18;
        const tableBodyHeight = screenHeight * 0.8 - 65 - 53 - 38 - 130;
        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 <Radio checked={selectedRecord ? selectedRecord.code === record.code : false}/>
            }
        }, {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: 200,
            render: (text, record) => {
                return <div className='datasource-name'>
                    <div className={`datasource-type type-${record.type.key}`}></div>
                    <div>
                        <span>
                            { (filterItem.name === 'name' && filterLabel) ?
                                (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: 'dbConfig.name',
            key: 'dbConfig.name',
            width: 100
        }, {
            title: '创建人',
            dataIndex: 'creatorName',
            key: 'creatorName',
            width: 100,
            render: (text, record) => {
                return <div className='datasource-name'>
                    <div className={`datasource-type type-${record.type.key}`}></div>
                    <div>
                        <span>
                            { (filterItem.name === 'creatorName' && filterLabel) ?
                                (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) => dateFormat(new Date(text), 'yyyy-MM-dd')
        }, {
            title: '说明',
            dataIndex: 'description',
            key: 'description',
            width: 200,
            render: (text, record) => {
                return (
                    <span>
                        { (filterItem.name === 'description' && filterLabel) ?
                            ((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>
                )
            }
        }];

        return (
            <Modal
                className='choosedatasource-box'
                title='选择数据源'
                visible={visibleChooseDataSourceBox}
                onOk={this.okHandler}
                onCancel={hideBox}
                maskClosable={false}
                destroyOnClose={true}
            >
                <div>
                    <Row type='flex' justify='end'>
                        <Col style={{ padding: '8px' }}>
                            <ListFilter
                                modelName={null}
                                model={{
                                    filterItems: dataSource.filterItems,
                                    filterItem, // 已选过滤字段
                                    filterLabel: stateFilterLabel,
                                }}
                                onChangeFilterItem={(filterItem) => {
                                    this.setState({
                                        filterItem
                                    });
                                }}
                                onChangeFilterValue={(filterLabel) => {
                                    this.setState({
                                        filterLabel
                                    });
                                }}
                            />
                        </Col>
                    </Row>
                    <Table
                        className='choosedatasource-table'
                        columns={columns}
                        dataSource={this.onSearch(dataSource.list)}
                        size='small'
                        scroll={{ x: columns ? columns.length * 100 : tableBodyWidth, y: tableBodyHeight }}
                        pagination={{ defaultPageSize: Math.floor(tableBodyHeight/tableRowHeight) || 10 }}
                        onRow={(record) => {
                            return {
                                onClick: () => {
                                    this.changeSelected(record);
                                }
                            };
                        }}
                    />
                </div>
            </Modal>
        )
    }
}

function mapStateToProps({ present: { dataSource } }) {
    return { dataSource: dataSource };
}

export default connect(mapStateToProps)(ChooseDataSourceBox)