import React from 'react'
import { Layout, Form, Row, Col, Input, Icon, Menu, Dropdown, Divider, Upload, message, Card } from 'antd'
import { connect } from 'dva'
import DataConnectBox from './dataConnectBox'
import Ellipsis from 'ant-design-pro/lib/Ellipsis'
const { Content } = Layout
const CardGrid = Card.Grid
const UploadDragger = Upload.Dragger
const Search = Input.Search

class DataConnectConfig extends React.Component {
    
    componentDidMount() {
        const { dispatch } = this.props;
        dispatch({ type: 'dataConnect/fetchList' });
    }

    render() {
        const { dataSourceDetail, dataConnect, dispatch } = this.props;
        const reg = new RegExp('([+ \\- & | ! ( ) { } \\[ \\] ^ \" ~ * ? : ( ) \/])', 'g'); // 需要转义的字符
        let filterLabel = dataConnect.filterLabel.replace(new RegExp('(\\\\)', 'g'), '\\$1').replace(reg, '\\$1'); // 添加转义符号
        
        const generateCard = () => {
            const operationMenu = (
                <Menu className='menu-operation'>
                    <Menu.Item onClick={() => {
                        dispatch({ type: 'dataConnect/setNewModel', model: dataConnect.selected });
                        dispatch({ type: 'dataConnect/setNewModelFields', fields: [
                            { name: 'visibleBox', value: true },
                            { name: 'boxOperation', value: 'modify' }
                        ] });
                    }}>
                        <Icon type='edit'/>编辑
                    </Menu.Item>
                    <Menu.Item onClick={(e) => {
                        dispatch({ type: 'dataConnect/remoteDelete', code: dataConnect.selected.code });
                    }}>
                        <Icon type='delete'/>删除
                    </Menu.Item>
                </Menu>
            )

            let cards = dataConnect.list.filter(l => {
                return ((l.name || '').search(new RegExp('(' + filterLabel + '){1}', 'ig')) !== -1) ||
                    ((l.description || '').search(new RegExp('(' + filterLabel + '){1}', 'ig')) !== -1);
            }).map( (l, i) => (
                <CardGrid className='dataconnect-card' key={i}>
                    <Card
                        title={
                            <Row type='flex' justify='start'>
                                <Col className='label'>{l.name}</Col>
                                <div style={{ display: (dataConnect.selected && dataConnect.selected.code === l.code) ? 'block' : 'none' }} className='selected'></div>
                            </Row>
                        }
                        onClick={() => {
                            // 选中项设置
                            dispatch({ type: 'dataConnect/setSelected', selected: l });
                            dispatch({ type: 'dataSourceDetail/setFields', fields: [
                                { name: 'connectCode', value: l.code },
                                { name: 'dbType', value: l.dbType },
                                { name: 'address', value: l.address },
                                { name: 'port', value: l.port },
                                { name: 'dbName', value: l.dbName },
                                { name: 'userName', value: l.userName },
                                { name: 'password', value: l.password },
                                { name: 'target', value: '' },
                                { name: 'columns', value: [] },
                                { name: 'notice', value: '' },
                            ] });
                        }}
                    >
                        <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', height: '100%' }}>
                            <Row>
                                <Ellipsis lines={3}>
                                    {l.description}
                                </Ellipsis>
                            </Row>
                            <Row type='flex' justify='space-between'>
                                <Col>{l.dbType}</Col>
                                <Col>
                                    <Dropdown overlay={operationMenu} trigger={['click']}>
                                        <Icon type="ellipsis" />
                                    </Dropdown>
                                </Col>
                            </Row>
                        </div>
                    </Card>
                </CardGrid>
            ))

            cards.unshift(
                <CardGrid className='dataconnect-card dataconnect-card-create' key='create' onClick={() => {
                    dispatch({ type: 'dataConnect/setNewModel', model: {} });
                    dispatch({ type: 'dataConnect/setNewModelFields', fields: [
                        { name: 'visibleBox', value: true },
                        { name: 'boxOperation', value: 'create' }
                    ] });
                }}>
                    <Card>
                        <Icon type="plus-circle-o" />
                    </Card>
                </CardGrid>
            );
            
            return cards;
        }

        return (
            <Form className='form-base' size='small'>
                {
                    dataSourceDetail.type==='file'?(
                        <div>
                            <Divider orientation="left">选择文件</Divider>
                            <UploadDragger
                                className='upload'
                                name='file' // 上传到后台的文件名
                                fileList={dataSourceDetail.fileList}
                                accept='application/vnd.ms-excel,.csv' // 只支持excel和csv格式文件
                                action='//jsonplaceholder.typicode.com/posts/'
                                headers={{authorization: 'authorization-text'}}
                                beforeUpload={(file, fileList) => {
                                    const trueType = file.type === 'application/vnd.ms-excel';
                                    if (!trueType) {
                                        message.error('选择文件格式错误!');
                                    }
                                    const trueSize = file.size / 1024 / 1024 < 30;
                                    if (!trueSize) {
                                        message.error('选择文件过大!');
                                    }
                                    return trueType && trueSize;
                                }}
                                onChange={(info) => {
                                    const file = info.file;
                                    let fileList = info.fileList;
                                    fileList = fileList.slice(-1); // 只保留最后一个
                                    if (info.file.status !== 'uploading') {
                                        console.log(file, info.fileList);
                                        const trueType = file.type === 'application/vnd.ms-excel';
                                        const trueSize = file.size / 1024 / 1024 < 30;
                                        if(!trueType || !trueSize) {
                                            fileList = [];
                                        }
                                    }
                                    if (file.status === 'done') {
                                        message.success(`${file.name} 文件上传成功`);
                                    } else if (file.status === 'error') {
                                        fileList = [];
                                        message.error(`${file.name} 文件上传失败.`);
                                    }
                                    dispatch({ type: 'dataSourceDetail/setField', name: 'fileList', value: fileList })
                                }}
                            >
                                <p className="ant-upload-drag-icon">
                                    <Icon type="inbox" />
                                </p>
                                <p className="ant-upload-text">点击选择或拖动文件到该区域</p>
                                <p className="ant-upload-hint">仅支持上传单个30MB以内EXCEL/CSV格式文件</p>
                            </UploadDragger>
                        </div>
                    ):(
                        <Layout className='dataconnect'>
                            <Content>
                                <Card title={
                                    <Row type='flex' justify='end'>
                                        <Search
                                            style={{ width: '200px' }}
                                            value={dataConnect.filterLabel}
                                            placeholder="请输入关键字"
                                            onChange={e => {
                                                dispatch({ type: 'dataConnect/setFilterLabel', label: e.target.value });
                                            }}
                                        />
                                    </Row>
                                }>
                                    <div className='dataconnect-list'>
                                        { generateCard() }
                                    </div>
                                    <DataConnectBox />
                                </Card>
                            </Content>
                        </Layout>
                    )
                }
            </Form>
        );
    }
}

export default connect(({ present: { dataSourceDetail, dataConnect } }) => ({ dataSourceDetail, dataConnect }))(DataConnectConfig);