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

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};

function beforeUpload(file) {
    const isJPG = file.type === 'image/jpeg';
    if (!isJPG) {
        message.error('You can only upload JPG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJPG && isLt2M;
};

class Avatar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            imageUrl: ''
        }
    }
    handleChange(info) {
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, imageUrl => this.setState({ imageUrl }));
            this.props.urlData(info.file.response.data);
        }
    }
    render() {
        const imageUrl = this.state.imageUrl;
        return (
            <Upload
                className="avatar-uploader"
                name="avatar"
                showUploadList={false}
                action={globalConfig.context + "/techservice/patent/patentFile"}
                data={{ 'sign': this.props.name }}
                beforeUpload={beforeUpload}
                onChange={this.handleChange.bind(this)}
            >
                {
                    imageUrl ?
                        <img src={imageUrl} role="presentation" className="avatar" /> :
                        <Icon type="plus" className="avatar-uploader-trigger" />
                }
            </Upload>
        );
    }
};

const PatentAddFrom = Form.create()(React.createClass({
    getInitialState() {
        return {
            loading: false,
            firstCheck: 0,
            secondCheck: 0,
            thirdCheck: 0

        };
    },
    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 + "/techservice/patent/clientApplyPatent",
                    data: {
                        'firstInventorIdNumber': values.firstInventorID,
                        'firstInventorName': values.firstInventorName,
                        'patentDes': values.intro,
                        'secondInventorName': values.secondInventorName,
                        'thirdInventorName': values.thirdInventorName,
                        'firstInventorIsPublish': this.state.firstCheck,
                        'secondInventorIsPublish': this.state.secondCheck,
                        'thirdInventorIsPublish': this.state.thirdCheck,
                        'patentProryStatementUrl': this.state.avatarUrl
                    }
                }).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.closeModal();
                    this.props.form.resetFields();
                }.bind(this));
            }
        });
    },
    firstInventorCheck(e) {
        if (e.target.checked == true) {
            this.state.firstCheck = 1;
        } else if (e.target.checked == false) {
            this.state.firstCheck = 0;
        }
    },
    secondInventorCheck(e) {
        if (e.target.checked == true) {
            this.state.secondCheck = 1;
        } else if (e.target.checked == false) {
            this.state.secondCheck = 0;
        };
    },
    thirdInventorCheck(e) {
        if (e.target.checked == true) {
            this.state.thirdCheck = 1;
        } else if (e.target.checked == false) {
            this.state.thirdCheck = 0;
        };
    },
    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="person-form">
                <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: 'Please input name!' }]
                    })(
                        <Input className="mini-input" />
                        )}
                    <Checkbox onChange={this.firstInventorCheck}>是否同意专利局公布</Checkbox>
                </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" />
                    )}
                    <Checkbox onChange={this.secondInventorCheck}>是否同意专利局公布</Checkbox>
                </FormItem>
                <p>第三发明人</p>
                <FormItem
                    {...formItemLayout}
                    label="姓名"
                >
                    {getFieldDecorator('thirdInventorName')(
                        <Input className="mini-input" />
                    )}
                    <Checkbox onChange={this.thirdInventorCheck}>是否同意专利局公布</Checkbox>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="上传代理委托书"
                    labelCol={{ span: 24 }}
                    wrapperCol={{ span: 12 }}
                >
                    {getFieldDecorator('avatar')(
                        <Avatar urlData={this.avatarUrl} name='patent_prory_statement' />
                    )}
                    <span>请上传专利代理委托书</span><a onClick={() => { window.open(globalConfig.context + "/techservice/patent/downloadTemplate") }}>模板下载</a>
                </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,
        });
        this.props.closeDesc(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>
                <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} />
                    </Modal>
                </Spin>
            </div>
        );
    },
});
export default PatentAdd;