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

import YearSelect from '../../yearSelect.jsx';
import { getBase64, beforeUpload } from '../../tools.js';
import { jingli_yuanxiao, jingli_shehui, chengjiu_yuanxiao, chengjiu_shehui } from '../../dataDic.js';
import { techFieldList } from '../../DicTechFieldList';


const FormItem = Form.Item;
const RadioButton = Radio.Button;
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>
        );
    }
};

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({
                        id: data.data.id,
                        field: data.data.engagedField ? data.data.engagedField.split(',') : [],
                        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,
            zigePicUrl: '',
            zhichengPicUrl: ''
        };
    },
    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: {
                        "id": this.state.id,
                        "engagedField": values.field ? values.field.join(',') : '',
                        "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.touxian,
                        "experiences": values.jingli,
                        "achievement": values.chengjiu
                    }
                }).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));
            }
        });
    },
    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': this.state.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': this.state.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 className="half-item"
                    {...formItemLayout}
                    label="从事领域" >
                    {getFieldDecorator('field', {
                        initialValue: this.state.field
                    })(
                        <Cascader placeholder="请选择一个领域" options={techFieldList} />
                        )}
                </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} picUrl={this.state.zhichengPicUrl} />
                    )}
                </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} picUrl={this.state.zigePicUrl} />
                    )}
                </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;