import React from 'react';
import { Input, Button, Form, Upload, Icon, Spin, message, Row, Col, Cascader } from 'antd';
import './certify.less';
import { getBase64, beforeUpload } from '../tools.js';
import { areaSelect } from '../NewDicProvinceList'
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) {
                    this.setState({
                        positiveIdUrl: data.data.positiveIdUrl,
                        oppositeIdUrl: data.data.oppositeIdUrl,
                        address: [data.data.province, data.data.city, data.data.area],
                        aftUsername: data.data.aftUsername,
                        username: data.data.username,
                        idNumber: data.data.idNumber,
                        contactMobile: data.data.contactMobile
                    });
                };
            }.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: ''
        };
    },
    handleSubmit(e) {
        this.reloadVCode();
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!this.state.positiveIdUrl || !this.state.oppositeIdUrl) {
                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.positiveIdUrl,
                        oppositeIdUrl: this.state.oppositeIdUrl,
                        province: values.address[0],
                        city: values.address[1],
                        area: values.address[2],
                        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);
                        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.positiveIdUrl = e;
    },
    getIdCardUrl2(e) {
        this.state.oppositeIdUrl = 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: 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
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 18 }}
                        label="所在地"
                    >
                        {getFieldDecorator('address', {
                            initialValue: this.state.address || null,
                            rules: [{ type: 'array', required: true, message: '请选择地址!' }]
                        })(
                            <Cascader options={areaSelect()} placeholder="请选择" />
                            )}
                    </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="身份证正面">
                        <Avatar name="idcard1" urlData={this.getIdCardUrl1} />
                    </FormItem>
                    <FormItem
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 18 }}
                        label="身份证反面">
                        <Avatar name="idcard2" urlData={this.getIdCardUrl2} />
                    </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={this.state.vsCodeSrc} 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" onClick={() => {
                            window.location.href = globalConfig.context + '/user/account/index.html'
                        }}>退出实名认证</Button>
                    </FormItem>
                </Form >
            </Spin >
        );
    },
}));

export default Content;