import React from 'react'
import { Layout, Row, Col, Button, Table, Icon, Menu, Dropdown, Card, Breadcrumb, Tag, Checkbox } 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 EllipsisTooltip from '../common/ellipsisTooltip/index'
import Loading from '../common/loading/index'
import CusIcon from '../common/cusIcon'
import './list.less'
const { Content } = Layout

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, // 显示分组管理
        }
    };
    hideTransferBox = () => {
        this.setState({ visibleTransferBox: false})
    }
    componentDidMount() {
        const { dispatch, dataSource } = this.props;
        this.setScrollTableHeight();
        dispatch({ type: 'dataSource/fetchList' });
        dispatch({ type: 'dataSource/remoteGroupList' });
        let tableBody = document.getElementsByClassName('ant-table-body')[0];
        tableBody.scrollTo && tableBody.scrollTo(0, dataSource.listScrollTop);
    }
    componentWillUnmount() {
        const { dispatch } = this.props;
        dispatch({ type: 'dataSource/setField', name: 'listScrollTop', value: document.getElementsByClassName('ant-table-body')[0].scrollTop });
    }

    /**
     * 根据视图设置表格高度以呈现滚动条
     */
    setScrollTableHeight() {

        const mainContentBody = document.getElementsByClassName('datasource-body')[0];
        const tableContentBody = mainContentBody.getElementsByClassName('ant-card-body')[0];
        const tableHeader = tableContentBody.getElementsByClassName('ant-table-header')[0];
        const tableBody = tableContentBody.getElementsByClassName('ant-table-body')[0];

        // 如果上下padding不一致就有问题了
        const padding = tableContentBody.children[0].getBoundingClientRect().top - tableContentBody.getBoundingClientRect().top;
        // table容器高度 - 上下padding - 表头高度 - 边框线宽
        tableBody.style.maxHeight = `${tableContentBody.offsetHeight - padding * 2 - tableHeader.offsetHeight - 2}px`;
    }

    onGroup() {
        const { dataSource } = this.props;
        const { currentGroup, list, noGroup } = 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 });
    }

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

    getParentsByCode = (groupCode) => {
        const groupData = this.props.dataSource.groupList;
        let group = groupData.find(g => g.code === groupCode);
        if(group) {
            return this.getParents(group);
        }else {
            return [{ label: '未分组' }]
        }
    }

    generateGroupTags = () => {
        const { dataSource, dispatch } = this.props;
        const { currentGroup, noGroup } = dataSource;
        const pGroups = (currentGroup) ? [{ code: '-1', label: '全部分组' }].concat(this.getParents(currentGroup)) : [{ code: '-1', label: '全部分组' }];
        return <Breadcrumb className={`group${noGroup ? ' nogroup' : ''}`} separator=">">
            { pGroups.map(g => (
                <Breadcrumb.Item key={g.code}>
                    <Tag color={'blue'} >
                        {g.code === '-1' && <Icon title="分组维护" type="bars" onClick={() => {
                            this.setState({
                                visibleGroupManageMentBox: true
                            });
                        }}/>}
                        <span onClick={() => {
                            let group = dataSource.groupList.find(group => group.code === g.code);
                            dispatch({ type: 'dataSource/setCurrentGroup', group: group });
                        }}>{g.label}</span>
                        <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 });
                            }}
                        >
                            { arrayToTree(dataSource.groupList, g.code, 'code', 'pcode', 'children').length > 0 && <Icon style={{ marginLeft: '4px', fontSize: '12px' }} type="caret-down" /> }
                        </GroupSelector>
                    </Tag>
                </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}
                    className={selectedRecord.groupCode === t.code ? 'current' : ''}
                    title={t.label}
                    onTitleClick={() => {
                        dispatch({ type: 'dataSource/remoteSetGroup', dataSource: selectedRecord, group: t });
                    }}
                >
                    {this.createGroupMenu(t.children)}
                </Menu.SubMenu>
            }else {
                return <Menu.Item className={selectedRecord.groupCode === t.code ? 'current' : ''} key={t.code} onClick={() => {
                    dispatch({ type: 'dataSource/remoteSetGroup', dataSource: selectedRecord, group: t });
                }}>
                    {t.label}
                </Menu.Item>
            }
        })
    }

    render() {
        const { main, dataSource, dispatch } = this.props;
        const { listLoading, noGroup } = dataSource;
        const { selectedRecord, visibleTransferBox, visibleGroupManageMentBox, visibleCopyBox, visibleDeleteBox, visibleDataPreviewBox } = 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 || currentUser.role === 'superAdmin') && <Menu.SubMenu className='setgroupmenu' title={<div><Icon style={{ marginRight: '6px' }} type='profile' />移动到</div>}>
                    {[<Menu.Item className={selectedRecord.groupCode === '-1' ? 'current' : ''} key='-1' onClick={() => {
                        dispatch({ type: 'dataSource/remoteSetGroup', dataSource: selectedRecord, group: { code: '-1'} });
                    }}>
                         未分组
                    </Menu.Item>].concat(this.createGroupMenu(treeData))}
                </Menu.SubMenu>}
                <Menu.Divider />
                { selectedRecord && (currentUser.code === selectedRecord.creatorCode || currentUser.role === 'superAdmin') && <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 || currentUser.role === 'superAdmin') && <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>
                        <span style={{ color: '#1890ff', cursor: 'pointer' }} onClick={() => {
                            dispatch({ type: 'dataSource/resetNewModel' });
                            dispatch({type: 'main/redirect', path: {pathname: '/workshop/datasource/'+ record.type +'/' + record.code + '/base'}});
                        }}>
                            {record.type === 'database' ? <Icon type="database" theme="outlined" style={{ marginRight: '8px' }}/> : <Icon type="file-excel" theme="outlined" style={{ marginRight: '8px' }}/>}
                            { (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: 'groupCode',
            key: 'groupCode',
            width: 100,
            onCell: () => {
                return {
                    style: {
                        whiteSpace: 'nowrap',
                        maxWidth: 100,
                    }
                }
            },
            render: (text) => <EllipsisTooltip title={this.getParentsByCode(text).map(g => g.label).join('/')}>{this.getParentsByCode(text).map(g => g.label).join('/')}</EllipsisTooltip>,
        }, {
            title: '数据链接',
            dataIndex: 'dbConfig.name',
            key: 'dbConfig.name',
            width: 100,
            onCell: () => {
                return {
                    style: {
                        whiteSpace: 'nowrap',
                        maxWidth: 100,
                    }
                }
            },
            render: (text) => <EllipsisTooltip title={text}>{text}</EllipsisTooltip>,
        }, {
            title: '创建人',
            dataIndex: 'creatorName',
            key: 'creatorName',
            width: 80,
            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: 30
        }];

        return ( 
            <Layout className='layout-datasource'>
                <Loading visible={listLoading} />
                <Content>
                    <Card bordered={false} className='datasource-body' title={
                        <Row className='datasource-tools' type='flex' justify='space-between'>
                            <Col className="groups" style={{ display: 'flex', width: 'calc(100% - 324px)', overflow: 'hidden' }}>
                                <Checkbox style={{ marginTop: '4px' }} checked={noGroup} onChange={(e) => {
                                    dispatch({ type: 'dataSource/setField', name: 'noGroup', value: e.target.checked });
                                }}>未分组</Checkbox>
                                { this.generateGroupTags() }
                            </Col>
                            <Col className='search'>
                                <Col>
                                    <Button className='btn-refresh' onClick={() => {
                                        dispatch({ type: 'dataSource/setFilterLabel', label: '' });
                                        dispatch({ type: 'dataSource/fetchList', mandatory: true });
                                    }}>
                                        {/* <CusIcon type='bi-refresh'/> */}
                                        <Icon type='sync'/>
                                    </Button>
                                </Col>
                                <Col>
                                    <ListFilter modelName='dataSource' model={dataSource} />
                                </Col>
                                <Col>
                                    <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, group });
                                            dispatch({type: 'main/redirect', path: {pathname: '/workshop/datasource/'+ type +'/create/base'}});
                                        }}>
                                            { (currentUser.role === 'admin' || currentUser.role === 'superAdmin') && <Menu.Item key='database'>选择数据链接</Menu.Item>}
                                            <Menu.Item disabled key='file'>上传文件</Menu.Item>
                                        </Menu>
                                    )} trigger={['click']}>
                                        <Button className='tool-link'>
                                            <CusIcon type='bi-nav-datasource'/>添加数据源
                                        </Button>
                                    </Dropdown>
                                </Col>
                            </Col>
                        </Row>
                    }>
                        <Table
                            ref={(node) => { this.tableRef = node}}
                            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
                            typeText='数据源'
                            visibleBox={visibleGroupManageMentBox}
                            groupData={dataSource.groupList}
                            hideBox={() => {
                                this.setState({
                                    visibleGroupManageMentBox: false
                                })
                            }}
                            okHandler={(aGroups, mGroups, dGroups) => {
                                return dispatch({ type: 'dataSource/remoteSetGroups', aGroups, mGroups, dGroups }).then(() => {
                                    dispatch({ type: 'dataSource/fetchList', mandatory: true });
                                    dispatch({ type: 'dataSource/setCurrentGroup', group: null });
                                });
                            }}
                        />}
                        {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: 'dataSource/fetchList', mandatory: true });
                                })
                            }} 
                        />}
                        {visibleDataPreviewBox && <DataPreview
                            title={selectedRecord.name}
                            visibleBox={visibleDataPreviewBox}
                            hideBox={() => {
                                this.setState({
                                    visibleDataPreviewBox: false
                                });
                            }}
                            fetchFunction={(page, pageSize) => {
                                dispatch({ type: 'dataSource/remoteDataList', code: selectedRecord.code, page, pageSize });
                            }}
                        />}
                    </Card>
                </Content>
            </Layout>
        )

    }
}

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

export default connect(mapStateToProps)(DataSource)