import React from 'react'
import { Layout, Button, Table, Form, Row, Col, Input, InputNumber, Select, Icon, Menu, Dropdown, Divider, Upload, message, Card } from 'antd'
const { Header, Content } = Layout
const CardGrid = Card.Grid
const FormItem = Form.Item
const SelectOption = Select.Option
const OptionGroup = Select.OptGroup
const InputGroup = Input.Group
const SubMenu = Menu.SubMenu
const MenuItem = Menu.Item
const MenuItemGroup = Menu.ItemGroup
const UploadDragger = Upload.Dragger
const Search = Input.Search
import { connect } from 'dva'
import DataConnectBox from './dataConnectBox'
import '../../models/dataSource'
import '../../models/dataConnect'

class DataConnectConfig extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visibleBox: false,
            operation: 'modify',
            selected: null
        };
    }
    render() {
        const { dataSource, dataConnect, dispatch } = this.props;
        const { visibleBox, operation, selected } = this.state;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
        };

        const generateCard = () => {
            const operationMenu = (
                <Menu className='menu-operation'>
                    <Menu.Item onClick={() => {
                        dispatch({ type: 'dataConnect/setNewModel', model: selected });
                        this.setState({
                            visibleBox: true,
                            operation: 'modify'
                        })
                    }}>
                        <Icon type='edit'/>编辑
                    </Menu.Item>
                    <Menu.Item onClick={(e) => {
                        dispatch({ type: 'chart/remoteDelete', code: this.state.selectedCode });
                    }}>
                        <Icon type='delete'/>删除
                    </Menu.Item>
                </Menu>
            )

            let cards = dataConnect.list.map( (l, i) => (
                <CardGrid className='dataconnect-card' key={i}>
                    <Card
                        title={
                            <Row type='flex' justify='start'>
                                <Col>{l.name}</Col>
                                <div style={{ display: (selected && selected.code === l.code) ? 'block' : 'none' }} className='selected'></div>
                            </Row>
                        }
                        onClick={() => {
                            this.setState({ selected: l }, () => {
                                let s = this.state.selected;
                                console.log(s);
                                dispatch({ type: 'dataSource/setNewModelFields', fields: [
                                    { name: 'dbType', value: s.dbType },
                                    { name: 'address', value: s.address },
                                    { name: 'port', value: s.port },
                                    { name: 'dbName', value: s.dbName },
                                    { name: 'userName', value: s.userName },
                                    { name: 'password', value: s.password },
                                ] });
                            });
                        }}
                    >
                        <div>
                            <Row>
                                {`说明 ：${l.description}`}
                            </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: {} });
                    this.setState({
                        operation: 'create',
                        visibleBox: true
                    })
                }}>
                    <Card>
                        <Icon type="plus-circle-o" />
                    </Card>
                </CardGrid>
            );
            
            return cards;
        }

        return (
            <Form className='form-base' size='small'>
                {
                    dataSource.newOne.type=='file'?(
                        <div>
                            <Divider orientation="left">选择文件</Divider>
                            <UploadDragger
                                className='upload'
                                name='file' // 上传到后台的文件名
                                fileList={dataSource.newOne.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: 'dataSource/setNewModelField', 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' }}
                                            placeholder="请输入关键字"
                                            onSearch={value => console.log(value)}
                                        />
                                    </Row>
                                }>
                                    <div className='dataconnect-list'>
                                        { generateCard() }
                                    </div>
                                    <DataConnectBox visibleBox={visibleBox} hideBox={() => {this.setState({visibleBox: false})}} operation={operation} />
                                </Card>
                            </Content>
                        </Layout>
                    )
                }
            </Form>
        );
    }
}

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

export default connect(mapStateToProps)(DataConnectConfig);