import React from 'react'
import { Layout, Row, Col, Button, Table, Icon, Menu, Dropdown, Card, Breadcrumb, Tag, Checkbox, Select } from 'antd'
import { connect } from 'dva'
import { arrayToTree, dateFormat } from '../../utils/baseUtils'
import GroupManagementBox from '../common/groupManageMentBox/box'
import GroupSelector from '../common/groupSelector/popover'
import TransferBox from '../common/selectUserBox/selectUserBox'
import CopyBox from './copyBox'
import DeleteBox from '../common/deleteBox/deleteBox'
import DataPreview from '../common/dataPreview/dataPreview'
import ListFilter from '../common/listFilter/index'
import './list.less'
const { Content } = Layout
const { Option } = Select

class DataSource extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedRecord: null, // 当前选中的dataSource
            visibleGroupMenu: false, // 显示分组菜单
            visibleTransferBox: false,
            visibleDeleteBox: false,
            visibleCopyBox: false,
            visibleDataPreviewBox: false, // 显示数据预览
            visibleGroupManageMentBox: false, // 显示分组管理
            noGroup: false, // 显示未分组数据
        }
    };
    hideTransferBox = () => {
        this.setState({ visibleTransferBox: false})
    }
    componentDidMount() {
        const { dispatch } = this.props;
        this.setScrollTableHeight();
        dispatch({ type: 'dataSource/fetchList' });
        dispatch({ type: 'dataSource/remoteGroupList' });
    }

    /**
     * 根据视图设置表格高度以呈现滚动条
     */
    setScrollTableHeight() {
        const mainContent = document.getElementsByClassName('main-content')[0];
        const toolbar = mainContent.getElementsByClassName('datasource-tools')[0];
        const tableHeader = mainContent.getElementsByClassName('ant-table-header')[0];
        const tableBody = mainContent.getElementsByClassName('ant-table-body')[0];
        tableBody.style.maxHeight=`${mainContent.offsetHeight - toolbar.offsetHeight - tableHeader.offsetHeight - 58}px`;
    }

    onGroup() {
        const { dataSource } = this.props;
        const { noGroup } = this.state;
        const { currentGroup, list } = dataSource;
        
        if(noGroup) {
            return list.filter(l => l.groupCode === '-1' );
        }else if(currentGroup) {
            return list.filter(l => l.groupCode === currentGroup.code );
        }else {
            return list;
        }
    }

    onSearch(list, dataSource) {
        const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符
        let filterItem = dataSource.filterItem
        let filterLabel = dataSource.filterLabel ? (dataSource.filterLabel + '').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);
    }

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

    handleVisibleChange = (flag) => {
        this.setState({ visibleGroupMenu: flag });
    }

    getParens = (group) => {
        const groupData = this.props.dataSource.groupList;
        let pgroups = [group];
        let fgroup = groupData.find(g => g.code === group.pcode);
        if(fgroup) {
            pgroups = this.getParens(fgroup).concat(pgroups);
        }
        return pgroups;
    }

    generateGroupTags = () => {
        const { dataSource, dispatch } = this.props;
        const { noGroup } = this.state;
        const { currentGroup } = dataSource;
        const pGroups = currentGroup ? [{ code: '-1', label: '全部分组' }].concat(this.getParens(currentGroup)) : [{ code: '-1', label: '全部分组' }];
        return <Breadcrumb className={`group${noGroup ? ' nogroup' : ''}`} separator=">">
            { pGroups.map(g => (
                <Breadcrumb.Item key={g.code}>
                    <GroupSelector
                        visible={this.state['visibleGroupSelector' + g.code]}
                        handleVisibleChange={(visible) => {
                            let obj = {};
                            obj['visibleGroupSelector' + g.code] = visible
                            this.setState(obj);
                        }}
                        pGroup={g}
                        groupList={dataSource.groupList}
                        selectGroup={(group) => {
                            let obj = {};
                            obj['visibleGroupSelector' + g.code] = false;
                            this.setState(obj);
                            dispatch({ type: 'dataSource/setCurrentGroup', group });
                        }}
                    >
                        <Tag color={'blue'} >
                            {g.label}
                        </Tag>
                    </GroupSelector>
                </Breadcrumb.Item>
            )) }
        </Breadcrumb>
    }

    createGroupMenu = (treeData) => {
        const { dispatch } = this.props;
        const { selectedRecord } = this.state;

        return treeData.map(t => {
            if(t.children && t.children.length > 0) {
                return <Menu.SubMenu
                    key={t.code}
                    title={selectedRecord.groupCode === t.code ? <span className='current' style={{ fontWeight: 'bold' }}>{t.label}</span> : t.label}
                    onTitleClick={() => {
                        dispatch({ type: 'dataSource/remoteSetGroup', dataSource: selectedRecord, group: t });
                        dispatch({ type: 'dataSource/setCurrentGroup', group: t });
                    }}
                >
                    {this.createGroupMenu(t.children)}
                </Menu.SubMenu>
            }else {
                return <Menu.Item key={t.code} onClick={() => {
                    dispatch({ type: 'dataSource/remoteSetGroup', dataSource: selectedRecord, group: t });
                    dispatch({ type: 'dataSource/setCurrentGroup', group: t });
                }}>
                    {selectedRecord.groupCode === t.code ? <span className='current' style={{ fontWeight: 'bold' }}>{t.label}</span> : t.label}
                </Menu.Item>
            }
        })
    }


    hideGroupMenu = () => {
        this.setState({
            visibleGroupMenu: false
        });
    }

    onDrop = (info) => {
        const { dispatch } = this.props;

        const dropCode = info.node.props.eventKey;
        const dragCode = info.dragNode.props.eventKey;
        const dropPos = info.node.props.pos.split('-');
        const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]); // -1/0/1 -> 兄/子/弟
        dispatch({ type: 'dataSource/remoteMoveGroup', dragCode, dropCode, dropPosition });
    }

    generateFilterItems = () => {
        const { filterItems } = this.props.dataSource;
        return filterItems.map(t => <Option key={t.name}  value={t.name}>{t.label}</Option>);
    }

    render() {
        const { main, dataSource, dispatch } = this.props;
        const { selectedRecord, visibleTransferBox, visibleGroupManageMentBox, visibleCopyBox, visibleDeleteBox, visibleDataPreviewBox, noGroup } = this.state;
        const { currentUser } = main;
        const treeData = arrayToTree(dataSource.groupList, '-1', 'code', 'pcode', 'children');
        const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符
        let filterItem = dataSource.filterItem;
        let filterLabel = dataSource.filterLabel ? (dataSource.filterLabel + '').replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1') : ''; // 添加转义符号

        const moreOperatingMenu = (
            <Menu className='operationmenu' visible={true}>
                <Menu.Item
                    onClick={() => {
                        dispatch({ type: 'chartDesigner/remoteQucikAdd', dataSource: selectedRecord });
                    }}
                >
                    <Icon type="file-add" />创建图表
                </Menu.Item>
                <Menu.Item onClick={() => {
                    this.setState({
                        visibleDataPreviewBox: true
                    });
                }}><Icon type="search" />预览数据</Menu.Item>
                <Menu.Divider />
                { selectedRecord && currentUser.code === selectedRecord.creatorCode && <Menu.SubMenu className='setgroupmenu' title={<div><Icon style={{ marginRight: '6px' }} type='profile' />移动到</div>}>
                    {[<Menu.Item key='-1' onClick={() => {
                        dispatch({ type: 'dataSource/remoteSetGroup', dataSource: selectedRecord, group: { code: '-1'} });
                        this.setState({
                            noGroup: true
                        });
                    }}>未分组</Menu.Item>].concat(this.createGroupMenu(treeData))}
                </Menu.SubMenu>}
                <Menu.Divider />
                { selectedRecord && currentUser.code === selectedRecord.creatorCode && <Menu.Item
                    onClick={()=>{
                        this.setState({ visibleTransferBox: true})
                    }}
                >
                    <Icon type="swap" />移交
                </Menu.Item>}
                <Menu.Divider />
                {/* { selectedRecord && <Menu.Item
                    onClick={()=>{
                        this.setState({ visibleCopyBox: true})
                    }}
                >
                    <Icon type="copy" />复制
                </Menu.Item>} */}
                { selectedRecord && currentUser.code === selectedRecord.creatorCode && <Menu.Item
                    onClick={(e) => {
                        this.setState({ visibleDeleteBox: true})
                    }}
                >
                    <Icon type="delete" />删除
                    
                </Menu.Item>}
            </Menu>
        );
        const dataSourceColumns = [{
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: 100,
            render: (text, record) => {
                return <div className='datasource-name'>
                    <div className={`datasource-type`}>
                        {record.type === 'database' ? <Icon type="database" theme="outlined" /> : <Icon type="file-excel" theme="outlined" />}
                    </div>
                    <div>
                        <span style={{ color: '#1890ff', cursor: 'pointer' }} onClick={() => {
                            dispatch({ type: 'dataSource/resetNewModel' });
                            dispatch({type: 'main/redirect', path: {pathname: '/workshop/datasource/'+ record.type +'/' + record.code + '/base'}});
                        }}>
                            { (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: '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>
                )
            }
        }, {
            title: '创建人',
            dataIndex: 'creatorName',
            key: 'creatorName',
            width: 100,
            render: (text, record) => {
                return (
                    <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>
                )
            }
        }, {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (text, record) => dateFormat(text, 'yyyy-MM-dd hh:mm:ss'),
            width: 100
        }, {
            title: '操作',
            key: 'action',
            render: (text, record, index) => (
                <Dropdown code={record.code} overlay={moreOperatingMenu} trigger={['click']} >
                    <Icon type="setting" />
                </Dropdown>
            ),
            width: 50
        }];

        return ( 
            <Layout className='layout-datasource'>
                <Content>
                    <Card className='datasource-body' title={
                        <Row className='datasource-tools' type='flex' justify='space-between'>
                            <Col style={{ display: 'flex', width: 'calc(100% - 324px)', overflow: 'hidden' }}>
                                <Icon type="bars" onClick={() => {
                                    this.setState({
                                        visibleGroupManageMentBox: true
                                    });
                                }}/>
                                <Checkbox style={{ marginTop: '4px' }} value={noGroup} onChange={(e) => {
                                    this.setState({noGroup: e.target.checked})
                                }}>未分组</Checkbox>
                                { this.generateGroupTags() }
                            </Col>
                            <Col className='search'>
                                <Col style={{ padding: '0 5px' }}>
                                    <ListFilter modelName='dataSource' model={dataSource} />
                                </Col>
                                <Col>
                                    <Button style={{ marginRight: '8px' }} onClick={() => {
                                        dispatch({ type: 'dataSource/setFilterLabel', label: '' });
                                        dispatch({ type: 'dataSource/fetchList', mandatory: true });
                                    }}>
                                        <Icon type="sync" />
                                    </Button>
                                    <Dropdown overlay={(
                                        <Menu onClick={(item, key, keyPath) => {
                                            const type = item.key;
                                            dispatch({ type: 'dataSource/resetNewModel' });
                                            dispatch({ type: 'dataConnect/resetSelected' });
                                            dispatch({ type: 'dataSource/setNewModelField', name: 'type', value: type });
                                            dispatch({type: 'main/redirect', path: {pathname: '/workshop/datasource/'+ type +'/create/base'}});
                                        }}>
                                            { currentUser.role === 'admin' && <Menu.Item key='database'>来自数据库</Menu.Item>}
                                            <Menu.Item disabled key='file'>来自文件</Menu.Item>
                                        </Menu>
                                    )} trigger={['click']}>
                                        <Button>
                                            <Icon type="plus" />添加数据源
                                        </Button>
                                    </Dropdown>
                                </Col>
                            </Col>
                        </Row>
                    }>
                        <Table
                            className='datasource-table'
                            columns={dataSourceColumns}
                            dataSource={
                                this.onSort(
                                    this.onSearch(this.onGroup(), dataSource)
                                )
                            }
                            size='small'
                            scroll={{x: false, y: true}}
                            pagination={false}
                            onRow={(record) => {
                                return {
                                    onClick: () => {this.setState({ selectedRecord:  record})}
                                }
                            }}
                        />
                        {visibleGroupManageMentBox && <GroupManagementBox
                            visibleBox={visibleGroupManageMentBox}
                            groupData={dataSource.groupList}
                            hideBox={() => {
                                this.setState({
                                    visibleGroupManageMentBox: false
                                })
                            }}
                            okHandler={(aGroups, mGroups, dGroups) => {
                                dispatch({ type: 'dataSource/remoteSetGroups', aGroups, mGroups, dGroups });
                            }}
                        />}
                        {visibleTransferBox && <TransferBox
                            visibleBox={visibleTransferBox}
                            title='选择移交对象'
                            okHandler={(user) => {
                                dispatch({ type: 'dataSource/transfer', dataSourceCode: this.state.selectedRecord.code, userCode: user.code });
                            }}
                            hideBox={() => {
                                this.setState({
                                    visibleTransferBox: false
                                })
                            }}
                            onlyAdmin={true}
                        />}
                        {visibleCopyBox && <CopyBox
                            visibleBox={visibleCopyBox}
                            currentDataSourceCode={selectedRecord.code}
                            currentDataConnectCode={selectedRecord.dbConfig.code}
                            hideBox={() => { this.setState({ visibleCopyBox: false })
                            }}
                        />}
                        {visibleDeleteBox && <DeleteBox
                            visibleBox={visibleDeleteBox}
                            text={<div><span>确定要删除数据源【{selectedRecord.name}】吗？</span></div>}
                            hideBox={() => {
                                this.setState({
                                    visibleDeleteBox: false
                                })
                            }}
                            okHandler={() =>{
                                dispatch({ type: 'dataSource/remoteDelete', code: selectedRecord.code }).then(() => {
                                    dispatch({ type: 'chart/fetchList', mandatory: true });
                                })
                            }} 
                        />}
                        {visibleDataPreviewBox && <DataPreview
                            visibleBox={visibleDataPreviewBox}
                            hideBox={() => {
                                this.setState({
                                    visibleDataPreviewBox: false
                                });
                            }}
                            fetchFunction={(page, pageSize) => {
                                dispatch({ type: 'dataSource/remoteDataList', code: selectedRecord.code, page, pageSize });
                            }}
                        />}
                    </Card>
                </Content>
            </Layout>
        )


    }
}

function mapStateToProps({present: {main, dataSource, dataConnect}}) {
    return { main, dataSource, dataConnect }
}

export default connect(mapStateToProps)(DataSource)