import React from 'react';
import { Icon, Modal, Button, Form, Upload, message, Input, Spin, Select } from 'antd';
import { beforeUploadFile, downloadFile, setUserContactsList } from '../../tools.js';
import './patent.less';
import ajax from 'jquery/src/ajax/xhr.js'
import $ from 'jquery/src/ajax';

const PatentAddFrom = Form.create()(React.createClass({
    getInitialState() {
        return {
            loading: false
        };
    },
    componentWillMount() {
        this.state.contactsOption = setUserContactsList();
    },
    handleSubmit(e) {
        e.preventDefault();
        if (!this.state.patentProryStatementUrl) {
            message.warning('未上传代理委托书!');
            return;
        };
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.spinState(true);
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/user/patent/clientApplyPatent",
                    data: {
                        'firstInventorIdNumber': values.firstInventorID,
                        'firstInventorName': values.firstInventorName,
                        'patentDes': values.intro,
                        'patentName': values.patentName,
                        'contacts': values.contacts,
                        'secondInventorName': values.secondInventorName,
                        'thirdInventorName': values.thirdInventorName,
                        'patentProryStatementUrl': this.state.patentProryStatementUrl
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('保存成功!');
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this)).always(function () {
                    this.props.spinState(false);
                    this.props.clickOk();
                    this.props.form.resetFields();
                }.bind(this));
            }
        });
    },
    avatarUrl(e) {
        this.state.avatarUrl = e;
    },
    checkIdcardnum(rule, value, callback) {
        if (!/(^\d{15}$)|(^\d{17}(\d|X)$)/.test(value)) {
            callback('请输入正确的身份证号!');
        } else {
            callback();
        }
    },
    render() {
        const FormItem = Form.Item;
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 3 },
            wrapperCol: { span: 16 },
        };
        const _me = this;
        return (
            <Form horizontal onSubmit={this.handleSubmit} className="patent-form">
                <FormItem
                    {...formItemLayout}
                    label="专利名称"
                >
                    {getFieldDecorator('patentName', {
                        rules: [{ required: true, message: '请输入姓名!' }]
                    })(
                        <Input placeholder="请输入专利名称" style={{ width: 200 }} />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="选择联系人"
                >
                    {getFieldDecorator('contacts', {
                        rules: [{ required: true, message: '请选择一个联系人!' }]
                    })(
                        <Select placeholder="请选择联系人" style={{ width: 200 }}
                            notFoundContent="未获取到联系人列表"
                            onSelect={(e, n) => { this.setState({ contacts: e }); }}>
                            {this.state.contactsOption}
                        </Select>
                        )}
                </FormItem>
                <FormItem
                    labelCol={{ span: 24 }}
                    wrapperCol={{ span: 24 }}
                    label="专利简要描述"
                >
                    {getFieldDecorator('intro', {
                        initialValue: this.state.intro || null
                    })(
                        <Input type="textarea"
                            placeholder="多行输入"
                            rows={6} />
                        )}
                </FormItem>
                <p>第一发明人</p>
                <FormItem
                    {...formItemLayout}
                    label="姓名"
                >
                    {getFieldDecorator('firstInventorName', {
                        rules: [{ required: true, message: '请输入姓名!' }]
                    })(
                        <Input className="mini-input" />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="身份证"
                >
                    {getFieldDecorator('firstInventorID', {
                        rules: [{ required: true, validator: this.checkIdcardnum, message: '请输入正确的身份证号!' }]
                    })(
                        <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>
                <div className="hrSituation-roster">
                    <Upload
                        name="ratepay"
                        action={globalConfig.context + "/api/user/patent/upload"}
                        data={{ 'sign': 'patent_prory_statement' }}
                        beforeUpload={beforeUploadFile}
                        fileList={this.state.fileList}
                        onChange={(info) => {
                            if (info.file.status !== 'uploading') {
                                console.log(info.file, info.fileList);
                            }
                            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;
                                };
                                this.state.patentProryStatementUrl = info.file.response.data;
                            } else if (info.file.status === 'error') {
                                message.error(`${info.file.name} 文件上传失败。`);
                            };
                            this.setState({ fileList: info.fileList.slice(-1) });
                        }}
                    >
                        <Button><Icon type="upload" /> 上传专利代理委托书 </Button>
                    </Upload>
                    <p style={{ paddingLeft: '10px', marginTop: '10px' }}>
                        <a onClick={() => { window.open(globalConfig.context + "/api/user/patent/downloadTemplateFile?sign=patent_prory_statement") }}>专利代理委托书模板下载</a>
                    </p>
                </div>
                <FormItem style={{ marginTop: '20px' }}>
                    <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,
        });
        this.props.closeDesc(false, true);
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    spinChange(e) {
        this.setState({
            loading: e
        });
    },
    render() {
        return (
            <div className="patent-addNew">
                <Button disabled={this.props.ButtonDisabled} className="patent-addNew" type="primary" onClick={this.showModal}>申请新专利<Icon type="plus" /></Button>
                <Spin spinning={this.state.loading} className='spin-box'>
                    <Modal title="新专利申请" visible={this.state.visible}
                        onOk={this.handleOk} onCancel={this.handleCancel}
                        width='720px'
                        footer=''
                    >
                        <PatentAddFrom spinState={this.spinChange} closeModal={this.handleCancel} clickOk={this.handleOk} />
                    </Modal>
                </Spin>
            </div>
        );
    },
});
export default PatentAdd;