import React, {Component, PropTypes} from 'react';

import {
    Row,
    Col,
    Form,
    Input,
    Button,
    Checkbox,
    Select,
    message,
    Tabs,
    Cascader,
    Radio,
    Upload,
    Icon,
    Modal,
    DatePicker,
    Table,
    Spin
} from 'antd';
import {
    arrayRemoveIndex,
    NULL,
    UUID,
    formItemLayout,
    smallFormItemLayout,
    footerFormSubmitLayout,
    innerHTML
} from '../../utils';


export function CreateBaseElement() {
    return {key: UUID()};
}

export function BaseElementTransform(objs) {
    return Object.keys(objs).map(key=>({
        key: UUID(),
        title: key,
        content: objs[key]
    }));
}

@Form.create()
export default class ElementForm extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            elements: []
        };

    }

    static propsType = {
        product: PropTypes.object,

    };

    componentDidMount() {
        this.analysisBaseElement(this.props);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.isEdit !== this.props.isEdit) {
            this.analysisBaseElement(nextProps);
        }
    }

    analysisBaseElement(props) {
        if (props.product && props.product.elements) {
            const newElements = BaseElementTransform(props.product.elements);
            this.setState({
                elements: newElements
            });
        }
    }

    /**
     * 删除基本要素
     * @param index
     * @param e
     */
    handleRemoveElement(index, e) {
        e.preventDefault();
        const elements = arrayRemoveIndex(this.state.elements, index);
        this.setState({elements: elements});
    }

    /**
     * 添加基本要素
     * @param e
     */
    handleAddElement(e) {
        e.preventDefault();
        let elements = [].concat(this.state.elements);
        elements.push(CreateBaseElement());

        this.setState({elements: elements});
    }

    handleSubmit(e) {
        e.preventDefault();
        const formData = this.props.form.getFieldsValue();
        const tmp = {};
        Object.keys(formData).map(index=> {
            if (formData[index].title != 'undefined') {
                tmp[formData[index].title] = formData[index].content;
            }
        });
        const data = {
            id: this.props.product.id,
            elements: JSON.stringify(tmp)
        }

        console.log('收到表单值：', data);

        this.props.dispatch({
            type: 'UPDATE_PRODUCT_ITEM',
            item: data
        });


    }


    render() {
        const {form:{getFieldProps}, loading, isEdit, isCreate}  = this.props;
        return (
            <Spin spinning={loading}>
                <Form horizontal onSubmit={this.handleSubmit.bind(this)} style={{padding:'0 20px'}}>
                    {
                        isEdit ?  //或者自定义其他要素
                            <Form.Item>
                                <h3>可以设置以下要素</h3>
                                <p>总规模、投资亮点、托管方、结算方式、资金用途、融资方、担保主体、风控措施、还款来源、发行方、认购起点、大小额配比</p>

                                {
                                    this.state.elements.map((item, index)=>
                                        <div key={item.key} style={{marginBottom:8}}>
                                            <Input.Group>
                                                <Col span="6">
                                                    <Input placeholder="标题"
                                                        {...getFieldProps(item.key + '.title', {
                                                            initialValue: item.title
                                                        })}
                                                    />
                                                </Col>
                                                <Col span="10">
                                                    <Input type="textarea" placeholder="内容" autosize
                                                        {...getFieldProps(item.key + '.content', {
                                                            initialValue: item.content
                                                        })}
                                                    />
                                                </Col>
                                                <Col span="4">
                                                    <Icon type="cross" title="删除"
                                                          onClick={this.handleRemoveElement.bind(this, index)}/>
                                                </Col>
                                            </Input.Group>
                                        </div>
                                    )
                                }
                            </Form.Item>
                            :
                            this.state.elements.length ?
                                <Form.Item>

                                    <table className="data-grid" style={{maxWidth:600}}>
                                        <colgroup>
                                            <col width="150px"/>
                                            <col />
                                        </colgroup>
                                        <thead>
                                        <tr>
                                            <th>元素标题</th>
                                            <th>元素内容</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        {
                                            this.state.elements.map(item=>
                                                item.title && item.content &&
                                                <tr key={item.key}>
                                                    <th>{item.title}</th>
                                                    <td {...innerHTML(item.content, true)}/>
                                                </tr>
                                            )
                                        }
                                        </tbody>
                                    </table>
                                </Form.Item>
                                :
                                <Form.Item {...footerFormSubmitLayout}>
                                    还没有设置过任何基本要素
                                </Form.Item>

                    }
                    <Form.Item {...footerFormSubmitLayout} style={{marginTop:30}}>
                        {
                            isEdit ?
                                <span>
                                    <Button size="large" onClick={this.handleAddElement.bind(this)}
                                            style={{marginRight:'1em'}}>
                                        <Icon type="plus"/>添加
                                    </Button>
                                    <Button size="large" type="primary" htmlType="submit" loading={loading}>
                                        <Icon type="save"/>保存
                                    </Button>
                                </span>
                                :
                                <Button type="primary" onClick={e=>{
                                            e.preventDefault();
                                            this.props.dispatch({
                                                type:'UPDATE_PRODUCT'
                                            });
                                        }}>
                                    <Icon type="edit"/>编辑
                                </Button>
                        }
                        {
                            !this.props.isCreate &&
                            <Button onClick={e=>{
                                            e.preventDefault();
                                            isEdit ?
                                                this.props.dispatch({
                                                    type: 'CANCEL_UPDATE_PRODUCT'
                                                }) :
                                                this.props.history.goBack();
                                        }}
                                    style={{marginLeft:'1em'}}>
                                <Icon type="rollback"/>
                                {isEdit ? '取消' : '返回'}
                            </Button>
                        }
                    </Form.Item>

                </Form>
            </Spin>
        );
    }
}
