/** @format */

import * as React from 'react'
import {Select, Form, Button, Modal, Input, Spin} from "antd"
import Result from '../../../../components/result'
import {useDataEditorDb} from "../../../../service/dataEditor"
import {useEffect} from "react"
import {FormComponentProps} from "antd/es/form"



interface dbSourceSelectProps {
    getDbSourceConfig:any
}

const {Option} = Select

const formItemLayout = {
    labelCol: {
        span: 6
    },
    wrapperCol: {
        span: 12
    },
}

const DbSourceSelect: React.FC<FormComponentProps & dbSourceSelectProps> = props => {
    let [dbConfig, dbConfigRequest] = useDataEditorDb()
    const {getFieldDecorator, validateFields} = props.form 
    useEffect(() => {
        dbConfigRequest()
    }, [])

    const toGetDataKey = () => {
        validateFields((errors, data) => {
            props.getDbSourceConfig && props.getDbSourceConfig(data.dbSource)
        })
    }

    return (
        <Spin spinning={dbConfig.loading}>
            <Result error={dbConfig.error}
                    onRetry={dbConfigRequest}>
                <Form {...formItemLayout}>
                    <Form.Item label="数据源">
                        {
                            getFieldDecorator("dbSource", {
                                rules:[
                                    {
                                        required: true,
                                        message: "必选"
                                    }
                                ]
                            })(
                                <Select>
                                    {
                                        dbConfig.dbList.map(({db_code, db_name}) => {
                                            return <Option key={db_code} value={db_code}>{db_name}</Option>
                                        })
                                    }
                                </Select>
                            )
                        }
                        <Button onClick={toGetDataKey}>确定</Button>
                    </Form.Item>
                </Form>
            </Result>
        </Spin>
    )
}
export default Form.create<FormComponentProps & dbSourceSelectProps>()(DbSourceSelect)
