import React from 'react'
import { Form, Input, Select, Divider, Cascader } from 'antd'
import { arrayToTree } from '../../utils/baseUtils'
import { connect } from 'dva'
import './baseConfig.less'
const FormItem = Form.Item
const SelectOption = Select.Option

class DataSourceBaseConfig extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            validInfo: {
                name: { status: 'success', help: '' },
                description: { status: 'success', help: '' },
            }
        }
    }

    generateOptions () {
        const { dataConnect } = this.props;
        const { list } = dataConnect;

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

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

    generateGroupOptions = (treeData) => {
        return treeData.map(t => {
            t.children = t.children instanceof Array ? t.children : [];
            return {
                key: t.code,
                value: t.code,
                label: t.label,
                children: this.generateGroupOptions(t.children)
            }
        })
    }

    getParents = (group) => {
        const groupData = this.props.dataSource.groupList;
        let pgroups = [group];
        let fgroup = groupData.find(g => g.code === group.pcode);
        if(fgroup) {
            pgroups = this.getParents(fgroup).concat(pgroups);
        }
        return pgroups;
    }

    render() {
        const { dataConnect, dataSource, dataSourceDetail, dispatch } = this.props;
        const { validInfo } = this.state;
        const treeData = arrayToTree(dataSource.groupList, '-1', 'code', 'pcode', 'children');
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
        };
    
        let getGroup = () => {
            const { group: key } = dataSourceDetail;
            if(key === '-1') {
                return ['-1'];
            }else {
                let group = dataSource.groupList.find(g => g.code === key);
                if(group) {
                    let groups = this.getParents(group);
                    let val = groups.map(g => g.code);
                    return val;
                }else {
                    return null;
                }
            }
        }
    
        return (
            <Form className='base-config' size='small'>
                <FormItem label='数据源名称' {...formItemLayout}
                    validateStatus={validInfo.name.status}
                    help={validInfo.name.help}
                >
                    <Input
                        key={dataSourceDetail.code + '-name'}
                        defaultValue={dataSourceDetail.name}
                        onBlur={(e) => {
                            let value = e.target.value;
                            if(value !== dataSourceDetail.name) {
                                dispatch({ type: 'dataSourceDetail/setField', name: 'name', value });
                            }
                        }}
                        onChange={e => {
                            let val = e.target.value + '';
                            let status, help;
                            
                            if(val.trim().length === 0) {
                                status = 'error';
                                help = '数据源名称不能为空';
                            }else if(val.trim().length > 50) {
                                status = 'error';
                                help = '数据源名称不能超过50个字符';
                            }else {
                                status = 'success';
                                help = '';
                            }

                            // 如果status发生了改变，将数据同步到dataSourceDetail Model
                            if(validInfo.name.status !== status) {
                                dispatch({ type: 'dataSourceDetail/setField', name: 'name', value: val });
                            }

                            window.clearTimeout(this.nameTimeout);
                            this.nameTimeout = window.setTimeout(() => {
                                this.setState({
                                    validInfo: { ...validInfo, name: { status, help } }
                                });
                            }, 100);
                        }}>
                    </Input>
                </FormItem>
                {
                    dataSourceDetail.type==='file'?(
                        <div>
                            <Divider orientation="left">文件</Divider>
                            <div>此处显示文件名</div>
                        </div>
                    ):(
                        <div>
                            <FormItem label='数据链接' {...formItemLayout}>
                                <Select
                                    disabled
                                    value={dataSourceDetail.connectCode}
                                    onChange={(value) => {
                                        let selectedDataConnect = dataConnect.list.filter((l) => l.code === value)[0];
                                        dispatch({ type: 'dataSourceDetail/setFields', fields: [
                                            { name: 'connectCode', value: selectedDataConnect.code },
                                            { name: 'dbType', value: selectedDataConnect.dbType },
                                            { name: 'address', value: selectedDataConnect.address },
                                            { name: 'port', value: selectedDataConnect.port },
                                            { name: 'dbName', value: selectedDataConnect.dbName },
                                            { name: 'userName', value: selectedDataConnect.userName },
                                        ] } );
                                    }}
                                >
                                    { this.generateOptions() }
                                </Select>
                            </FormItem>
                            {/* <FormItem label='数据库类型' {...formItemLayout}>
                                <Select
                                    disabled={true}
                                    value={dataSourceDetail.dbType}
                                    onChange={(value) => {
                                        dispatch({ type: 'dataSourceDetail/setField', name: 'dbType', value: value} );
                                    }}
                                >
                                    <SelectOption value='oracle'>
                                        ORACLE
                                    </SelectOption>
                                    <SelectOption value='mysql'>
                                        MYSQL
                                    </SelectOption>
                                    <SelectOption value='sqlserver'>
                                        SQLSERVER
                                    </SelectOption>
                                    <SelectOption value='sqlite'>
                                        SQLITE
                                    </SelectOption>
                                </Select>
                            </FormItem>
                            <Row>
                                <Col span={19}>
                                    <FormItem label='数据库地址' {...{
                                        labelCol: { span: 5 },
                                        wrapperCol: { span: 19 }
                                    }}>
                                        <Input
                                            disabled={true}
                                            value={dataSourceDetail.address}
                                            onChange={(e) => {
                                                dispatch({ type: 'dataSourceDetail/setField', name: 'address', value: e.target.value });
                                            }}
                                        />
                                    </FormItem>
                                </Col>
                                <Col span={5}>
                                    <FormItem className='input-port' label='端口' {...{
                                        labelCol: { span: 12 },
                                        wrapperCol: { span: 12 }
                                    }}>
                                        <InputNumber
                                            disabled={true}
                                            value={dataSourceDetail.port}
                                            onChange={(value) => {
                                                dispatch({ type: 'dataSourceDetail/setField', name: 'port', value: value });
                                            }}
                                        />
                                    </FormItem>
                                </Col>
                            </Row>
                            <FormItem label='数据库名' {...formItemLayout}>
                                <Input
                                    disabled={true}
                                    value={dataSourceDetail.dbName}
                                    onChange={(e) => {
                                        dispatch({ type: 'dataSourceDetail/setField', name: 'dbName', value: e.target.value });
                                    }}
                                />
                            </FormItem>
                            <Row>
                                <Col span={12}>
                                    <FormItem label='用户名' {...{
                                        labelCol: { span: 8 },
                                        wrapperCol: { span: 16 }
                                    }}>
                                        <Input
                                            disabled={true}
                                            value={dataSourceDetail.userName}
                                            onChange={(e) => {
                                                dispatch({ type: 'dataSourceDetail/setField', name: 'userName', value: e.target.value });
                                            }}
                                        />
                                    </FormItem>
                                </Col>
                                <Col span={12}>
                                    <FormItem label='密码' {...{
                                        labelCol: { span: 8 },
                                        wrapperCol: { span: 16 }
                                    }}>
                                        <Input
                                            disabled={true}
                                            // value={dataSourceDetail.password}
                                            onChange={(e) => {
                                                let value = e.target.value;
                                                dispatch({ type: 'dataSourceDetail/setField', name: 'password', value: value });
                                                e.target.removeAttribute('value')
                                            }}
                                        />
                                    </FormItem>
                                </Col>
                            </Row> */}
                        </div>
                    )
                }
                <FormItem label='所属分组' {...formItemLayout}>
                    <Cascader
                        value={getGroup()}
                        allowClear={true}
                        changeOnSelect={true}
                        expandTrigger='hover'
                        placeholder='未分组'
                        options={this.generateGroupOptions([{pcode: '-1', code: '-1', label: '未分组'}].concat(treeData))}
                        onChange={(value, items) => {
                            let v = value[value.length - 1];
                            dispatch({ type: 'dataSourceDetail/setField', name: 'group', value: v });
                        }}
                        
                    >
                    </Cascader>
                </FormItem>
                <FormItem className='textarea-desc' label='说明' {...formItemLayout}
                     validateStatus={validInfo.description.status}
                     help={validInfo.description.help}
                >
                    <Input.TextArea
                        key={dataSourceDetail.code+'-description'}
                        autosize={{ minRows: 2, maxRows: 5 }}
                        defaultValue={dataSourceDetail.description}
                        onBlur={(e) => {
                            let value = e.target.value;
                            if(value !== dataSourceDetail.description) {
                                dispatch({ type: 'dataSourceDetail/setField', name: 'description', value });
                            }
                        }}
                        onChange={e => {
                            let val = e.target.value + '';
                            let status, help;
                            if(val.length > 150) {
                                status = 'error';
                                help = '说明不能超过150个字符';
                            }else {
                                status = 'success';
                                help = '';
                            }

                            // 如果status发生了改变，将数据同步到dataSourceDetail Model
                            if(validInfo.name.status !== status) {
                                dispatch({ type: 'dataSourceDetail/setField', name: 'description', value: val });
                            }

                            window.clearTimeout(this.descriptionTimeout);
                            this.descriptionTimeout = window.setTimeout(() => {
                                this.setState({
                                    validInfo: { ...validInfo, description: { status, help } }
                                });
                            }, 100);
                        }}
                    />
                </FormItem>
            </Form>
        );
    }
}

export default connect(({ dataConnect, dataSource, dataSourceDetail }) => ({ dataConnect, dataSource, dataSourceDetail }))(DataSourceBaseConfig);