// 修改账户密码
import React from 'react';
import { Link } from 'react-router-dom'
import {
    Layout, Form, Icon, Input, Button, Row, Col, Modal
} from 'antd';
import '../../assets/css/login.css'
import { $http } from '../../containers/config/https';
import { httpConfig } from '../../containers/config/httpConfig'

import { Aes } from '../../tools/index';


const formItemLayout = {    // label 和input宽度
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
};

class Login extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            visibleCode: 'block',
            disabled: false, //工号框禁用
            contentH: '',  //content高度
            languageCode: 'CN',// 国际化标识
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
        }
    }

    componentDidMount() {
        let { input } = this.userName; // 如果是textArea的话，const { textAreaRef } = this.passWord;
        input.focus();

        this.contentHeight();   // 获取content的高度

        // 修改表单的值
        if (this.props.location.state) {
            const { input } = this.userPhone;
            input.focus();
            this.props.form.setFieldsValue({
                userName: this.props.location.state.userCode ? this.props.location.state.userCode : ''
            });
            this.setState({
                visibleCode: 'none',
                disabled: true, //工号框禁用
            })
        }
        this.CNEN() // 国际化

    }


    //点击切换中英文
    handleLanguage = (languageCode) => {
        this.setState({
            languageCode: languageCode === "CN" ? "EN" : "CN",
        }, () => {
            this.LanCNEN(this.state.languageCode)
        })
    }

    // 国际化
    CNEN = () => {
        var data = {
            params: [{
                "reactCode": ['ChangePassword'],
                "compontName": "ChangePassword",
                "type": "C"
            }]
        }

        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        languageData: res.result.language || {},  // 国际化语言包
                    }, () => {
                        this.LanCNEN(this.state.languageCode)
                    })
                }
            }
        });
    }

    LanCNEN = (code) => {
        let { languageData } = this.state
        this.setState({
            language: languageData[code]
        })
    }



    // 获取content的高度
    contentHeight = (e) => {
        let contenth = parseInt(document.body.clientHeight) - 160;
        this.setState({
            contentH: contenth
        })
    }


    // 验证码
    changeEvent = (e) => {
        if (e.target.value.length > 0) {
            this.setState({
                codeHelp: '',
                codeStatus: ''
            });
        } else {
            this.setState({
                codeHelp: language.ChangePasswordPleaseente && language.ChangePasswordPleaseente.descripts,
                codeStatus: 'error'
            });
        }
    }

    // 密码二次验证
    handlePassword = (rule, val, callback) => {
        if (!val) {
            callback();
        }
        let validateResult = this.props.form.getFieldValue('password1') === this.props.form.getFieldValue('password2')  // 自定义规则
        if (!validateResult) {
            callback(language.ChangePassworderr2 && language.ChangePassworderr2.descripts);
        }
        callback();
    }

    // 修改密码表单提交
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            // if (this.state.visibleCode === 'block' && parseInt(document.getElementById("verificationCode").value.length) < 1) {
            //     this.setState({
            //         codeHelp: language.ChangePasswordPleaseente && language.ChangePasswordPleaseente.descripts,
            //         codeStatus: 'error'
            //     });
            //     return false;
            // }
            if (!err) {
                var data = {
                    "params": [{
                        userID: this.props.location.state ? this.props.location.state.userID : '',
                        userCode: this.props.location.state ? this.props.location.state.userCode : this.props.form.getFieldValue('userName'),
                        identifyCode: document.getElementById("verificationCode").value || '',
                        mobile: this.props.form.getFieldValue('userPhone'),
                        password: Aes.Encrypt(this.props.form.getFieldValue('password2')),
                    }]
                };

                $http.post('urlDeault', this, {
                    code: "1003",
                    data: data,
                    success: function (res) {
                        let errorCode = res.errorCode;
                        if (errorCode === '0') {
                            // message.success(res.errorMessage);
                            let { language } = this.state
                            let secondsToGo = 1;
                            let thisParse = this;
                            const modal = Modal.success({
                                title: language.ChangePasswordPasswordmodified && language.ChangePasswordPasswordmodified.descripts,
                                content: ` ${secondsToGo} ${language.ChangePasswordseconds && language.ChangePasswordseconds.descripts}`,
                                okText: language.ChangePasswordWe && language.ChangePasswordWe.descripts,
                                onOk() {
                                    thisParse.props.history.push({ pathname: "/Login", state: { userCode: thisParse.props.form.getFieldValue('userName') } });
                                },
                            });
                            const timer = setInterval(() => {
                                secondsToGo -= 1;
                                modal.update({
                                    content: ` ${secondsToGo} ${language.ChangePasswordseconds && language.ChangePasswordseconds.descripts}`,
                                });
                            }, 1000);
                            setTimeout(() => {
                                clearInterval(timer);
                                this.props.history.push({ pathname: "/Login", state: { userCode: this.props.form.getFieldValue('userName') } });
                                modal.destroy();
                            }, secondsToGo * 1000);
                        }
                    }
                });
            }
        });
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const {
            Header, Footer, Content,
        } = Layout;
        let { languageCode, language } = this.state;
        return (
            <div>
                <Layout>
                    <Header className="loginHeader">
                        <div className="logoImg"></div>
                        {language.ChangePasswordTitle && language.ChangePasswordTitle.descripts}
                        <Button className='CNENBtn' style={{ width: '100px', margin: '0 auto', float: 'right', marginTop: '22px' }} onClick={() => this.handleLanguage(languageCode)} >{languageCode && languageCode === "CN" || languageCode === "" ? "English" : "简体中文"}</Button>
                    </Header>
                    <Content style={{ height: this.state.contentH }} className="loginContent regContent">
                        <div className="registerBody">
                            <div className="regHeader mB100" style={{ marginBottom: '100px' }}>
                                <div className="regTittle">{language.ChangePasswordForget && language.ChangePasswordForget.descripts}</div>
                                <div className="regBack">
                                    <Link to='/Login'> {language.ChangePasswordReturn && language.ChangePasswordReturn.descripts} {'>>>'} </Link>
                                </div>
                            </div>
                            <div className="registerBox mT30">
                                <Form onSubmit={this.handleSubmit} className="login-form register-form" >
                                    <Row>
                                        <Col span={24}>
                                            <Form.Item label={language.ChangePasswordnumber && language.ChangePasswordnumber.descripts} {...formItemLayout}>
                                                {getFieldDecorator('userName', {
                                                    rules: [{ required: true, message: language.ChangePasswordnumber && language.ChangePasswordnumber.message }],
                                                })(
                                                    <Input size="large" ref={(input) => { this.userName = input; }} prefix={<Icon type="user" />} disabled={this.state.disabled} placeholder={language.ChangePasswordnumber && language.ChangePasswordnumber.message} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={24}>
                                            <Form.Item label={language.ChangePasswordPhone && language.ChangePasswordPhone.descripts} {...formItemLayout}>
                                                {getFieldDecorator('userPhone', {
                                                    rules: [{ required: true, message: language.ChangePasswordPhone && language.ChangePasswordPhone.message }, { pattern: /^1\d{10}$/, message: language.ChangePassworderr1 && language.ChangePassworderr1.descripts }],
                                                })(
                                                    <Input size="large" ref={(input) => { this.userPhone = input; }} prefix={<Icon type="phone" />} placeholder={language.ChangePasswordPhone && language.ChangePasswordPhone.message} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={24}>
                                            <Form.Item label={language.ChangePasswordNewpassword && language.ChangePasswordNewpassword.descripts} {...formItemLayout}>
                                                {getFieldDecorator('password1', {
                                                    rules: [{ required: true, message: language.ChangePasswordNewpassword && language.ChangePasswordNewpassword.descripts }, { pattern:/^.{6,12}$/, message: language.ChangePasswordNewpassword && language.ChangePasswordNewpassword.message }, { pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])(.{6,12})$/, message: language.ChangePasswordLoginErr4 && language.ChangePasswordLoginErr4.descripts }, { pattern: /^(?:(?!(.+)\1{2,}).)+$/, message: language.ChangePasswordLoginErr8 && language.ChangePasswordLoginErr8.descripts }],
                                                })(
                                                    <Input size="large"  maxLength={12}  prefix={<Icon type="lock" />} type="password" placeholder={language.ChangePasswordNewpassword && language.ChangePasswordNewpassword.message} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={24}>
                                            <Form.Item label={language.ChangePasswordConfirmpassword && language.ChangePasswordConfirmpassword.descripts} {...formItemLayout}>
                                                {getFieldDecorator('password2', {
                                                    rules: [{ required: true, message: language.ChangePasswordConfirmpassword && language.ChangePasswordConfirmpassword.descripts }, { pattern: /^.{6,12}$/, message: language.ChangePasswordNewpassword && language.ChangePasswordNewpassword.message }, { pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])(.{6,12})$/, message: language.ChangePasswordLoginErr4 && language.ChangePasswordLoginErr4.descripts }, { pattern: /^(?:(?!(.+)\1{2,}).)+$/, message: language.ChangePasswordLoginErr8 && language.ChangePasswordLoginErr8.descripts }, {
                                                        validator: this.handlePassword
                                                    }],
                                                })(
                                                    <Input size="large"  maxLength={12}  prefix={<Icon type="lock" />} type="password" placeholder={language.ChangePasswordConfirmpassword && language.ChangePasswordConfirmpassword.descripts} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row style={{ display: this.state.visibleCode }}>
                                        <Col span={24}>
                                            <Form.Item
                                                help={this.state.codeHelp}
                                                validateStatus={this.state.codeStatus}
                                                label={language.ChangePasswordVerificationCode && language.ChangePasswordVerificationCode.descripts} {...formItemLayout}
                                            >
                                                <Input size="large" prefix={<Icon type="safety-certificate" />} placeholder={language.ChangePasswordVerificationCode && language.ChangePasswordVerificationCode.message} onChange={(e) => this.changeEvent(e)} id="verificationCode" addonAfter={<div className="codePhone">{language.ChangePasswordSend && language.ChangePasswordSend.descripts}</div>} />
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={18} offset={6}>
                                            <Row>
                                                <Col span={8} offset={8}>
                                                    <Form.Item>
                                                        <Button size="large" type="primary" htmlType="submit" className="login-form-button">{language.ChangePasswordSubmission && language.ChangePasswordSubmission.descripts}</Button>
                                                    </Form.Item>
                                                </Col>
                                            </Row>
                                        </Col>
                                    </Row>
                                </Form>
                            </div>
                        </div>
                    </Content>
                    <Footer className="loginFooter">
                        {httpConfig.Copyright}
                    </Footer>
                </Layout>
            </div>
        );
    }
}

const LoginFrom = Form.create()(Login);


export default LoginFrom