import React from 'react';
import { AutoComplete, Form, Input, message, Modal } from 'antd';
import { connectAlita } from 'redux-alita';
import * as PropTypes from 'prop-types';

/**
 * 添加属性标签的表单,
 * 包括编辑，和添加
 */
class AddLabelForm extends React.Component {

    static defaultProps = {
        searchLabel: { data: {} },
        cancel: () => {
        },
    };

    static propTypes = {
        visible: PropTypes.bool,
        refresh: PropTypes.func,
    };

    constructor(props) {
        super(props);
        let { label } = props;
        this.state = {
            label: label || { pid: 0 },
            labelList: [],
            visible: false,
        };
    }

    pLabel = {};

    componentWillReceiveProps(nextProps, nextContext) {
        let { label, visible } = nextProps;
        this.setState({ label: label || { pid: 0 }, visible });
    }


    closeModal() {


    }

    handleLabelAdd = (values, label) => {
        let params = { id: this.state.label.id, pid: label.pid };
        this.props.setAlitaState({ funcName: 'labelAdd', params: { ...values, ...params } })
            .then(() => {
                message.success('添加成功');
                this.props.refresh && this.props.refresh();
                this.setState({ visible: false });
            })
            .catch(e => {
                console.log('catch ', e);
            });
    };

    handleLabelEdit = (values, label) => {
        let params = { id: this.state.label.id, pid: label.pid };
        this.props.setAlitaState({ funcName: 'labelEdit', params: { ...values, ...params } })
            .then(() => {
                message.success('编辑成功');
                this.props.refresh && this.props.refresh();
                this.setState({ visible: false });
            });

    };

    handleSubmit = e => {
        e.preventDefault();
        const _this = this;
        let pLabel = _this.pLabel;
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                if (pLabel.id) {
                    _this.handleLabelEdit(values, pLabel);
                } else {
                    _this.handleLabelAdd(values, pLabel);
                }
            }
        });
    };

    handleSearchLabel = (keywords) => {
        this.props.setAlitaState({ funcName: 'searchLabel', params: { keywords } })
            .then(resp => {
                console.log('resp label ', resp);
            })
            .catch(e => {
                console.log('err ', e);
            });
    };

    onSelect(sources = [], path) {
        for (let i in sources) {
            let source = sources[i];
            if (source.path === path) {
                this.pLabel = { pid: source.id };
                break;
            }
        }
    }


    render() {
        let { label } = this.props;
        if (!label) return null;
        const { data: dataSource, isFetching } = this.props.searchLabel || { data: {} };
        const { isFetching: isSubmitLoading } = this.props.labelAdd || {};
        const { isFetching: isEditLoading } = this.props.labelEdit || {};

        let records = dataSource ? dataSource.records : [];
        if (!records) records = [];

        return (<Modal visible={this.state.visible}
                       title={label.id ? '编辑标签' : '添加标签'}
                       onOk={this.handleSubmit.bind(this)}
                       onCancel={() => this.setState({ visible: false })}>
            {this.renderForm(records, label, isFetching, isSubmitLoading || isEditLoading)}
        </Modal>);

    }

    renderForm(records = [], label = {}, isFetching, isLoading = false) {
        const { getFieldDecorator } = this.props.form;
        return (<Form onSubmit={this.handleSubmit}>
            {(!label.id) && (<Form.Item>
                {getFieldDecorator('path')(<AutoComplete onSearch={this.handleSearchLabel}
                                                         dataSource={records.map(item => item.path)}
                                                         loading={isFetching}
                                                         onSelect={this.onSelect.bind(this, records)}
                                                         placeholder="输入关键词查询上级标签"
                />)}
            </Form.Item>)}
            <Form.Item>
                {getFieldDecorator('label', {
                    rules: [{ required: true, message: '请输入标签' }],
                    initialValue: label.label,
                })
                (<Input disabled={!!label.id} placeholder="请输入标签"/>)}
            </Form.Item>
            <Form.Item>
                {getFieldDecorator('title', { initialValue: label.title })(<Input placeholder='请输入标签名称'/>)}
            </Form.Item>
            <Form.Item>
                {getFieldDecorator('description', { initialValue: label.description })(<Input placeholder='请输入标签简介'/>)}
            </Form.Item>
        </Form>);
    }


}

export default connectAlita(['searchLabel', 'labelAdd', 'labelEdit'])(Form.create({ name: 'AddLabelForm' })(AddLabelForm));
