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);
        }
    }
    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 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()
                    if (data.data.dateOfBirthMonth && data.data.dateOfBirthYear) {
                        d.setMonth(data.data.dateOfBirthMonth - 1);
                        d.setYear(parseInt(data.data.dateOfBirthYear));
                    };
                    this.setState({
                        id: data.data.id || null,
                        username: data.data.username,
                        sex: data.data.sex,
                        birth: d,
                        idnumber: data.data.idNumber,
                        oppositeIdUrl: data.data.oppositeIdUrl,
                        positiveIdUrl: data.data.positiveIdUrl,
                        auditStatus: data.data.auditStatus
                    })
                };
            }.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: {
                        "id": this.state.id,
                        "username": values.username,
                        "sex": values.sex,
                        "dateOfBirthYear": values.birth ? values.birth._d.getFullYear() : undefined,
                        "dateOfBirthMonth": values.birth ? values.birth._d.getMonth() + 1 : undefined,
                        "idNumber": values.idcardnum,
                        "positiveIdUrl": this.state.positiveIdUrl,
                        "oppositeIdUrl": this.state.positiveIdUrl
                    }
                }).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.oppositeIdUrl = e;
    },
    urlData2(e) {
        this.state.positiveIdUrl = 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
                    })(
                        this.state.auditStatus == 5 ? <span>{this.state.username}</span> : <Input />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="性别"
                >
                    {getFieldDecorator('sex', {
                        initialValue: this.state.sex || null
                    })(
                        <RadioGroup>
                            <Radio value="男">男</Radio>
                            <Radio value="女">女</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
                    })(
                        this.state.auditStatus == 5 ? <span>{this.state.idnumber}</span> : <Input />
                        )}
                </FormItem>
                <FormItem wrapperCol={{ span: 12, offset: 4 }}>
                    {this.state.auditStatus == 5 ? <span></span> : <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>
                        <p>认证状态： <span>{userData.lvl == '1' ? <span>已认证</span> : <span>未认证 <a href={globalConfig.context + '/user/certify'}> 马上认证</a></span>}</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;


// <FormItem wrapperCol={{ span: 21, offset: 4 }}>
//     <p>请上传清晰的个人身份证正反面原件照片/扫描件 （不能截图、图片内容要求完整 ），</p>
//     <p>要求2M 以下的jpg、jpeg、gif、png格式的图片。该资料不会公开展示，仅作为审核材料使用。</p>
// </FormItem>
//     <FormItem
//         {...formItemLayout}
//         label="身份证正面"
//     >
//         {getFieldDecorator('oppositeIdUrl')(
//             <Avatar name="oppositeIdUrl" urlData={this.urlData1} />
//         )}
//         <p>{
//             this.state.oppositeIdUrl !== "" && this.state.oppositeIdUrl !== undefined && this.state.oppositeIdUrl !== 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" /><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />未上传</span>
//         }
//         </p>
//     </FormItem>
//     <FormItem
//         {...formItemLayout}
//         label="身份证反面"
//     >
//         {getFieldDecorator('positiveIdUrl')(
//             <Avatar name="positiveIdUrl" urlData={this.urlData2} />
//         )}
//         <p>{
//             this.state.positiveIdUrl !== "" && this.state.positiveIdUrl !== undefined && this.state.positiveIdUrl !== 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" /><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />未上传</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>