import React from 'react'
import { Layout, Row, Col, Input, Button, Table, Icon, Tag, Menu, Dropdown, Card } from 'antd'
import { connect } from 'dva'
import '../../models/dataSource'
import '../../models/dataConnect'
import './dataSource.less'
import { dateFormat } from '../../utils/baseUtils'
const { Content } = Layout
const { Search } = Input

class DataSource extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            activeTab: 'dataSource',
            visibleCreateBox: false,
            selectedDataSourceCode: -1, // 当前选中的dataSource的code
            filterDropdownVisible: false,
            search: {} // 搜索条件
        }
    };

    componentDidMount() {
        this.setScrollTableHeight();
    }

    /**
     * 根据视图设置表格高度以呈现滚动条
     */
    setScrollTableHeight() {
        const mainContent = document.getElementsByClassName('main-content')[0];
        //const tabBar = mainContent.getElementsByClassName('datasource-view')[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`;
    }

    onInputChange = (name, value) => {
        const { search } = this.state;
        let newSearch = Object.assign({}, search );
        newSearch[name] = value;
        this.setState({ search: newSearch });
    }

    onSearch = () => {
        this.setState({
          filterDropdownVisible: false
        });
      }

    render() {
        
        const { dataSource, dispatch } = this.props;
        const { loading, activeTab, selectedDataSourceCode } = this.state;
        
        const moreOperatingMenu = (
            <Menu className='operationmenu'>
                <Menu.Item
                    onClick={() => {
                        dispatch({ type: 'main/redirect', path: '/chart/create' });
                        dispatch({ type: 'chartDesigner/changeDataSource', value: {
                            dataSource: selectedDataSourceCode,
                            viewType: 'bar'
                        } });
                    }}
                >
                    <Icon type="file-add" />创建图表
                </Menu.Item>
                <Menu.Item
                    onClick={(e) => {
                        let selectedModel = dataSource.list.find((i) => { return i.code === selectedDataSourceCode })
                        dispatch({type: 'main/redirect', path: {pathname: '/datasource/'+ selectedModel.type +'/' + selectedModel.code + '/base'}});
                    }}>
                    <Icon type="info-circle-o" />属性设置
                </Menu.Item>
                <Menu.Item onClick={() => {
                    let selectedModel = dataSource.list.find((i) => { return i.code === selectedDataSourceCode })
                    dispatch({type: 'main/redirect', path: {pathname: '/datasource/'+ selectedModel.type +'/' + selectedModel.code + '/column'}});
                }}>
                    <Icon type="table" />数据列设置
                </Menu.Item>
                <Menu.Item><Icon type="search" />预览数据</Menu.Item>
                <Menu.Item onClick={() => {
                    let selectedModel = dataSource.list.find((i) => { return i.code === selectedDataSourceCode })
                    dispatch({type: 'main/redirect', path: {pathname: '/datasource/'+ selectedModel.type +'/' + selectedModel.code + '/access'}});
                }}><Icon type="lock" />权限设置</Menu.Item>
                <Menu.Divider />
                <Menu.Item
                    onClick={(e) => {
                        dispatch({ type: 'dataSource/remoteDelete', code: selectedDataSourceCode });
                    }}
                ><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 type-${record.type.key}`}></div>
                    <div>{text}</div>
                </div>
            }
        }, {
            title: '标签',
            dataIndex: 'tags',
            key: 'tag',
            width: 150,
            render: (text, record) => {
                text=text.join(',');
                let tags = text ? text.split(',').map((t, i) => {
                    return <Tag className='datasource-tag' key={i}>{t}</Tag>
                }) : '';
                return (<div>
                    {tags}
                </div>)
            }
        }, {
            title: '说明',
            dataIndex: 'description',
            key: 'description',
            width: 200
        }, {
            title: '创建人',
            dataIndex: 'creator',
            key: 'creator',
            width: 100
        }, {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (text, record) => dateFormat(text, 'yyyy-MM-dd hh:mm:ss'),
            width: 100
        }, {
            title: '图表',
            dataIndex: 'chartSum',
            key: 'chartSum',
            width: 80
        }, {
            title: '操作',
            key: 'action',
            render: (text, record, index) => (
                <Dropdown code={record.code} overlay={moreOperatingMenu} trigger={['click']} >
                    <Icon type="setting" />
                </Dropdown>
            ),
            width: 80
        }];

        return ( 
            <Layout className='datasource-view'>
                <Content>
                    <Card className='datasource-body' title={
                        <Row className='datasource-tools' type='flex' justify='end'>
                            <Col className='search'>
                                <Search
                                    placeholder="请输入关键字"
                                    onSearch={value => console.log(value)}
                                />
                            </Col>
                            <Col>
                                <Dropdown overlay={(
                                    <Menu onClick={(item, key, keyPath) => {
                                        const type = item.key;
                                        dispatch({ type: 'dataSource/resetNewModel' });
                                        dispatch({ type: 'dataSource/setNewModelField', name: 'type', value: type });
                                        dispatch({type: 'main/redirect', path: {pathname: '/datasource/'+ type +'/create'}});
                                    }}>
                                        <Menu.Item key='database'>数据库</Menu.Item>
                                        <Menu.Item key='file'>文件</Menu.Item>
                                    </Menu>
                                )} trigger={['click']}>
                                    <Button style={{ display: activeTab==='dataConnect'?'none':'inline-block' }}>
                                        <Icon type="plus" />添加数据源
                                    </Button>
                                </Dropdown>
                            </Col>
                        </Row>
                    }>
                        <Table
                            className='datasource-table datasource-table'
                            columns={dataSourceColumns}
                            dataSource={dataSource.list.sort((a, b) => {
                                return new Date(b.createTime) - new Date(a.createTime);
                            })}
                            loading={loading}
                            size='small'
                            scroll={{x: false, y: true}}
                            pagination={false}
                            onRow={(record) => {
                                return {
                                    onClick: () => {this.setState({ selectedDataSourceCode:  record.code})}
                                }
                            }}
                        />
                    </Card>
                </Content>
            </Layout>
        )


    }
}

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

export default connect(mapStateToProps)(DataSource)