import React from 'react';
import { Input, Button, Form, Radio, Upload, Icon, DatePicker, Spin, message } from 'antd';
import moment from 'moment';
import './base.less';
import ajax from 'jquery/src/ajax/xhr.js'
import $ from 'jquery/src/ajax';

import ChangePw from './changePassword.jsx';
import ChangeMobile from './changeMobile.jsx';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { MonthPicker, RangePicker } = DatePicker

import weixin from '../../../../image/weixin-w.png';
import qq from '../../../../image/qq-w.png';
import weibo from '../../../../image/weibo-w.png';
import card1 from '../../../../image/idcard1.jpg';
import card2 from '../../../../image/idcard2.jpg';

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);
        }
    }
    theObj() {
        return {
            'sign': this.props.name
        }
    }
    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={this.theObj.bind(this)}
                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 BaseFrom = Form.create()(React.createClass({
    getData() {
        this.props.spinState(true);
        $.ajax({
            method: "get",
            dataType: "json",
            url: globalConfig.context + "/api/user/base",
            success: function (data) {
                if (data.data) {
                    let d = new Date();
                    d.setMonth(data.data.dateOfBirthMonth - 1);
                    d.setYear(parseInt(data.data.dateOfBirthYear));
                    this.setState({
                        username : data.data.username,
                        sex : data.data.sex === '女' ? 'female' : 'male',
                        birth : d,
                        idnumber : data.data.idNumber,
                        idcard1 : data.data.oppositeIdUrl,
                        idcard2 : data.data.positiveIdUrl,
                    })
                };
            }.bind(this),
        }).done(function (data) {
            if (data.error.length) {
                message.warning(data.error[0].message);
            }
        }.bind(this)).always(function () {
            this.props.spinState(false);
        }.bind(this));
    },
    getInitialState() {
        return {
        };
    },
    componentDidMount() {
        this.getData();
    },
    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 + "/api/user/userIndentity",
                    data: {
                        "username": values.username,
                        "sex": values.sex === 'female' ? '女' : '男',
                        "dateOfBirthYear": values.birth ? values.birth._d.getFullYear() : undefined,
                        "dateOfBirthMonth": values.birth ? values.birth._d.getMonth() + 1 : undefined,
                        "idNumber": values.idcardnum,
                        "positiveIdUrl": this.state.idcard1,
                        "oppositeIdUrl": this.state.idcard2
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('保存成功！');
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this)).always(function () {
                    this.props.spinState(false);
                }.bind(this));
            }
        });
    },
    checkIdcardnum(rule, value, callback) {
        if (!/(^\d{15}$)|(^\d{17}(\d|X)$)/.test(value)) {
            callback('请输入正确的身份证号！');
        } else {
            callback();
        }
    },
    urlData1(e) {
        this.state.idcard1 = e;
    },
    urlData2(e) {
        this.state.idcard2 = e;
    },
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 12 },
        };
        return (
            <Form horizontal onSubmit={this.handleSubmit} className="base-form">
                <FormItem
                    {...formItemLayout}
                    label="姓名"
                    >
                    {getFieldDecorator('username', {
                        initialValue: this.state.username || null
                    })(
                        <Input />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="性别"
                    >
                    {getFieldDecorator('sex', {
                        initialValue: this.state.sex || null
                    })(
                        <RadioGroup>
                            <Radio value="male">男</Radio>
                            <Radio value="female">女</Radio>
                        </RadioGroup>
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="出生日期"
                    >
                    {getFieldDecorator('birth', {
                        rules: [{ type: 'object', message: '请选择日期!' }],
                        initialValue: !this.state.birth ? null : moment( this.state.birth , 'YYYY/MM') 
                    })(
                        <MonthPicker />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="身份证号"
                    >
                    {getFieldDecorator('idcardnum', {
                        rules: [{
                            validator: this.checkIdcardnum,
                        }],
                        initialValue: this.state.idnumber || null
                    })(
                        <Input />
                        )}
                </FormItem>
                <FormItem wrapperCol={{ span: 21, offset: 4 }}>
                    <p>请上传清晰的个人身份证正反面原件照片/扫描件 （不能截图、图片内容要求完整 ），</p>
                    <p>要求2M 以下的jpg、jpeg、gif、png格式的图片。该资料不会公开展示，仅作为审核材料使用。</p>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="身份证正面"
                    >
                    {getFieldDecorator('idcard1')(
                        <Avatar name="idcard1" urlData={this.urlData1} />
                    )}
                    <p>{
                        this.state.idcard1 !== "" &&  this.state.idcard1 !== undefined && this.state.idcard1 !== null ?
                            <span><Icon style={{ 'color': '#79b5ff', 'fontSize': '14px', 'margin': '0 6px' }} type="check-circle" />已上传</span> :
                            <span><Icon style={{ 'color': '#fa0', 'fontSize': '14px', 'margin': '0 6px' }} type="exclamation-circle" />未上传</span>
                    }
                    </p>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="身份证反面"
                    >
                    {getFieldDecorator('idcard2')(
                        <Avatar name="idcard2" urlData={this.urlData2} />
                    )}
                    <p>{
                        this.state.idcard2 !== "" &&  this.state.idcard2 !== undefined && this.state.idcard2 !== null ? 
                            <span><Icon style={{ 'color': '#79b5ff', 'fontSize': '14px', 'margin': '0 6px' }} type="check-circle" />已上传</span> :
                            <span><Icon style={{ 'color': '#fa0', 'fontSize': '14px', 'margin': '0 6px' }} type="exclamation-circle" />未上传</span>
                    }
                    </p>
                </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 wrapperCol={{ span: 12, offset: 4 }}>
                    <Button className="set-submit" type="primary" htmlType="submit">保存</Button>
                </FormItem>
            </Form >
        );
    },
}));

const Base = React.createClass({
    getInitialState() {
        return {
            loading: false
        };
    },
    spinChange(e) {
        this.setState({
            loading: e
        });
    },
    render() {
        return (
            <Spin spinning={this.state.loading} className='spin-box'>
                <div className="set-base">
                    <div className="acc-detail">
                        <p className="acc-title">您登录的账号</p>
                        <p>阿凡提号： <span>{userData.number || undefined}</span></p>
                        <p>登录手机号： <span>{userData.mobile || undefined}</span></p>
                        <div className="clearfix">
                            <ChangeMobile />
                            <ChangePw />
                        </div>
                    </div>
                    <div className="acc-bind" style={{ 'display': 'none' }}>
                        <p className="acc-title">绑定账号 <span>绑定后，可使用第三方账号直接登录阿凡提网</span></p>
                        <p>
                            <Button className="relateqq"><img src={qq} alt="" /> QQ账号登录</Button>
                            <Button className="relateweibo"><img src={weibo} alt="" />微博账号登录</Button>
                            <Button className="relateweixin"><img src={weixin} alt="" />微信账号登录</Button>
                        </p>
                    </div>
                    <div className="acc-info">
                        <p className="acc-title">身份信息 <span>提供正确的身份信息，有助于进行身份验证，提升信用形象</span></p>
                        <BaseFrom spinState={this.spinChange} />
                    </div>
                </div>
            </Spin>
        )
    }
});

export default Base;