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

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>
        );
    }
};

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) {
                    this.setState({
                        firstContacts: data.data.firstContacts,
                        firstMobile: data.data.firstMobile,
                        aftUsername: data.data.aftUsername,
                        unitName: data.data.unitName,
                        registeredCapital: data.data.registeredCapital,
                        licenceNumber: data.data.licenceNumber,
                        address: [data.data.licenceProvince, data.data.licenceCity, data.data.licenceArea],
                        orgCode: data.data.orgCode,
                        legalPerson: data.data.legalPerson,
                        legalPersonIdCard: data.data.legalPersonIdCard,
                        licenceScanningUrl: data.data.licenceScanningUrl,
                        orgCodeUrl: data.data.orgCodeUrl,
                        lastYearTaxReportUrl: data.data.lastYearTaxReportUrl,
                        listed: data.data.listed,
                        listedDate: data.data.listedDateFormattedDate,
                        listedType: data.data.listedType,
                        stockCode: data.data.stockCode,
                        auditStatus: data.data.auditStatus
                    });
                };
            }.bind(this),
        }).done(function (data) {
            if (data.error.length) {
                message.warning(data.error[0].message);
            }
        }.bind(this)).always(function () {
            this.setState({
                loading: false
            });
            this.reloadVCode();
        }.bind(this));
    },
    getInitialState() {
        return {
            loading: false,
            vsCodeSrc: globalConfig.context + '/open/getVCode'
        };
    },
    handleSubmit(e) {
        this.reloadVCode();
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            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
                });
                if (values.listed == 1) {
                    if (!values.listedDate || !values.listedType || !values.stockCode) {
                        message.warning("请输入上市资料！");
                        return;
                    };
                };
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/user/orgNextPro",
                    data: {
                        firstContacts: values.firstContacts,
                        firstMobile: values.firstMobile,
                        aftUsername: values.aftUsername,
                        unitName: values.unitName,
                        registeredCapital: values.registeredCapital,
                        licenceNumber: values.licenceNumber,
                        licenceProvince: values.address[0],
                        licenceCity: values.address[1],
                        licenceArea: values.address[2],
                        licenceScanningUrl: this.state.licenceScanningUrl,
                        orgCode: values.orgCode,
                        orgCodeUrl: this.state.orgCodeUrl,
                        lastYearTaxReportUrl: this.state.lastYearTaxReportUrl,
                        legalPerson: values.legalPerson,
                        legalPersonIdCard: values.legalPersonIdCard,
                        verificationCode: values.captcha,
                        listed: values.listed,
                        listedDateFormattedDate: values.listedDate ? values.listedDate.format("YYYY-MM-DD") : null,
                        listedType: values.listedType,
                        stockCode: values.stockCode,
                        auditStatus: this.state.auditStatus,
                        process: 1
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('保存成功！');
                        this.props.changeStep(2);
                    } else {
                        message.warning(data.error[0].message);
                        this.reloadVCode();
                        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 (!/(^[a-zA-Z0-9]{0,18}$)/.test(value)) {
            callback('请输入正确的营业执照注册号！');
        } else {
            callback();
        }
    },
    getLicenceScanningUrl(e) {
        this.state.licenceScanningUrl = e;
    },
    getOrgCodeUrl(e) {
        this.state.orgCodeUrl = e;
    },
    getLastYearTaxReportUrl(e) {
        this.state.lastYearTaxReportUrl = e;
    },
    componentWillMount() {
        this.getData();
    },
    reloadVCode() {
        this.setState({
            vsCodeSrc: 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
                    })(
                        <Input />
                        )}
                        <span className="fromItem-postfix">万元</span>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="是否上市"
                    >   {getFieldDecorator('listed', {
                        initialValue: this.state.listed || "0"
                    })(
                        <Radio.Group>
                            <Radio value="0">否</Radio>
                            <Radio value="1">是</Radio>
                        </Radio.Group>
                        )}
                    </FormItem>
                    <FormItem style={{ display: this.props.form.getFieldValue('listed') == 0 ? 'none' : 'block' }}
                        {...formItemLayout}
                        label="上市时间"
                    >
                        {getFieldDecorator('listedDate', {
                            initialValue: this.state.listedDate ? moment(this.state.listedDate) : null
                        })(
                            <DatePicker />
                            )}
                    </FormItem>
                    <FormItem style={{ display: this.props.form.getFieldValue('listed') == 0 ? 'none' : 'block' }}
                        {...formItemLayout}
                        label="上市类型"
                    >   {getFieldDecorator('listedType', {
                        initialValue: this.state.listedType
                    })(
                        <Select placeholder="请选择上市类型">
                            <Select.Option value='0'>股票型上市公司</Select.Option>
                            <Select.Option value='1'>债券型上市公司</Select.Option>
                        </Select>
                        )}
                    </FormItem>
                    <FormItem style={{ display: this.props.form.getFieldValue('listed') == 0 ? 'none' : 'block' }}
                        {...formItemLayout}
                        label="股票代码"
                    >   {getFieldDecorator('stockCode', {
                        initialValue: this.state.stockCode
                    })(
                        <Input />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="联系人"
                    >
                        {getFieldDecorator('firstContacts', {
                            initialValue: this.state.firstContacts || null,
                            rules: [{ required: true, message: '请输入联系人姓名!' }]
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="联系方式"
                        extra={<span><Icon type="exclamation-circle" /> 请填写联系人手机号码，我们会将重要进度以短信形式通知您</span>}
                    >
                        {getFieldDecorator('firstMobile', {
                            initialValue: this.state.firstMobile || null,
                            rules: [{ validator: this.checkPhone }]
                        })(
                            <Input placeholder="建议使用常用手机" />
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="法人姓名"
                    >
                        {getFieldDecorator('legalPerson', {
                            initialValue: this.state.legalPerson || null,
                            rules: [{ required: true, message: '请输入联系人姓名!' }]
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="身份证号"
                    >
                        {getFieldDecorator('legalPersonIdCard', {
                            rules: [{
                                validator: this.checkIdcardnum,
                            }],
                            initialValue: this.state.legalPersonIdCard || null
                        })(
                            <Input placeholder="请输入真实有效的身份证号码" />
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="营业执照注册号"
                    >
                        {getFieldDecorator('licenceNumber', {
                            initialValue: this.state.licenceNumber || null,
                            rules: [{
                                validator: this.checkNumber,
                            }],
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        label="营业执照所在地"
                    >
                        {getFieldDecorator('address', {
                            initialValue: this.state.address || null,
                            rules: [{ type: 'array', required: true, message: '请选择地址!' }]
                        })(
                            <Cascader options={provinceSelect()} placeholder="请选择地址" />
                            )}
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        label="营业执照副本扫描件"
                    >
                        {getFieldDecorator('licenceScanningUrl')(
                            <Avatar name="licence" 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="orgCode" 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="上年度纳税报表"
                    >
                        <div className="hrSituation-roster">
                            <Upload
                                name="ratepay"
                                action={globalConfig.context + "/api/user/cognizance/uploadLastYearRatepay"}
                                data={{ 'sign': 'ratepay' }}
                                beforeUpload={beforeUploadFile}
                                showUploadList={false}
                                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.lastYearTaxReportUrl = info.file.response.data;
                                    } else if (info.file.status === 'error') {
                                        message.error(`${info.file.name} 文件上传失败。`);
                                    }
                                }}
                            >
                                <Button><Icon type="upload" /> 上传上年度纳税申报表 </Button>
                            </Upload>
                        </div>
                    </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={this.state.vsCodeSrc} 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;