import React from 'react';
import { Input, Button, Form, Upload, Icon, Spin, message, Row, Col } from 'antd';
import './certify.less';
import { addressInit, getBase64, beforeUpload, beforeUploadFile } from '../tools.js';
import ajax from 'jquery/src/ajax/xhr.js'
import $ from 'jquery/src/ajax';

import card1 from '../../../image/idcard1.jpg';
import card2 from '../../../image/idcard2.jpg';

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={this.props.name}
                showUploadList={false}
                action={globalConfig.context + "/api/user/identity/upload"}
                data={{ 'sign': this.props.name }}
                beforeUpload={beforeUpload}
                onChange={this.handleChange.bind(this)}
            >
                {
                    imageUrl ?
                        <img src={imageUrl} role="presentation" id={this.props.name} /> :
                        <Icon type="plus" className="avatar-uploader-trigger" />
                }
            </Upload>
        );
    }
};
class UploadFile extends React.Component {
    constructor(props) {
        super(props);
    }

    handleChange(info) {
        if (info.file.status === 'done') {
            this.props.urlData(info.file.response.data);
        }
    }
    render() {
        return (
            <Upload
                name={this.props.name}
                showUploadList={false}
                action={globalConfig.context + "/api/user/identity/upload"}
                data={{ 'sign': this.props.name }}
                beforeUpload={beforeUploadFile}
                onChange={this.handleChange.bind(this)}
            >
                <Button><Icon type="upload" />上传</Button>
            </Upload>
        );
    }
};

const Content = Form.create()(React.createClass({
    getData() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            url: globalConfig.context + "/api/user/orgProcess",
            success: function (data) {
                if (data.data) {
                    addressInit('cmbProvince', 'cmbCity', 'cmbArea',
                        data.data.licenceProvince, data.data.licenceCity, data.data.licenceArea);
                    this.setState({
                        contactMobile: data.data.contactMobile,
                        aftUsername: data.data.aft,
                        unitName: data.data.unitName,
                        registeredCapital: data.data.registeredCapital,
                        licenceNumber: data.data.licenceNumber,
                        orgCode: data.data.orgCode,
                        legalPerson:data.data.legalPerson,
                        legalPersonIdNumber:data.data.legalPersonIdNumber
                    });
                } else {
                    message.warning(data.error[0].message);
                };
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            loading: false
        };
    },
    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            //地址值
            let cmbP = document.getElementById('cmbProvince').value;
            let cmbC = document.getElementById('cmbCity').value;
            let cmbA = document.getElementById('cmbArea').value;
            if (cmbP || cmbC || cmbA) {
                message.warning("请选择所在地！");
                return;
            };
            if (this.state.licenceScanningUrl) {
                message.warning("请上传营业执照副本！");
                return;
            };
            if (this.state.orgCodeUrl) {
                message.warning("请上传组织机构代码证！");
                return;
            };
            if (this.state.lastYearTaxReportUrl) {
                message.warning("请上传上年度纳税报表！");
                return;
            };
            if (!err) {
                this.setState({
                    loading: true
                });
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/user/orgNextPro",
                    data: {
                        contacts:values.contacts,
                        contactMobile: values.contactMobile,
                        aftUsername: values.aft,
                        unitName: values.unitName,
                        registeredCapital: values.registeredCapital,
                        licenceNumber: values.licenceNumber,
                        licenceProvince: cmbP,
                        licenceCity: cmbC,
                        licenceArea: cmbA,
                        licenceScanningUrl: this.state.licenceScanningUrl,
                        orgCode: values.orgCode,
                        orgCodeUrl: this.state.orgCodeUrl,
                        lastYearTaxReportUrl: this.state.lastYearTaxReportUrl,
                        legalPerson:values.legalPerson,
                        legalPersonIdNumber:values.legalPersonIdNumber,
                        captcha:values.captcha,
                        process: 1
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('保存成功！');
                        this.props.changeStep(2);
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this)).always(function () {
                    this.setState({
                        loading: false
                    });
                }.bind(this));
            }
        });
    },
    checkIdcardnum(rule, value, callback) {
        if (!/(^\d{15}$)|(^\d{17}(\d|X)$)/.test(value)) {
            callback('请输入正确的身份证号！');
        } else {
            callback();
        }
    },
    checkPhone(rule, value, callback) {
        const form = this.props.form;
        const _me = this;
        if (!(/^1[34578]\d{9}$/.test(value))) {
            callback('请输入正确的手机号码！');
            _me.setState({
                getCodeButton: true
            });
        } else {
            callback();
            _me.setState({
                getCodeButton: false
            });
        }
    },
    checkNumber(rule, value, callback) {
        if (!/(^\d{15}$)/.test(value)) {
            callback('请输入正确的营业执照注册号！');
        } else {
            callback();
        }
    },
    getLicenceScanningUrl(e) {
        this.state.licenceScanningUrl = e;
    },
    getOrgCodeUrl(e) {
        this.state.orgCodeUrl = e;
    },
    getLastYearTaxReportUrl(e) {
        this.state.lastYearTaxReportUrl = e;
    },
    componentDidMount() {
        addressInit('cmbProvince', 'cmbCity', 'cmbArea');
        this.getData();
    },
    reloadVCode(e) {
        e.target.src = globalConfig.context + '/open/getVCode?t=' + Math.random();
    },
    render() {
        const FormItem = Form.Item;
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 12 },
        };
        const _me = this;
        return (
            <Spin spinning={this.state.loading} className="certify-spin">
                <Form horizontal onSubmit={this.handleSubmit} className="certify-form">
                    <FormItem
                        {...formItemLayout}
                        label="用户名"
                        extra={<span><Icon type="exclamation-circle" /> 建议字母、数字和符号两种以上组合，6-20个字符</span>}
                    >
                        {getFieldDecorator('aftUsername', {
                            initialValue: this.state.aftUsername || null,
                            rules: [{ required: true, message: '请输入用户名!' }]
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="企业名称"
                    >
                        {getFieldDecorator('unitName', {
                            initialValue: this.state.unitName || null,
                            rules: [{ required: true, message: '请输入企业名称!' }]
                        })(
                            <Input placeholder="请输入企业名称" />
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="注册资金"
                    >
                        {getFieldDecorator('registeredCapital', {
                            initialValue: this.state.registeredCapital || null,
                            rules: [{ required: true, message: '请输入注册资金!' }]
                        })(
                            <Input />
                            )}
                        <span className="fromItem-postfix">万元</span>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="联系人"
                    >
                        {getFieldDecorator('contacts', {
                            initialValue: this.state.contacts || null,
                            rules: [{ required: true, message: '请输入联系人姓名!' }]
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="联系方式"
                        extra={<span><Icon type="exclamation-circle" /> 请填写联系人手机号码，我们会将重要进度以短信形式通知您</span>}
                    >
                        {getFieldDecorator('contactMobile', {
                            initialValue: this.state.contactMobile || null,
                            rules: [{ validator: this.checkPhone }]
                        })(
                            <Input placeholder="建议使用常用手机" />
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="法人姓名"
                    >
                        {getFieldDecorator('contacts', {
                            initialValue: this.state.contacts || null,
                            rules: [{ required: true, message: '请输入联系人姓名!' }]
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="身份证号"
                    >
                        {getFieldDecorator('idNumber', {
                            rules: [{
                                validator: this.checkIdcardnum,
                            }],
                            initialValue: this.state.idNumber || null
                        })(
                            <Input placeholder="请输入真实有效的身份证号码" />
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="营业执照注册号"
                    >
                        {getFieldDecorator('licenceNumber', {
                            initialValue: this.state.licenceNumber || null,
                            rules: [{
                                validator: this.checkNumber,
                            }],
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="营业执照所在地"
                    >
                        {getFieldDecorator('address')(
                            <div>
                                <select id="cmbProvince" name="cmbProvince"></select>
                                <select id="cmbCity" name="cmbCity"></select>
                                <select id="cmbArea" name="cmbArea"></select>
                            </div>
                        )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        label="营业执照副本扫描件"
                    >
                        {getFieldDecorator('licenceScanningUrl')(
                            <Avatar name="licenceScanningUrl" urlData={this.getLicenceScanningUrl} />
                        )}
                    </FormItem>
                    <FormItem wrapperCol={{ span: 21, offset: 6 }}>
                        <p>1.企业营业执照副本复印件加盖企业公章后，扫描或拍照上传，图片大小不超过2M以内，仅支持jpg格式。</p>
                        <p>2.若已办理三证合一，请输入统一社会信用代码并上传营业执照副本复印件（加盖企业公章）。</p>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="组织机构代码证号码"
                        extra={<span><Icon type="exclamation-circle" /> 如机构已五证合一，社会统一注册号的第九位至倒数第二位，即为您单位的组织机构代码证号码。</span>}
                    >
                        {getFieldDecorator('orgCode', {
                            initialValue: this.state.orgCode || null,
                            rules: [{ required: true, message: '请输入组织机构代码证号码!' }]
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        label="组织机构代码证扫描件"
                    >
                        {getFieldDecorator('orgCodeUrl')(
                            <Avatar name="orgCodeUrl" urlData={this.getOrgCodeUrl} />
                        )}
                    </FormItem>
                    <FormItem wrapperCol={{ span: 21, offset: 6 }}>
                        <p>1.组织机构代码证副本复印件加盖企业公章后，扫描或拍照上传，图片大小不超过2M以内，仅支持jpg格式。</p>
                        <p>2.若已办理三证合一，请输入统一社会信用代码并上传营业执照副本复印件（加盖企业公章）。</p>
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        label="上年度纳税报表"
                    >
                        {getFieldDecorator('lastYearTaxReportUrl')(
                            <UploadFile name="lastYearTaxReportUrl" urlData={this.getLastYearTaxReportUrl} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="验证码"
                        extra={<span style={{ 'color': '#ea0862' }}><Icon type="exclamation-circle" /> 看不清？点击图片更换验证码</span>}
                    >
                        <Row gutter={8}>
                            <Col span={16}>
                                {getFieldDecorator('captcha', {
                                    rules: [{ required: true, message: '请输入图片中的验证码' }],
                                })(
                                    <Input />
                                    )}
                            </Col>
                            <Col span={8}>
                                <div className="getVcode">
                                    <img id="VCode" src={globalConfig.context + '/open/getVCode'} alt="" onClick={this.reloadVCode} />
                                </div>
                            </Col>
                        </Row>
                    </FormItem>
                    <FormItem wrapperCol={{ span: 12, offset: 6 }}>
                        <Button className="set-submit" type="primary" htmlType="submit">下一步</Button>
                        <Button className="exit" type="ghost">退出实名认证</Button>
                    </FormItem>
                </Form >
            </Spin >
        );
    },
}));

export default Content;