import React from 'react';
import { Input, Button, Form, Select, Upload, Icon, Spin, message, InputNumber } from 'antd';
import './person.less';
import ajax from 'jquery/src/ajax/xhr.js'
import $ from 'jquery/src/ajax';

import { addressInit } from '../../tools.js';


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 }));
        }
    }

    render() {
        const imageUrl = this.state.imageUrl;
        return (
            <Upload
                className="avatar-uploader"
                name="avatar"
                showUploadList={false}
                action="/upload.do"
                beforeUpload={beforeUpload}
                onChange={this.handleChange}
                >
                {
                    imageUrl ?
                        <img src={imageUrl} role="presentation" className="avatar" /> :
                        <Icon type="plus" className="avatar-uploader-trigger" />
                }
            </Upload>
        );
    }
};

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);

                    this.setState({
                        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,
                        address: data.data.postalAddress,
                        postcode: data.data.postcode,
                    });
                }

                //"personPortraitUrl": "/avadar/4303502988139.jpg",
                //"lifePhotoUrl": "/avadar/4303502988131.jpg",
            }.bind(this),
        }).always(function () {
            this.props.spinState(false);
        }.bind(this));
    },
    getInitialState() {
        return {
            loading: false,

            idttType: '企业',

            companyDis: 'block',
            schoolDis: 'none',
            resDis: 'none',

            aca: 0,
            PhDTutor: 0,
            MSTutor: 0,
            otherExperts: 0,
            StateKeyLab: 0,
            EduKeyLab: 0,
            ComCenter: 0,
            otherCenter: 0
        };
    },
    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 (!err) {
                this.props.spinState(true);
                 
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/user/userInfo",
                    data: {
                        "info.identityType": this.state.idttType,
                        "info.companyName": values.unitName,
                        "info.locationProvince": cmbP,
                        "info.locationCity": cmbC,
                        "info.locationArea": cmbA,
                        "info.unitSize": values.unitNumber,
                        "info.companyIntroduction": values.unitIntro,
                        "info.homeUnit": values.unitFrom,
                        //"info.logoUrl": "logo图",
                        //"info.publicityPictureUrl": "宣传图片",
                        "pro.qualification": values.qiyezizhi,
                        "pro.turnover": values.turnover,
                        "pro.collegeAttribute": values.schoolProp,
                        "pro.collegeEstablishTime": values.schoolTime,
                        "pro.academician": this.state.aca,
                        "pro.doctoralTutor": this.state.PhDTutor,
                        "pro.masterTutor": this.state.MSTutor,
                        "pro.otherExpert": this.state.otherExperts,
                        "pro.nationalLab": this.state.StateKeyLab,
                        "pro.educationLab": this.state.EduKeyLab,
                        "pro.enterpriseCenter": this.state.ComCenter,
                        "pro.otherCenter": this.state.otherCenter,
                        "pro.institutionEstablishTime": this.state.resTime
                    }
                }).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));
            }
        });
    },
    idttTypeChange(e) {
        if (e === '企业') {
            this.props.form.setFieldsValue({ 'indentityType': e });
            this.setState({
                companyDis: 'block',
                schoolDis: 'none',
                resDis: 'none'
            });
        } else if (e === '院校') {
            this.props.form.setFieldsValue({ 'indentityType': e });
            this.setState({
                companyDis: 'none',
                schoolDis: 'block',
                resDis: 'none'
            });
        } else if (e === '研究机构') {
            this.props.form.setFieldsValue({ 'indentityType': e });
            this.setState({
                companyDis: 'none',
                schoolDis: 'none',
                resDis: 'block'
            });
        } else {
            this.props.form.setFieldsValue({ 'indentityType': e });
            this.setState({
                companyDis: 'none',
                schoolDis: 'none',
                resDis: 'none'
            });
        }
    },
    componentDidMount() {
        addressInit('cmbProvince', 'cmbCity', 'cmbArea');
        this.getData();
    },
    render() {
        const FormItem = Form.Item;
        const Option = Select.Option;

        const edulvlArr = ["企业", "院校", "研究机构", "政府部门", "非法人团体"];
        const zizhiArr = ["高新技术型企业", "创新型企业", "双软企业", "小心微利企业", "科技部认定示范企业", "其他"];
        const schoolArr = ["普通本科院校", "高职专科院校", "独立学院", "中央部署院校", "地方所属院校", "211工程院校", "985工程院校"];

        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
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 8 }}
                    label="身份类型"
                    >
                    {getFieldDecorator('indentityType', {
                        initialValue: this.state.idttType
                    })(
                        <Select className="acc-edu-lvl" onChange={this.idttTypeChange}>
                            {
                                edulvlArr.map(function (item, i) {
                                    return <Option key={i} value={item} >{item}</Option>
                                })
                            }
                        </Select>
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="单位名称"
                    >
                    {getFieldDecorator('unitName', {
                        initialValue: this.props.unitName
                    })(
                        <Input />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="所在地"
                    >
                    {getFieldDecorator('province')(
                        <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('unitNumber', {
                        initialValue: this.props.unitNumber
                    })(
                        <InputNumber />
                        )}
                    <span>人</span>
                </FormItem>

                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 20 }}
                    label="单位简介"
                    >
                    {getFieldDecorator('unitIntro', {
                        initialValue: this.props.unitIntro
                    })(
                        <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="归属单位"
                    >
                    {getFieldDecorator('unitFrom', {
                        initialValue: this.state.unitFrom
                    })(
                        <Input placeholder="非法人单位填写。" />
                        )}
                </FormItem>
                <FormItem style={{ 'display': this.state.companyDis }}
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 8 }}
                    label="企业资质"
                    >
                    {getFieldDecorator('qiyezizhi', {
                        initialValue: this.state.qiyezizhi
                    })(
                        <Select className="acc-edu-lvl">
                            {
                                zizhiArr.map(function (item, i) {
                                    return <Option key={i} value={item} >{item}</Option>
                                })
                            }
                        </Select>
                        )}
                </FormItem>
                <FormItem style={{ 'display': this.state.companyDis }}
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 6 }}
                    label="年营业额"
                    >
                    {getFieldDecorator('turnover', {
                        initialValue: this.state.turnover
                    })(
                        <InputNumber />
                        )}
                    <span>万元</span>
                </FormItem>
                <FormItem style={{ 'display': this.state.schoolDis }}
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 8 }}
                    label="院校属性"
                    >
                    {getFieldDecorator('schoolProp', {
                        initialValue: this.state.schoolProp
                    })(
                        <Select className="acc-edu-lvl">
                            {
                                schoolArr.map(function (item, i) {
                                    return <Option key={i} value={item} >{item}</Option>
                                })
                            }
                        </Select>
                        )}
                </FormItem>
                <FormItem style={{ 'display': this.state.schoolDis }}
                    {...formItemLayout}
                    label="创办时间"
                    >
                    {getFieldDecorator('schoolTime', {
                        initialValue: this.state.schoolTime
                    })(
                        <InputNumber />
                        )}
                </FormItem>
                <FormItem style={{ 'display': this.state.schoolDis }}
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 20 }}
                    label=""
                    >
                    <div>
                        <span>院士：<InputNumber value={this.state.aca} onChange={function (e) { this.setState({ aca: e }) }.bind(this)} />人</span>
                        <span>博士生导师：<InputNumber value={this.state.PhDTutor} onChange={function (e) { this.setState({ PhDTutor: e }) }.bind(this)} />人</span>
                        <span>硕士生导师：<InputNumber value={this.state.MSTutor} onChange={function (e) { this.setState({ MSTutor: e }) }.bind(this)} />人</span>
                        <span>其他专家：<InputNumber value={this.state.otherExperts} onChange={function (e) { this.setState({ otherExperts: e }) }.bind(this)} />人</span>
                        <span>国家级重点实验室：<InputNumber value={this.state.StateKeyLab} onChange={function (e) { this.setState({ StateKeyLab: e }) }.bind(this)} />所</span>
                        <span>教育部重点实验室：<InputNumber value={this.state.EduKeyLab} onChange={function (e) { this.setState({ EduKeyLab: e }) }.bind(this)} />所</span>
                        <span>企业共建研究中心：<InputNumber value={this.state.ComCenter} onChange={function (e) { this.setState({ ComCenter: e }) }.bind(this)} />所</span>
                        <span>其他研究中心：<InputNumber value={this.state.otherCenter} onChange={function (e) { this.setState({ otherCenter: e }) }.bind(this)} />所</span>
                    </div>
                </FormItem>
                <FormItem style={{ 'display': this.state.resDis }}
                    {...formItemLayout}
                    label="创办时间"
                    >
                    {getFieldDecorator('resTime', {
                        initialValue: this.state.resTime
                    })(
                        <InputNumber />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="LOGO"
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 20 }}
                    hasFeedback
                    >
                    {getFieldDecorator('avatar')(
                        <Avatar />
                    )}
                </FormItem>
                <div className="set-explain">
                    <p>上传的照片图片格式应为jpg格式，大小在2M以内</p>
                </div>
                <FormItem
                    {...formItemLayout}
                    label="宣传图片"
                    >
                    {getFieldDecorator('companyimg', {
                        valuePropName: 'fileList',
                        normalize: this.normFile,
                    })(
                        <Upload
                            name="companyimg"
                            action="/upload.do"
                            listType="picture"
                            beforeUpload={beforeUpload}
                            onChange={this.handleUpload}>
                            <Button type="primary">
                                <Icon type="upload" /> 点击选择文件
                            </Button>
                            <p>上传的照片图片格式应为jpg格式，大小在2M以内</p>
                        </Upload>
                        )}
                </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;