import React from 'react'
import { connect } from 'dva'
import { Modal, Form, Select } from 'antd'
const { Item: FormItem } = Form
const { Option: SelectOption } = Select

class CopyBox extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            currentDataConnectCode: props.currentDataConnectCode ? props.currentDataConnectCode : null
        }
    }

    componentDidMount() {
        const { dispatch } = this.props;
        dispatch({ type: 'dataConnect/fetchList' });
    }

    generateOption() {
        const { dataConnect } = this.props;
        const { currentDataConnectCode } = this.state;
        const { list } = dataConnect;

        return list.filter((l) => l.code !== currentDataConnectCode).map((l) => <SelectOption key={l.code} value={l.code}>{l.name}</SelectOption>);
    }

    render() {
        const { visibleBox, hideBox, dispatch, currentDataSourceCode } = this.props;
        const { currentDataConnectCode } = this.state;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 8 },
        }

        return <Modal
            className='copy-box'
            title={'复制数据源'}
            visible={visibleBox}
            onCancel={hideBox}
            onOk={() => {
                dispatch({ type: 'dataSource/copy', dataSourceCode: currentDataSourceCode, dataConnectCode: currentDataConnectCode }).then(() => {
                    hideBox()
                });
            }}
            maskClosable={true}
            destroyOnClose={true}
        >
            <Form>
                <FormItem
                    label='切换数据链接'
                    {...formItemLayout}
                >
                    <Select
                        disabled={!currentDataConnectCode}
                        placeholder='不切换'
                        onChange={(value) => {
                            this.setState({
                                currentDataConnectCode: value
                            })
                        }}
                    >
                        { this.generateOption() }
                    </Select>
                </FormItem>
            </Form>
        </Modal>
    }
}

export default connect(({ dataConnect }) => ({ dataConnect }))(CopyBox)