import React from 'react';
import { Input, Button, Form, Upload, Icon, Spin, message, Row, Col } from 'antd';
import './certify.less';
import { addressInit, getBase64, beforeUpload } 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>
        );
    }
};


const Content = Form.create()(React.createClass({
    getData() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            url: globalConfig.context + "/api/user/userPro",
            success: function (data) {
                if (data.data) {
                    addressInit('cmbProvince', 'cmbCity', 'cmbArea',
                        data.data.province, data.data.city, data.data.area);
                    this.setState({
                        aftUsername: data.data.aftUsername,
                        username: data.data.username,
                        idNumber: data.data.idNumber,
                        contactMobile: data.data.contactMobile
                    });
                } 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.idCardUrl1 || this.state.idCardUrl2) {
                message.warning("请上传身份证！");
                return;
            };
            if (!err) {
                this.setState({
                    loading: true
                });
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/user/userNextPro",
                    data: {
                        verificationCode: values.captcha,
                        aftUsername: values.aftUsername,
                        username: values.username,
                        idNumber: values.idNumber,
                        positiveIdUrl: this.state.idCardUrl1,
                        oppositeIdUrl: this.state.idCardUrl2,
                        province: cmbP,
                        city: cmbC,
                        area: cmbA,
                        contactMobile: values.contactMobile,
                        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));
            }
        });
    },
    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
            });
        }
    },
    checkIdcardnum(rule, value, callback) {
        if (!/(^\d{15}$)|(^\d{17}(\d|X)$)/.test(value)) {
            callback('请输入正确的身份证号！');
        } else {
            callback();
        }
    },
    getIdCardUrl1(e) {
        this.state.idCardUrl1 = e;
    },
    getIdCardUrl2(e) {
        this.state.idCardUrl2 = 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: 4 },
            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('username', {
                            initialValue: this.state.username || null,
                            rules: [{ required: true, message: '请输入真实姓名!' }]
                        })(
                            <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
                        {...formItemLayout}
                        label="身份证号"
                    >
                        {getFieldDecorator('idNumber', {
                            rules: [{
                                validator: this.checkIdcardnum,
                            }],
                            initialValue: this.state.idNumber || null
                        })(
                            <Input placeholder="请输入真实有效的身份证号码" />
                            )}
                    </FormItem>
                    <FormItem wrapperCol={{ span: 21, offset: 4 }}>
                        <p>请上传清晰的个人身份证正反面原件照片/扫描件 （不能截图、图片内容要求完整 ），</p>
                        <p>要求2M 以下的jpg、jpeg、gif、png格式的图片。该资料不会公开展示，仅作为审核材料使用。</p>
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 18 }}
                        label="身份证图片"
                    >
                        {getFieldDecorator('idcard')(
                            <div>
                                <Avatar name="idcard1" urlData={this.getIdCardUrl1} />
                                <Avatar name="idcard2" urlData={this.getIdCardUrl2} />
                            </div>
                        )}
                    </FormItem>
                    <FormItem wrapperCol={{ span: 18, offset: 4 }}>
                        <span className="idCard-text">上传身份证正面</span>
                        <span className="idCard-text">上传身份证反面</span>
                    </FormItem>
                    <FormItem wrapperCol={{ span: 21, offset: 4 }}>
                        <p className="acc-title">示例</p>
                        <div className="idcard-img clearfix">
                            <div>
                                <div className="idcard-imgbox">
                                    <img src={card1} alt="" />
                                </div>
                            </div>
                            <div>
                                <div className="idcard-imgbox">
                                    <img src={card2} alt="" />
                                </div>
                            </div>
                        </div>
                    </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="验证码"
                        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: 4 }}>
                        <Button className="set-submit" type="primary" htmlType="submit">下一步</Button>
                        <Button className="exit" type="ghost">退出实名认证</Button>
                    </FormItem>
                </Form >
            </Spin >
        );
    },
}));

export default Content;