import React from 'react'
import { Modal, Form, Row, Col, Input, InputNumber, Select, Button, Icon } from 'antd'
import { connect } from 'dva'
import './dataConnectBox.less'
const FormItem = Form.Item
const SelectOption = Select.Option

class DataConnectBox extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            password: '',
            validInfo: {
                name: { status: 'success', help: '' },
                dbType: { status: 'success', help: '' },
                address: { status: 'success', help: '' },
                port: { status: 'success', help: '' },
                dbName: { status: 'success', help: '' },
                userName: { status: 'success', help: '' },
                password: { status: 'success', help: '' },
                description: { status: 'success', help: '' },
            }
        }
    }

    hideBox() {
        const { dispatch } = this.props;
        dispatch({ type: 'dataConnect/setNewModelField', name: 'visibleBox', value: false });
    }

    okHandler() {
        const { dispatch, dataConnect} = this.props;
        const operation = dataConnect.newOne.boxOperation;
        this.validAll();
        if(operation === 'create' && this.checkValid()) {
            dispatch({ type: 'dataConnect/remoteAdd' }).then((success) => {
                success && this.hideBox()
            });
        }else if(operation === 'modify' && this.checkValid()) {
            dispatch({ type: 'dataConnect/remoteModify', code: dataConnect.newOne.code }).then((success) => {
                success && this.hideBox();
            });
        }
    }

    validAll = () => {
        const { boxOperation } = this.props.dataConnect.newOne;
        const arr = [
            { name: 'name', label: '数据链接名称', rule: { required: true, maxLength: 50 } },
            { name: 'dbType', label: '数据库类型', rule: { required: true } },
            { name: 'address', label: '数据库地址', rule: { required: true } },
            { name: 'port', label: '端口', rule: { required: true } },
            { name: 'dbName', label: '数据库名', rule: { required: true } },
            { name: 'userName', label: '用户名', rule: { required: true } },
            { name: 'password', label: '密码', rule: { required: boxOperation === 'create' } },
            { name: 'description', label: '说明', rule: { maxLength: 150 } },
        ]
        for(let i = 0; i < arr.length; i++) {
            let a = arr[i];
            this.valid(a.name, undefined, a.label, a.rule);
        }
    }

    // // 执行校验并生成错误提示
    valid = (fieldName, nowValue, fieldLabel, rule) => {
        const { validInfo } = this.state;
        const { dataConnect } = this.props;
        const { newOne } = dataConnect;
        const { required, maxLength, minLength, reg } = rule;

        let value = nowValue === undefined  ? newOne[fieldName] : nowValue;
        let status = 'success';
        let help = '';
        if(status === 'success' && required !== undefined && required) {
            status = (value === undefined || value === null) ? 'error' : ((value + '').trim().length === 0 ? 'error' : 'success');
            help = (value === undefined || value === null) ? fieldLabel + '不能为空' : ((value + '').trim().length === 0 ? fieldLabel + '不能为空' : '');
        }
        if(status === 'success' && minLength !== undefined && minLength > 0) {
            status = !!value && (value + '').length < minLength ? 'error' : 'success'
            help = !!value && (value + '').length < minLength ? fieldLabel + '长度不能小于' + minLength + '个字符' : ''
        }
        if(status === 'success' && maxLength !== undefined && maxLength > 0) {
            status = !!value && (value + '').length > maxLength ? 'error' : 'success'
            help = !!value && (value + '').length > maxLength ? fieldLabel + '长度不能大于' + maxLength + '个字符' : ''
        }
        if(status === 'success' && reg !== undefined) {
            status = !!value.match(new RegExp(reg)) ? 'success' : 'error'
            help = !!value.match(new RegExp(reg)) ? '' : fieldLabel + '格式有误'
        }
        validInfo[fieldName] = { status, help }
        this.setState({
            validInfo
        });
    }

    // 检查错误提示
    checkValid = () => {
        const { validInfo } = this.state;
        let flag = true;

        for(let k in validInfo) {
            if(validInfo[k].status === 'error') {
                flag = false;
            }
        }

        return flag;
    }

    render() {
        const { dispatch, dataConnect } = this.props;
        const { password, validInfo } = this.state;
        const operation = dataConnect.newOne.boxOperation;
        const disabled = operation === 'view';

        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
        };

        return (
            <Modal
                className='dataconnect-box'
                title={`${operation === 'create'?'添加':(operation === 'modify' ? '修改' : '查看')}数据链接`}
                visible={dataConnect.newOne.visibleBox}
                onCancel={() => { this.hideBox() }}
                maskClosable={false}
                destroyOnClose={true}
                footer={
                    operation === 'view' ? null : (
                        <Row type='flex' justify='space-between'>
                            <Col>
                                <Button type='danger' disabled={dataConnect.newOne.validating || dataConnect.newOne.saving} onClick={() => {
                                    dispatch({ type:'dataConnect/resetNewModel'});
                                    this.setState({
                                        password: '',
                                    });
                                }}>清空</Button>
                            </Col>
                            <Col>
                                <Button onClick={() => {this.hideBox()}}>取 消</Button>
                                <Button className={dataConnect.newOne.validating ? 'ant-btn-loading' : ''} type="primary" disabled={dataConnect.newOne.validating || dataConnect.newOne.saving || !this.checkValid()} onClick={() => {this.okHandler()}}>
                                    {dataConnect.newOne.saving ? (<Icon type='loading' />) : ''}
                                    {dataConnect.newOne.saving ? '校验中' : '保存'}
                                </Button>
                            </Col>
                        </Row>
                    )
                }
            >
                <Form size='small'>
                    <FormItem
                        className='required'
                        label='链接名'
                        {...formItemLayout}
                        validateStatus={validInfo.name.status}
                        help={validInfo.name.help}
                    >
                        <Input
                            key={dataConnect.newOne.name}
                            disabled={disabled}
                            placeholder="输入数据链接名称"
                            defaultValue={dataConnect.newOne.name}
                            onChange={e => {
                                let val = e.target.value+'';
                                window.clearTimeout(this.nameTimeout);
                                this.nameTimeout = window.setTimeout(() => {
                                    this.valid('name', val, '数据链接名称', { required: true, maxLength: 50 });
                                }, 100);
                            }}
                            onBlur={(e) => { dispatch({ type: 'dataConnect/setNewModelField', name: 'name', value: e.target.value+'' }) }}
                        >
                        </Input>
                    </FormItem>
                    <FormItem className='required' label='数据库类型' {...formItemLayout}
                        validateStatus={validInfo.dbType.status}
                        help={validInfo.dbType.help}
                    >
                        <Select
                            key={dataConnect.newOne.dbType}
                            disabled={true}
                            placeholder="选择数据库类型"
                            defaultValue='oracle'
                            value={dataConnect.newOne.dbType}
                            onChange={(value) => {
                                dispatch({ type: 'dataConnect/setNewModelField', name: 'dbType', value: value} );
                                this.valid('dbType', value, '数据库类型', { required: true });
                            }}
                        >
                            <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={16}>
                            <FormItem className='required' label='数据库地址' {...{
                                labelCol: { span: 6 },
                                wrapperCol: { span: 18 }
                            }}
                            validateStatus={validInfo.address.status}
                            help={validInfo.address.help}
                            >
                                <Input
                                    key={dataConnect.newOne.address}
                                    disabled={disabled}
                                    placeholder="格式：192.168.1.1"
                                    defaultValue={dataConnect.newOne.address}
                                    onBlur={(e) => {
                                        dispatch({ type: 'dataConnect/setNewModelField', name: 'address', value: e.target.value+'' });
                                    }}
                                    onChange={e => {
                                        let val = e.target.value+'';
                                        window.clearTimeout(this.addressTimeout);
                                        this.addressTimeout = window.setTimeout(() => {
                                            this.valid('address', val, '数据库地址', { required: true });
                                        }, 100);
                                    }}
                                />
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem className='input-port required' label='端口' {...{
                                labelCol: { span: 8 },
                                wrapperCol: { span: 16 }
                            }}
                            validateStatus={validInfo.port.status}
                            help={validInfo.port.help}
                            >
                                <InputNumber
                                    disabled={disabled}
                                    value={dataConnect.newOne.port}
                                    onChange={(value) => {
                                        this.valid('port', value, '端口', { required: true });
                                        dispatch({ type: 'dataConnect/setNewModelField', name: 'port', value: value });
                                    }}
                                />
                            </FormItem>
                        </Col>
                    </Row>
                    <FormItem className='required' label='数据库名' {...formItemLayout}
                        validateStatus={validInfo.dbName.status}
                        help={validInfo.dbName.help}
                    >
                        <Input
                            key={dataConnect.newOne.dbName}
                            disabled={disabled}
                            defaultValue={dataConnect.newOne.dbName}
                            onBlur={(e) => {
                                dispatch({ type: 'dataConnect/setNewModelField', name: 'dbName', value: e.target.value+'' });
                            }}
                            onChange={(e) => {
                                this.valid('dbName', e.target.value+'', '数据库名', { required: true })
                            }}
                        />
                    </FormItem>
                    <Row>
                        <Col span={12}>
                            <FormItem className='required' label='用户名' {...{
                                labelCol: { span: 8 },
                                wrapperCol: { span: 16 }
                            }}
                            validateStatus={validInfo.userName.status}
                            help={validInfo.userName.help}
                            >
                                <Input
                                    key={dataConnect.newOne.userName}
                                    disabled={disabled}
                                    autoComplete="off"
                                    defaultValue={dataConnect.newOne.userName}
                                    onBlur={(e) => {
                                        dispatch({ type: 'dataConnect/setNewModelField', name: 'userName', value: e.target.value+'' });
                                    }}
                                    onChange={(e) => {
                                        this.valid('userName', e.target.value+'', '用户名', { required: true });
                                    }}
                                />
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem className='required' label='密码' {...{
                                labelCol: { span: 8 },
                                wrapperCol: { span: 16 }
                            }}
                            validateStatus={validInfo.password.status}
                            help={validInfo.password.help}
                            >
                                <Input
                                    disabled={disabled}
                                    className='password'
                                    type='password'
                                    value={password}
                                    autoComplete="off"
                                    placeholder={operation === 'create' ? '' : '******'}
                                    onChange={(e) => {
                                        let val = e.target.value+'';
                                        this.setState({
                                            password: val
                                        });
                                        if(operation === 'create') {
                                            this.valid('password', val, '密码', { required: true });
                                        }
                                    }}
                                    onBlur={(e) => {
                                        dispatch({ type: 'dataConnect/setNewModelField', name: 'password', value: e.target.value+'' });
                                    }}
                                />
                            </FormItem>
                        </Col>
                        <Col span={4}>
                            <FormItem>
                                <Button
                                    style={{ marginLeft: '10px' }}
                                    disabled={dataConnect.newOne.validating || dataConnect.newOne.saving}
                                    onClick={() => {
                                        this.validAll();
                                        if(this.checkValid()) {
                                            dispatch({ type:'dataConnect/remoteValidate'})
                                        }
                                    }}
                                    className={`valid-btn ${dataConnect.newOne.invalid === undefined ? 'valid-default' : ( dataConnect.newOne.invalid ? 'valid-failure' : 'valid-success' )}`}
                                >
                                    {dataConnect.newOne.validating ? (<Icon type='loading' />) : ( dataConnect.newOne.invalid === undefined ? <Icon type='question-circle' /> : ( dataConnect.newOne.invalid ? <Icon type="exclamation-circle" /> : <Icon type="check-circle" /> ) ) }
                                    {dataConnect.newOne.invalid === undefined ? '测试' : ( dataConnect.newOne.invalid ? '失败' : '成功' )}
                                </Button>
                            </FormItem>
                        </Col>
                    </Row>
                    <FormItem
                        className='textarea-desc'
                        label='说明'
                        {...formItemLayout}
                        validateStatus={validInfo.description.status}
                        help={validInfo.description.help}
                    >
                        <Input.TextArea
                            key={dataConnect.newOne.description}
                            disabled={disabled}
                            autosize={{ minRows: 2 }}
                            defaultValue={dataConnect.newOne.description}
                            onChange={e => {
                                let val = e.target.value+'';
                                window.clearTimeout(this.nameTimeout);
                                this.nameTimeout = window.setTimeout(() => {
                                    this.setState({
                                        validInfo: { ...validInfo, description: { status: (!!val && val.length > 150) ? 'error' : 'success', help: (!!val && val.length > 150) ? '说明不能超过150个字符' : '' } }
                                    });
                                }, 100);
                            }}
                            onBlur={(e) => {
                                dispatch({ type: 'dataConnect/setNewModelField', name: 'description', value: e.target.value+'' });
                            }}
                        />
                    </FormItem>
                </Form>
            </Modal>
        )
    }
}

function mapStateToProps(state) {
    const dataConnect = state.present.dataConnect;
    return { dataConnect };
}

export default connect(mapStateToProps)(DataConnectBox)