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

import YearSelect from '../../yearSelect.jsx';
import { jingli_yuanxiao, jingli_shehui, chengjiu_yuanxiao, chengjiu_shehui } from '../../tools.js';

const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;

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 PfsFrom = Form.create()(React.createClass({
    getData() {
        this.props.spinState(true);
        $.ajax({
            method: "get",
            dataType: "json",
            url: globalConfig.context + "/api/user/job",
            success: function (data) {
                if (data.data) {
                    this.setState({
                        lingyu: data.data.engagedField,
                        gongling: data.data.workingAge,
                        zhichengname: data.data.professionalTitle,
                        zhichengyear: data.data.professionalTitleGettime,
                        zhichengPicUrl: data.data.professionalCertificateUrl,
                        zigename: data.data.qualification,
                        zigeyear: data.data.qualificationGettime,
                        zigePicUrl: data.data.qualificationCertificateUrl,
                        danwei: data.data.workUnit,
                        touxian: data.data.position,
                        jingli: data.data.experiences,
                        chengjiu: data.data.achievement
                    });
                };
            }.bind(this),
        }).always(function () {
            this.props.spinState(false);
        }.bind(this));
    },
    getInitialState() {
        return {
            loading: false,
        };
    },
    componentWillMount() {
        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/userCareer",
                    data: {
                        "engagedField": values.lingyu,
                        "workingAge": values.gongling,
                        "professionalTitle": values.zhichengname,
                        "professionalTitleGettime": this.state.zhichengyear,
                        "professionalCertificateUrl": this.state.zhichengPicUrl,
                        "qualification": values.zigename,
                        "qualificationGettime": this.state.zigeyear,
                        "qualificationCertificateUrl": this.state.zigePicUrl,
                        "workUnit": values.danwei,
                        "position": values.touxia,
                        "experiences": values.jingli,
                        "achievement": values.chengjiu
                    }
                }).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));
            }
        });
    },
    zhichengPic(e) {
        this.state.zhichengPicUrl = e;
    },
    zhichengyear(e) {
        this.state.zhichengyear = e;
    },
    zigePic(e) {
        this.state.zigePicUrl = e;
    },
    zigeyear(e) {
        this.state.zigeyear = e;
    },
    jingliChange(e) {
        if (e.target.value == "a") {
            this.props.form.setFieldsValue({ 'jingli': "" })
        } else if (e.target.value == "b") {
            this.props.form.setFieldsValue({
                'jingli': jingli_yuanxiao
            })
        } else if (e.target.value == "c") {
            this.props.form.setFieldsValue({
                'jingli': jingli_shehui
            })
        }
    },
    chengjiuChange(e) {
        if (e.target.value == "a") {
            this.props.form.setFieldsValue({ 'chengjiu': "" })
        } else if (e.target.value == "b") {
            this.props.form.setFieldsValue({
                'chengjiu': chengjiu_yuanxiao
            })
        } else if (e.target.value == "c") {
            this.props.form.setFieldsValue({
                'chengjiu': chengjiu_shehui
            })
        }
    },
    downloadPic(type) {
        window.open(globalConfig.context + "/open/downLoadPicture?path="+type)
    },
    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 3 },
            wrapperCol: { span: 12 },
        };
        const _me = this;
        return (
            <Form horizontal onSubmit={this.handleSubmit} className="pfs-form">
                <FormItem
                    {...formItemLayout}
                    label="从事领域"
                    help={'请输入所从事领域的名称，多个领域请以逗号隔开'}
                    >
                    {getFieldDecorator('lingyu', {
                        initialValue: this.state.lingyu || null
                    })(
                        <Input />
                        )}
                </FormItem>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 4 }}
                    label="从业工龄"
                    >
                    {getFieldDecorator('gongling', {
                        initialValue: this.state.gongling
                    })(
                        <InputNumber />
                        )}
                    <span>年</span>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="职称名字"
                    >
                    {getFieldDecorator('zhichengname', {
                        initialValue: this.state.zhichengname || null
                    })(
                        <Input />
                        )}
                </FormItem>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 6 }}
                    label="取得时间"
                    hasFeedback
                    >
                    {getFieldDecorator('zhichengyear')(
                        <YearSelect defValue={this.state.zhichengyear} handleyear={this.zhichengyear} />
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="职称证书"
                    hasFeedback
                    >
                    {getFieldDecorator('zhichengPic')(
                        <Avatar name="zhichengPic" urlData={this.zhichengPic} />
                    )}
                </FormItem>
                <div className="set-explain">
                    <p>要求2M 以下的jpg、jpeg格式的图片。该资料不会公开展示，仅作为审核材料使用。</p>
                    <p>{this.state.zhichengPicUrl !== "" ? <Button onClick={this.downloadPic.bind(this,this.state.zhichengPicUrl)}>下载证书</Button> : ""}</p>
                </div>
                <FormItem
                    {...formItemLayout}
                    label="执业资格"
                    >
                    {getFieldDecorator('zigename', {
                        initialValue: this.state.zigename
                    })(
                        <Input />
                        )}
                </FormItem>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 6 }}
                    label="取得时间"
                    hasFeedback
                    >
                    {getFieldDecorator('zigeyear')(
                        <YearSelect defValue={this.state.zigeyear} handleyear={this.zigeyear} />
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="资格证明"
                    hasFeedback
                    >
                    {getFieldDecorator('zigePic')(
                        <Avatar name="zigePic" urlData={this.zigePic} />
                    )}
                </FormItem>
                <div className="set-explain">
                    <p>要求2M 以下的jpg、jpeg格式的图片。该资料不会公开展示，仅作为审核材料使用。</p>
                    <p>{this.state.zigePicUrl !== "" ? <Button onClick={this.downloadPic.bind(this,this.state.zigePicUrl)}>下载证书</Button> : ""}</p>
                </div>
                <FormItem
                    {...formItemLayout}
                    label="工作单位"
                    >
                    {getFieldDecorator('danwei', {
                        initialValue: this.state.danwei || null
                    })(
                        <Input />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="职位头衔"
                    >
                    {getFieldDecorator('touxian', {
                        initialValue: this.state.touxian || null
                    })(
                        <Input />
                        )}
                </FormItem>
                <div className="textarea-title">
                    <span>从业经历</span>
                    <RadioGroup className="set-radio-button" onChange={this.jingliChange} defaultValue="a">
                        <RadioButton value="a">自定义</RadioButton>
                        <RadioButton value="b">院校专家模板</RadioButton>
                        <RadioButton value="c">企业或社会专家模板</RadioButton>
                    </RadioGroup>
                </div>
                <div className="set-explain">
                    <p>您可使用模板直接编辑调整!</p>
                </div>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 20, offset: 3 }}
                    help={
                        <div>
                            <p>还可输入{
                                (() => {
                                    if (_me.props.form.getFieldValue('jingli') && _me.props.form.getFieldValue('jingli').length) {
                                        return 1000 - _me.props.form.getFieldValue('jingli').length;
                                    } else {
                                        return 1000;
                                    }
                                })()
                            }字/1000</p>
                            <p>描述您主要的从业履历，包括职业，最有亮点的社会兼职。可自定义或选择模板后直接编辑</p>
                        </div>
                    }
                    label=""
                    >
                    {getFieldDecorator('jingli', {
                        initialValue: this.state.jingli || null
                    })(
                        <Input type="textarea"
                            rows={6} />
                        )}
                </FormItem>
                <div className="textarea-title">
                    <span>从业经历</span>
                    <RadioGroup className="set-radio-button" onChange={this.chengjiuChange} defaultValue="a">
                        <RadioButton value="a">自定义</RadioButton>
                        <RadioButton value="b">院校专家模板</RadioButton>
                        <RadioButton value="c">企业或社会专家模板</RadioButton>
                    </RadioGroup>
                </div>
                <div className="set-explain">
                    <p>您可使用模板直接编辑调整!</p>
                </div>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 20, offset: 3 }}
                    help={
                        <div>
                            <p>还可输入{
                                (() => {
                                    if (_me.props.form.getFieldValue('chengjiu') && _me.props.form.getFieldValue('chengjiu').length) {
                                        return 1000 - _me.props.form.getFieldValue('chengjiu').length;
                                    } else {
                                        return 1000;
                                    }
                                })()
                            }字/1000</p>
                            <p>描述您主要的从业履历，包括职业，最有亮点的社会兼职。可自定义或选择模板后直接编辑</p>
                        </div>
                    }
                    label=""
                    >
                    {getFieldDecorator('chengjiu', {
                        initialValue: this.state.chengjiu || null
                    })(
                        <Input type="textarea"
                            rows={6} />
                        )}
                </FormItem>
                <FormItem wrapperCol={{ span: 12, offset: 3 }}>
                    <Button className="set-submit" type="primary" htmlType="submit">保存</Button>
                </FormItem>
            </Form >
        );
    },
}));

const Pfs = 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-pfs">
                    <div className="acc-detail">
                        <p className="acc-title">职业信息</p>
                        <PfsFrom spinState={this.spinChange} />
                    </div>
                </div>
            </Spin>
        )
    }
});

export default Pfs;