/**
 * @Classname AddConfigForm
 * @Description TODO
 * @Date 2019/8/22 11:45
 * @Created by Administrator
 * 编辑或者添加微服务配置属性
 */

import React from 'react';
import * as PropTypes from 'prop-types';
import { connectAlita } from 'redux-alita';

import { AutoComplete, Button, Form, Input, message, Modal, Select } from 'antd';
import TuonSelect from '../../../components/widget/TuonSelect';

class AddConfigForm extends React.Component {

    static propTypes = {
        onCancel: PropTypes.func,
        visible: PropTypes.bool,
        config: PropTypes.object,
        onRefresh: PropTypes.func,
        fData:PropTypes.object
    };

    static defaultProps = {
        config: {
            id: undefined,
            key: undefined,
            value: undefined,
            application: undefined,//暂时定如果为空，则是通用的
            profile: 'dev',
            label: 'master',
            desc: undefined,
        },
        fData:{data:{}}
    };

    static getDerivedStateFromProps(nextProps, prevState) {
        let { visible, config } = nextProps;
        return {
            visible, config: config || { profile: 'dev', label: 'master' },
        };
    }

    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            config: {},
        };
    }

    _queryLabelList(keywords) {
        if (!keywords) return;
        let params = { keywords, pageSize: 6 };
        this.props.setAlitaState({ funcName: 'searchLabel', params });
    }


    handleAddConfig(values) {
        this.props.setAlitaState({ funcName: 'configAddConfig', params: values })
            .then(resp => {
                message.success('添加成功！');
                this.props.onRefresh && this.props.onRefresh();
            });
    }

    handleEditConfig(values) {
        let params = { id: this.state.config.id, data: values };
        this.props.setAlitaState({ funcName: 'configEditConfig', params })
            .then(() => {
                message.success('修改成功！');
                this.props.onCancel && this.props.onCancel();
                this.props.onRefresh && this.props.onRefresh();
            });
    }

    _onModalOkPress(e) {
        e.preventDefault();
        let _this = this;
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                if (_this.state.config.id) {
                    _this.handleEditConfig(values);
                } else {
                    _this.handleAddConfig(values);
                }
            } else {
                console.log('validateFields error=>', err);
            }
        });
    }


    _onModalCancel() {
        this.props.onCancel && this.props.onCancel();
        this.props.form.resetFields();
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        let { visible } = this.state;
        const { data: labelPage, isFetching: isSearching } = this.props.searchLabel || {};

        let isSubmitting = false;
        if (this.props.configAddConfig && this.props.configAddConfig.isFetching) {
            isSubmitting = true;
        }
        if (this.props.configEditConfig && this.props.configEditConfig.isFetching) {
            isSubmitting = true;
        }

        let labelList = [];
        if (labelPage && labelPage.records) {
            labelList = labelPage.records;
        }

        let config = this.state.config;

        let {cApps,cLabels,cProfiles} =this.props.fData.data;
        return (<Modal title={config.id ? '编辑配置项' : '新增配置项'}
                       onCancel={this._onModalCancel.bind(this)}
                       onOk={this._onModalOkPress.bind(this)}
                       footer={[
                           <Button key="back" htmlType="button" onClick={this._onModalCancel.bind(this)}>取消</Button>,
                           <Button key="submit" htmlType="button" type="primary"
                                   onClick={this._onModalOkPress.bind(this)}
                                   loading={isSubmitting}
                           >提交</Button>,
                       ]}
                       visible={visible}
        >
            <Form>
                <Form.Item>
                    {getFieldDecorator('application', { initialValue: config.application })(
                        <TuonSelect placeholder="请选择应用系统" data={cApps}/>)}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('profile', { initialValue: config.profile })(
                        <TuonSelect placeholder="请选择环境" data={cProfiles}/>)}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('label', { initialValue: config.label })(
                        <TuonSelect placeholder="请选择分支" data={cLabels}/>)}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('key',
                        {
                            initialValue: config.key,
                            rules: [{ required: true, message: '请输入配置项' }],
                        })(<AutoComplete
                            dataSource={labelList}
                            loading={isSearching}
                            placeholder="请输入配置项"
                            onSearch={this._queryLabelList.bind(this)}>
                            {labelList.map(item => <AutoComplete.Option key={item.id}
                                                                        value={item.path}>{item.path}</AutoComplete.Option>)}
                        </AutoComplete>,
                    )}
                </Form.Item>

                <Form.Item>
                    {getFieldDecorator('value', { initialValue: config.value })(<Input
                        placeholder="请输入值"
                    />)}
                </Form.Item>

                <Form.Item>
                    {getFieldDecorator('desc', { initialValue: config.desc })(<Input
                        placeholder="输入配置简介"
                    />)}
                </Form.Item>
            </Form>
        </Modal>);
    }


}


export default connectAlita(['searchLabel', 'configAddConfig', 'configEditConfig','fData'])(Form.create({ name: 'AddConfigForm' })(AddConfigForm));
