import React from 'react';
import { Icon, Modal, Button, Form, Upload, message, Input, Spin, Select } from 'antd';
import './comprehensive.less';
import ajax from 'jquery/src/ajax/xhr.js'
import $ from 'jquery/src/ajax';
import { getBase64, beforeUpload, companySearch } from '../../../tools.js';

class Avatar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            imageUrl: ''
        }
    }
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            this.state.fileList = [];
        };
    }
    handleChange(info) {
        if (!this.props.oid || this.props.oid === "") {
            message.warning('请先选择公司！');
            return;
        };
        if (info.file.status === 'done') {
            if (!info.file.response.error.length) {
                message.success(`${info.file.name} 文件上传成功！`);
            } else {
                message.warning(info.file.response.error[0].message);
                return;
            };
            getBase64(info.file.originFileObj, imageUrl => this.setState({ imageUrl }));
            this.props.urlData(info.file.response.data);
        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} 文件上传失败。`);
        };
        this.setState({ fileList: info.fileList.slice(-1) });
    }
    render() {
        return (
            <Upload
                className="avatar-uploader"
                name="avatar"
                fileList={this.state.fileList}
                action={globalConfig.context + "/api/admin/patent/uploadProry"}
                data={{ 'sign': this.props.name, 'uid': this.props.oid }}
                beforeUpload={beforeUpload}
                onChange={this.handleChange.bind(this)}
            >
                <Button><Icon type="upload" />上传专利代理委托书</Button>
            </Upload>
        );
    }
};

const PatentAddFrom = Form.create()(React.createClass({
    getCompanyList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/getUnitNames",
            success: function (data) {
                if (data.error.length || !data.data) {
                    return;
                };
                let _me = this;
                for (var item in data.data) {
                    _me.state.companyOption.push(
                        <Select.Option value={item} key={item}>{data.data[item]}</Select.Option>
                    )
                };
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getSalesmanList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/salesman",
            success: function (data) {
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    }
                    return;
                };
                let _me = this, theArr = [];
                for (var item in data.data) {
                    theArr.push(
                        <Select.Option value={item} key={item}>{data.data[item]}</Select.Option>
                    )
                };
                this.setState({
                    salesmanOption: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getContactsList(theUid) {
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/getContacts",
            data: {
                uid: theUid || this.state.uid
            },
            success: function (data) {
                let theOption = [];
                if (data.error.length || !data.data) {
                    return;
                };
                for (let item in data.data) {
                    let theData = data.data[item];
                    theOption.push(
                        <Select.Option value={item} key={theData}>{theData}</Select.Option>
                    );
                };
                this.setState({
                    contactsOption: theOption
                });
            }.bind(this),
        });
    },
    getInitialState() {
        return {
            loading: false,
            companyOption: []
            //            firstCheck: 0,
            //            secondCheck: 0,
            //            thirdCheck: 0

        };
    },
    componentWillMount() {
        this.getCompanyList();
        this.getSalesmanList();
    },
    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.spinState(true);
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/admin/patent/apply",
                    data: {
                        'uid': values.companyName,
                        'contacts': values.contacts,
                        'firstInventorIdNumber': values.firstInventorID,
                        'firstInventorName': values.firstInventorName,
                        'patentDes': values.intro,
                        'secondInventorName': values.secondInventorName,
                        'office': values.office,
                        'thirdInventorName': values.thirdInventorName,
                        'patentProryStatementUrl': this.state.avatarUrl,
                        'salesman': values.salesman
                    }
                }).done(function (data) {
                    if (data.error && !data.error.length) {
                        message.success('保存成功！');
                        this.props.okClick();
                        this.props.closeModal();
                        this.props.form.resetFields();
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this)).always(function () {
                    this.props.spinState(false);
                }.bind(this));
            }
        });
    },
    avatarUrl(e) {
        this.state.avatarUrl = e;
    },
    render() {
        const FormItem = Form.Item;
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 18 },
        };
        const _me = this;
        return (
            <Form horizontal onSubmit={this.handleSubmit} className="person-form">
                <FormItem
                    {...formItemLayout}
                    label="申请公司"
                >
                    {getFieldDecorator('companyName', {
                        rules: [{ required: true, message: '请选择一个公司!' }],
                        initialValue: this.state.companyName || null

                    })(
                        <Select placeholder="选择公司"
                            showSearch
                            filterOption={companySearch}
                            onChange={(e) => { this.setState({ companyName: e }); this.getContactsList(e); }}
                            showSearch={true} style={{ width: 260 }} >
                            {this.state.companyOption}
                        </Select>
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="联系人"
                >
                    {getFieldDecorator('contacts', {
                        rules: [{ required: true, message: '请选择一个联系人!' }],
                        initialValue: this.state.contacts || null
                    })(
                        <Select placeholder="选择联系人"
                            style={{ width: 260 }} >
                            {this.state.contactsOption}
                        </Select>
                        )}
                </FormItem>
                <FormItem
                    labelCol={{ span: 24 }}
                    wrapperCol={{ span: 18 }}
                    label="专利简要描述"
                >
                    {getFieldDecorator('intro', {
                        initialValue: this.state.intro || null
                    })(
                        <Input type="textarea"
                            placeholder="多行输入"
                            rows={6} />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="事务所"
                >
                    {getFieldDecorator('office')(
                        <Input className="mini-input" />
                    )}
                </FormItem>
                <p>第一发明人</p>
                <FormItem
                    {...formItemLayout}
                    label="姓名"
                >
                    {getFieldDecorator('firstInventorName')(
                        <Input className="mini-input" />
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="身份证"
                >
                    {getFieldDecorator('firstInventorID')(
                        <Input className="mini-input" />
                    )}
                </FormItem>
                <p>第二发明人</p>
                <FormItem
                    {...formItemLayout}
                    label="姓名"
                >
                    {getFieldDecorator('secondInventorName')(
                        <Input className="mini-input" />
                    )}
                </FormItem>
                <p>第三发明人</p>
                <FormItem
                    {...formItemLayout}
                    label="姓名"
                >
                    {getFieldDecorator('thirdInventorName')(
                        <Input className="mini-input" />
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="上传代理委托书"
                    labelCol={{ span: 24 }}
                    wrapperCol={{ span: 12 }}
                >
                    {getFieldDecorator('avatar')(
                        <Avatar
                            urlData={this.avatarUrl}
                            name='patent_prory_statement'
                            oid={this.state.companyName}
                            visible={this.props.visible} />
                    )}
                    <p>
                        <a onClick={() => { window.open(globalConfig.context + "/api/admin/patent/downloadTemplateFile?sign=patent_prory_statement") }}>模板下载</a>
                    </p>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="营销员"
                >
                    {getFieldDecorator('salesman', {
                        rules: [{ required: true, message: '请选择一个营销员!' }],
                        initialValue: this.state.salesman || null
                    })(
                        <Select placeholder="选择营销员"
                            style={{ width: 260 }} >
                            {this.state.salesmanOption}
                        </Select>
                        )}
                </FormItem>
                <FormItem>
                    <Button className="set-submit" type="primary" htmlType="submit">保存</Button>
                    <Button type="ghost" style={{ marginLeft: '20px' }} onClick={this.props.closeModal}>取消</Button>
                </FormItem>
            </Form >
        );
    },
}));


const PatentAdd = React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false
        };
    },
    showModal() {
        this.setState({
            visible: true,
        });
    },
    handleOk() {
        this.setState({
            visible: false,
        });
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    spinChange(e) {
        this.setState({
            loading: e
        });
    },
    render() {
        return (
            <div className="patent-addNew">
                <Button className="patent-addNew" type="primary" onClick={this.showModal}>申请新专利<Icon type="plus" /></Button>
                <Modal maskClosable={false} title="新专利申请" visible={this.state.visible}
                    onOk={this.handleOk} onCancel={this.handleCancel}
                    width='800px'
                    footer='' >
                    <Spin spinning={this.state.loading} className='spin-box'>
                        <PatentAddFrom
                            visible={this.state.visible}
                            spinState={this.spinChange}
                            closeModal={this.handleCancel}
                            okClick={() => { this.props.closeDesc(false, true) }} />
                    </Spin>
                </Modal>
            </div>
        );
    },
});
export default PatentAdd;

//                    <Checkbox onChange={this.firstInventorCheck}>告知专利局是否公布</Checkbox>