import React from 'react';
import { Input, Button, Form, Select, Radio, Upload, Icon, Spin, message, Modal } from 'antd';
import './person.less';
import { addressInit, splitUrl, getBase64, beforeUpload } from '../../tools.js';
import ajax from 'jquery/src/ajax/xhr.js'
import $ from 'jquery/src/ajax';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;

class Avatar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            imageUrl: '',
            propsbool: true,
        }
    }
    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);
        }
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps.picUrl && this.state.propsbool) {
            this.state.imageUrl = globalConfig.avatarHost + "/upload" + nextProps.picUrl;
            this.state.propsbool = false;
        }
    }
    render() {
        const imageUrl = this.state.imageUrl;
        return (
            <Upload
                className="avatar-uploader"
                name="avatar"
                showUploadList={false}
                action={globalConfig.context + "/api/user/avatar/uploadReplace"}
                data={{ 'sign': this.props.name }}
                beforeUpload={beforeUpload}
                onChange={this.handleChange.bind(this)}
            >
                {
                    imageUrl ?
                        <img src={imageUrl} role="presentation" className="avatar" /> :
                        <Icon type="plus" className="avatar-uploader-trigger" />
                }
            </Upload>
        );
    }
};

class PicturesWall extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            previewVisible: false,
            propsbool: true,
            previewImage: '',
            fileList: [],
        }
    }
    handleCancel() {
        this.setState({ previewVisible: false })
    }
    handlePreview(file) {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }

    handleChange(info) {
        let fileList = info.fileList;
        this.setState({ fileList });
        this.props.fileList(fileList);
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps.lifePhotoList && this.state.propsbool) {
            this.state.fileList = nextProps.lifePhotoList;
            this.state.propsbool = false;
        }
    }
    render() {
        const { previewVisible, previewImage, fileList } = this.state;
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        return (
            <div className="clearfix">
                <Upload
                    action={globalConfig.context + "/api/user/avatar/upload"}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange.bind(this)}
                >
                    {fileList.length >= 9 ? null : uploadButton}
                </Upload>
                <Modal maskClosable={false} visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
};

const PersonFrom = Form.create()(React.createClass({
    getData() {
        this.props.spinState(true);
        $.ajax({
            method: "get",
            dataType: "json",
            url: globalConfig.context + "/api/user/member",
            success: function (data) {
                if (data.data) {
                    addressInit('cmbProvince', 'cmbCity', 'cmbArea',
                        data.data.residenceProvince, data.data.residenceCity, data.data.residenceArea);
                    let theArr = splitUrl(data.data.lifePhotoUrl, ',', globalConfig.avatarHost + '/upload');
                    this.setState({
                        id: data.data.id,
                        nickname: data.data.nickname,
                        cmbP: data.data.residenceProvince,
                        cmbC: data.data.residenceCity,
                        cmbA: data.data.residenceArea,
                        intro: data.data.personalProfile,
                        email: data.data.email,
                        fixTelArea: data.data.fixedTelArea,
                        fixTel: data.data.fixedTel,
                        fixTelExtension: data.data.fixedTelExtension,
                        qq: data.data.qq,
                        personPortraitUrl: data.data.personPortraitUrl,
                        address: data.data.postalAddress,
                        postcode: data.data.postcode,
                        lifePhotoList: theArr
                    });
                }
            }.bind(this),
        }).always(function () {
            this.props.spinState(false);
        }.bind(this));
    },
    getInitialState() {
        return {
            loading: false,
            livePicUrlArr: []
        };
    },
    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;
            //lifePhotoUrl
            let livePicArr = [];

            this.state.lifePhotoList.map(function (item) {
                livePicArr.push(item.response.data);
            });
            let lifePhotoUrl = livePicArr.join(",");

            if (!err) {
                this.props.spinState(true);
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/user/userInfo",
                    data: {
                        "id": this.state.id,
                        "nickname": values.nickname,
                        "residenceProvince": cmbP,
                        "residenceCity": cmbC,
                        "residenceArea": cmbA,
                        "personPortraitUrl": this.state.avatarUrlData,
                        "lifePhotoUrl": lifePhotoUrl,
                        "personalProfile": values.intro,
                        "email": values.email,
                        "fixedTelArea": this.state.fixTelArea,
                        "fixedTel": this.state.fixTel,
                        "fixedTelExtension": this.state.fixTelExtension,
                        "qq": values.qq,
                        "postalAddress": values.address,
                        "postcode": values.postcode
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('保存成功！');
                        this.getData();
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this)).always(function () {
                    this.props.spinState(false);
                }.bind(this));
            }
        });
    },
    avatarUrl(e) {
        this.state.avatarUrlData = e;
    },
    livePicFileList(e) {
        this.state.lifePhotoList = e;
    },
    componentDidMount() {
        addressInit('cmbProvince', 'cmbCity', 'cmbArea');
        this.getData();
    },
    fixTelAreaChange(e) {
        this.setState({
            fixTelArea: e.target.value
        });
    },
    fixTelChange(e) {
        this.setState({
            fixTel: e.target.value
        });
    },
    fixTelExtensionChange(e) {
        this.setState({
            fixTelExtension: e.target.value
        });
    },
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 3 },
            wrapperCol: { span: 12 },
        };
        const _me = this;
        return (
            <Form horizontal onSubmit={this.handleSubmit} className="person-form">
                <FormItem
                    {...formItemLayout}
                    label="社区昵称"
                >
                    {getFieldDecorator('nickname', {
                        initialValue: this.state.nickname || null
                    })(
                        <Input />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="居住地"
                >
                    {getFieldDecorator('province', {
                        initialValue: this.state.cmbA || null
                    })(
                        <div>
                            <select id="cmbProvince" name="cmbProvince"></select>
                            <select id="cmbCity" name="cmbCity"></select>
                            <select id="cmbArea" name="cmbArea"></select>
                        </div>
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="个人头像"
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 21 }}
                >
                    {getFieldDecorator('avatar')(
                        <Avatar urlData={this.avatarUrl} name='personPortrait' picUrl={this.state.personPortraitUrl} />
                    )}
                </FormItem>
                <div className="set-explain">
                    <p>请上传清晰的个人身份证正反面原件照片/扫描件 （不能截图、图片内容要求完整 ），</p>
                    <p>要求2M 以下的jpg、jpeg格式的图片。该资料不会公开展示，仅作为审核材料使用。</p>
                </div>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 21 }}
                    label="生活照"
                >
                    {getFieldDecorator('livePic')(
                        <PicturesWall fileList={this.livePicFileList} lifePhotoList={this.state.lifePhotoList} />
                    )}
                </FormItem>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 20 }}
                    label="个人简介"
                >
                    {getFieldDecorator('intro', {
                        initialValue: this.state.intro || null
                    })(
                        <Input type="textarea"
                            placeholder="全面介绍自己，让商友更深入了解您，内容长度不超过1000个字。"
                            rows={6} />
                        )}
                    <p>还可输入{
                        (() => {
                            if (_me.props.form.getFieldValue('intro') && _me.props.form.getFieldValue('intro').length) {
                                return 1000 - _me.props.form.getFieldValue('intro').length;
                            } else {
                                return 1000;
                            }
                        })()
                    }字/1000</p>
                </FormItem>

                <FormItem
                    {...formItemLayout}
                    label="电子邮箱"
                    hasFeedback
                >
                    {getFieldDecorator('email', {
                        rules: [{
                            type: 'email', message: '请输入正确的邮箱地址!',
                        }],
                        initialValue: this.state.email || null
                    })(
                        <Input />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="固定电话"
                >
                    {getFieldDecorator('telephone')(
                        <p>
                            <Input value={this.state.fixTelArea} id="fixTelArea" onChange={this.fixTelAreaChange} /> - <Input value={this.state.fixTel} id="fixTel" onChange={this.fixTelChange} /> - <Input value={this.state.fixTelExtension} id="fixTelExtension" onChange={this.fixTelExtensionChange} />
                        </p>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="QQ"
                >
                    {getFieldDecorator('qq', {
                        initialValue: this.state.qq || null
                    })(
                        <Input />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="通讯地址"
                >
                    {getFieldDecorator('address', {
                        initialValue: this.state.address || null
                    })(
                        <Input />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="邮编"
                >
                    {getFieldDecorator('postcode', {
                        initialValue: this.state.postcode || null
                    })(
                        <Input />
                        )}
                </FormItem>
                <FormItem wrapperCol={{ span: 12, offset: 3 }}>
                    <Button className="set-submit" type="primary" htmlType="submit">保存</Button>
                </FormItem>
            </Form >
        );
    },
}));

const Person = 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-person">
                    <div className="acc-detail">
                        <p className="acc-title">个人资料</p>
                        <PersonFrom spinState={this.spinChange} />
                    </div>
                </div>
            </Spin>
        )
    }
});

export default Person;