import React, {Component} from 'react';

import {BrowserRouter as Router, Route, Link, Switch} from "react-router-dom";

import {getImageUrl, DragValidator,broadcastChannelPostMessage} from 'educoder';
import {Tabs, Input, Checkbox, Button, notification,Menu} from 'antd';
import passopen from '../../../src/images/login/passopen.png';
import passoff from '../../../src/images/login/passoff.png';
import axios from 'axios';
import DragValidatortwo from '../../../src/common/components/DragValidatortwo'
import './common.css'
const { TabPane } = Tabs;
const loginInputsyl = {
"width":"434px",
"height": "462px",
"-webkit-box-shadow": "3px 10px 21px 0px rgba(76,76,76,0.15)",
"box-shadow": "3px 10px 21px 0px rgba(76,76,76,0.15)",
"border-radius": "6px",
"background": "#fff"
}

//父组件EducoderLogin.js
class LoginRegisterComponent extends Component {
    constructor(props) {
        super(props)


        //
        // console.log("LoginRegisterComponent");
        // console.log("29");
        // console.log(props.loginstatus);
        if(props.loginstatus === true){
            // console.log(props.loginstatus);
            this.state = {
                tab:["0"],
                activeKey: 0,
                classpass: "text",
                // 登录
                passopens: passopen,
                seconds: 35,
                discodeBtn: false,
                clearInterval: false,
                autoLogin: true,
                classpassbool: false,
                // 注册
                readAgreement: false,
                getverificationcodes: true,
                dragOk: false,
                Agreetotheterms: false,
                login: "",
                password: "",
                logins: "",
                passwords: "",
                codes: "",
                Phonenumberisnotco: undefined,
                Phonenumberisnotcos: undefined,
                Phonenumberisnotcobool: false,
                Whethertoverify:false,

            }
        }
        if(props.loginstatus === false){
            // console.log(props.loginstatus);
            this.state = {
                tab:["1"],
                activeKey: '1',
                classpass: "text",
                // 登录
                passopens: passopen,
                seconds: 35,
                discodeBtn: false,
                clearInterval: false,
                autoLogin: true,
                classpassbool: false,
                // 注册
                readAgreement: false,
                getverificationcodes: true,
                dragOk: false,
                Agreetotheterms: false,
                login: "",
                password: "",
                logins: "",
                passwords: "",
                codes: "",
                Phonenumberisnotco: undefined,
                Phonenumberisnotcos: undefined,
                Phonenumberisnotcobool: false,
                Whethertoverify:false,

            }
        }
    }

// 点击表单后,改变type
    changeType = () => {
        this.setState({classpass: 'password'});
    }
    componentDidMount = () => {
        // console.log("componentDidUpdate");
        // console.log(this.props);
        if (this.props.match.url === "/login") {
            console.log("11111111111111111111111111");
            this.state = {
                tab:["0"],
            }
            this.onTabChange('0');
        } else if (this.props.match.url === "/register") {
            this.state = {
                tab:["1"],
            }
            this.onTabChange('1');
        }

    }
    openNotification = (messge,type) => {
        // type  1 成功提示绿色 2提醒颜色黄色 3错误提示红色
        notification.open({
            message: "提示",
            description: messge,
            onClick: () => {
                console.log('Notification Clicked!');
            },
        });
    }


    ;
    StudyMakeMoney = () => { // 调用父组件方法
        this.props.Setshowbool(3);
        // this.props.Setlogins(3);
        this.setState({
            login: "",
            password: "",
            logins: "",
            passwords: "",
            codes: "",
        })
    }
    onTabChange = (activeKey) => {
        console.log("onTabChange");
        // console.log(activeKey);
        // this.setState({activeKey})
    }
    // -------------------- LOGIN START
    //下次自动登入
    onAutoLoginChange = (e) => {
        this.setState({autoLogin: e.target.checked})
    }

    // -------------------- LOGIN END

    isCorrectname = (value, id) => {
        if (id === 1) {
            console.log(value.length);
            if (value.length === 0) {
                this.setState({
                    Phonenumberisnotco: undefined,
                    Phonenumberisnotcobool: false,
                })
                return;
            }
        } else if (id === 2) {
            if (value.length === 0) {
                this.setState({
                    Phonenumberisnotcos: undefined,
                    Phonenumberisnotcobool: false,
                })
                return;
            }
        }
        this.Emailphonenumberverification(value, id)

    }
    // -------------------- REGISTER START
    onReadAgreementChange = (e) => {
        this.setState({readAgreement: e.target.checked})
    }
    //是否验证通过
    dragOkCallback = () => {
        console.log(this.state.logins);
        this.Emailphonenumberverification(this.state.logins, 2)

    }
    // -------------------- REGISTER END

    //是否同意
    onChange = (e) => {
        this.setState({
            Agreetotheterms: e.target.checked,
        })
    }

    //登入接口
    postLogin = () => {
        if (this.state.login === undefined || this.state.login == "") {
            this.openNotification(`请输入登录手机号码或邮箱`,2);
            return
        } else if (this.state.password === undefined || this.state.password == "") {
            this.openNotification(`请输入密码`,2);
            return
        }
        var url = "/accounts/login.json";
        axios.post(url, {
            login: this.state.login,
            password: this.state.password,
        }).then((response) => {
            if (response === undefined) {
                return
            }
            if (response.status === 200) {
                if (response.data.status === 402) {
                    window.location.href = response.data.url;
                } else {
                    broadcastChannelPostMessage('refreshPage')
                    this.setState({
                        isRender: false
                    })
                    window.location.href = "/"

                }
            }


        }).catch((error) => {

        })

    }
    //注册接口
    postregistered = () => {
        if (this.state.logins === undefined || this.state.logins === "") {
            this.openNotification(`请输入登录手机号码或邮箱`,2);

            return
        } else if (this.state.dragOk === false) {
            this.openNotification(`请拖动滑块验证`,2);
            return
        } else if (this.state.codes === undefined || this.state.codes == "") {
            this.openNotification(`请输入验证码`,2);
            return
        } else if (this.state.passwords === undefined || this.state.passwords == "") {
            this.openNotification(`请输入密码`,2);
            return
        } else if (this.state.Agreetotheterms === false) {
            this.openNotification(`请同意服务协议条款`,2);
            return;
        }
        var url = "/accounts/register.json";
        axios.post(url, {
            login: this.state.logins,
            password: this.state.passwords,
            code: this.state.codes,
        }).then((result) => {
            if(result){
                        this.setState({
                            logins: "",
                            dragOk: false,
                            codes: "",
                            passwords: "",
                            Agreetotheterms: "",
                        })
                        this.props.history.push("/interesse");
                }
        }).catch((error) => {

        })
    }

    //邮箱手机号验证
    Emailphonenumberverification = (value, id) => {
        var url = `/accounts/valid_email_and_phone.json`;
        axios.get((url), {
            params: {
                login: value,
                type: 1,
            }
        }).then((result) => {
            //验证有问题{"status":1,"message":"success"}
            // console.log(result);
            // this.setState({dragOk: true})

            if(result){
                 if(result.data.status===-2){
                     if (id === 1) {
                         console.log(value.length);
                         if(result.data.message==="该手机号码或邮箱已被注册"){
                             this.setState({
                                 Phonenumberisnotco: undefined,
                                 Phonenumberisnotcobool: false,
                                 dragOk:true,
                             })
                         }else {
                             this.setState({
                                 Phonenumberisnotco: result.data.message,
                                 Phonenumberisnotcobool: true,
                                 dragOk:false,
                                 Whethertoverify:this.state.Whethertoverify===true?false:true,
                             })
                         }
                             return;
                     } else if (id === 2) {
                             this.setState({
                                 Phonenumberisnotcos: result.data.message,
                                 Phonenumberisnotcobool: true,
                                 dragOk:false,
                                 Whethertoverify:this.state.Whethertoverify===true?false:true,
                             })
                             return;
                     }
                 }else {
                     if (id === 1) {
                         console.log(value.length);
                             this.setState({
                                 Phonenumberisnotco: undefined,
                                 Phonenumberisnotcobool: false,
                                 dragOk:true,
                             })
                             return;
                     } else if (id === 2) {
                             this.setState({
                                 Phonenumberisnotcos: undefined,
                                 Phonenumberisnotcobool: false,
                                 dragOk:true,
                             })
                             return;
                     }
                 }
             }

        }).catch((error) => {

        })
    }
    //短信验证
    SMSverification = () => {
        var url = `/accounts/get_verification_code.json`;
        axios.get((url), {
            params: {
                login: this.state.logins,
                type: 1,
            }
        }).then((result) => {
            //验证有问题{"status":1,"message":"success"}
            // console.log(result);
            this.openNotification("验证码已发送,请注意查收!",2);


        }).catch((error) => {
            console.log(error);

        })
    }
    //显示和不显示密码
    Showandhide = (e) => {
        console.log("显示于隐藏");
        if (this.state.classpassbool === true) {
            this.setState({
                passopens: passopen,
                classpass: "text",
                classpassbool: false,
            })
        } else {
            this.setState({
                passopens: passoff ,
                classpass: "password",
                classpassbool: true,
            })
        }

    }

    //倒计时
    getverificationcode = () => {
        console.log(this.state.Phonenumberisnotcobool);
        console.log(this.state.dragOk);
        if(this.state.logins === undefined || this.state.logins.length===0){
            this.openNotification("请输入手机号或邮箱");
            return;
        }
        //这是判断是否手机正确
        if(this.state.Phonenumberisnotcobool === true){
            this.openNotification(this.state.Phonenumberisnotcos);
            this.setState({
                Whethertoverify:this.state.Whethertoverify===true?false:true,
            })
            return;
        }
        if(this.state.dragOk===undefined||this.state.dragOk === false){
            this.openNotification("拖动滑块验证");
            return;
        }

        if (this.state.getverificationcodes === true) {
            this.setState({
                getverificationcodes: undefined,
            })
            let timer = setInterval(() => {
                this.setState((preState) => ({
                    seconds: preState.seconds - 1,
                }), () => {
                    if (this.state.seconds == 0) {
                        clearInterval(timer);
                        this.setState({
                            getverificationcodes: false,
                            seconds: 35,
                        })
                    }
                });
            }, 1000)
            this.SMSverification();
        } else {
            this.setState({
                getverificationcodes: undefined,
            })
            let timer = setInterval(() => {
                this.setState((preState) => ({
                    seconds: preState.seconds - 1,
                }), () => {
                    if (this.state.seconds == 0) {
                        clearInterval(timer);
                        this.setState({
                            getverificationcodes: false,
                            seconds: 35,

                        })
                    }
                });
            }, 1000)
            this.SMSverification();
        }
    }
    //滑动验证手机号

    //获取登入
    loginInputonChange = (e) => {
        // console.log(e.target.value);
        var stirngt;
        if(e.target.value.length>0){
            var str=  e.target.value.replace(/\s*/g,"")
            stirngt=str;
        }else{
            stirngt=  e.target.value;
        }

        if (e.target.value.length === 0) {
            this.setState({
                Phonenumberisnotco: undefined,
                Phonenumberisnotcobool: false,
                login: stirngt,
            })
        }else{
            this.setState({
                login: stirngt,
            })
        }

    }
    //失去焦点判断
    inputOnBlur = (e, id) => {
        this.isCorrectname(e.target.value, id);
        // this.Emailphonenumberverification(e.target.value, id);
    }
    //获取登入密码
    passwordonChange = (e) => {
        // console.log(e.target.value);
        var stirngt;
        if(e.target.value.length>0){
            var str=  e.target.value.replace(/\s*/g,"")
            stirngt=str;
        }else{
            stirngt=  e.target.value;
        }
        this.setState({
            password: stirngt,
        })
        // this.setState({
        //     password: e.target.value
        // })
    }
    //获取注册登入
    loginInputonChanges = (e) => {
        console.log(e.target.value);
        var stirngt;
          if(e.target.value.length>0){
           var str=  e.target.value.replace(/\s*/g,"")
              stirngt=str;
          }else{
              stirngt=  e.target.value;
          }
            if (e.target.value.length === 0) {
                this.setState({
                    Phonenumberisnotcos: undefined,
                    Phonenumberisnotcobool: false,
                    logins: stirngt,
                    dragOk:false,
                    Whethertoverify:this.state.Whethertoverify===true?false:true,
                })
            }else{
                this.setState({
                    logins: stirngt,
                    Phonenumberisnotcos: undefined,
                    dragOk:false,
                    Whethertoverify:this.state.Whethertoverify===true?false:true,
                })
            }

    }
    //获取注册密码
    passwordonChanges = (e) => {
        // console.log(e.target.value);
        var stirngt;
        if(e.target.value.length>0){
            var str=  e.target.value.replace(/\s*/g,"")
            stirngt=str;
        }else{
            stirngt=  e.target.value;
        }
        this.setState({
            passwords: stirngt,
        })
    }
    //获取code
    codesonChange = (e) => {
        this.setState({
            codes: e.target.value
        })
    }
    //切换tab
    changeTab=(e)=>{
        this.setState({
            tab:e.key
        })
       console.log(e.key);
        if(e.key === 0){
            this.setState({
                Phonenumberisnotcos:undefined
            })
        }else{
            this.setState({
                Phonenumberisnotco:undefined
            })

        }

        // this.props.history.push(`/courses/${this.props.match.params.coursesId}/exercises/${this.props.match.params.Id}/student_exercise_list?tab=`+e.key)

    }
    loginonkeyup =(e)=>{
        if(e.keyCode==32){

            return false;
        }
    }
    render() {
        const {
            activeKey,
            // 登录
            autoLogin,
            classpass,
            passopens,
            seconds,
            getverificationcodes,
            Agreetotheterms,
            Phonenumberisnotco,
            Phonenumberisnotcos,
            codes,
            tab,
            dragOk,
            Whethertoverify,
            classpassbool,
            // 注册
            readAgreement,
        } = this.state
        // height: 346px;
        if (this.state.seconds === 0) {
            // window.location.href='http://www.cnblogs.com/a-cat/';
        }

        console.log(classpass);
        return (

            <div className="login_register_content" style={  parseInt(tab[0])==0?{height: "346px"} :{height: "490px"}}>


                <div>
                    <Menu mode="horizontal" selectedKeys={tab} onClick={this.changeTab}>
                        <Menu.Item key="0" className={tab===0?"active font-18":"font-18"}   > 登录</Menu.Item>
                        <Menu.Item key="1" className={tab===1?"active font-18":"font-18"}  >注册</Menu.Item>
                    </Menu>

                    {
                        parseInt(tab[0])==0 &&
                        <div style={{width: '340px'}}>
                            <style>
                                {
                                    `
														.ant-input {
																		font-family: "Monospaced Number", "Chinese Quote", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
																		-webkit-box-sizing: border-box;
																		box-sizing: border-box;
																		margin: 0;
																		padding: 0;
																		list-style: none;
																		position: relative;
																		display: inline-block;
																		padding: 4px 11px;
																		width: 100%;
																		height: 38px;
																		font-size: 14px;
																		line-height: 1.5;
																		color: rgba(0, 0, 0, 0.65);
																		background-color: #fff;
																		background-image: none;
																		border: 1px solid #d9d9d9;
																		border-radius: 4px;
																		-webkit-transition: all .3s;
																		-o-transition: all .3s;
																		transition: all .3s;
																}
														  .loginInputzhuche{
																	width: 100%;
																	background-color: #fff!important;
																	height: 45px !important;
																	padding: 5px;

																}

                                `
                                }
                            </style>

                            <Input placeholder="请输入登录手机号码或邮箱" value={this.state.login}
                                   onChange={this.loginInputonChange}
                                   name="username"
                                   className="font-14 color-grey-9 loginInputzhuche"
                                   onBlur={(e) => this.inputOnBlur(e, 1)}
                                   style={{marginTop: '30px', height: '38px'}}></Input>

                            {
                                Phonenumberisnotco && Phonenumberisnotco != "" ?
                                    <p className="color-red  mt5 mb5" style={{width: " 100%", height: "20px"}}>
                                        <span className="fl" style={{textAlign:"left",width: " 100%"}}>{Phonenumberisnotco}</span>
                                    </p>
                                    : <div style={{height:"25px"}}></div>
                            }

                            <Input type="password" name="password" id="password"   value={this.state.password}
                                   onChange={this.passwordonChange}
                                   className="font-14 color-grey-9 loginInputzhuche"

                                   placeholder="密码"></Input>

                            <div className="left_right mt25 font-12 " style={{color: '#676767'}}>
                                <Checkbox onChange={this.onAutoLoginChange} checked={autoLogin}>下次自动登录</Checkbox>

                                <a onClick={()=>this.StudyMakeMoney()}
                                    className="mr3 color-grey-9 mt3 font-12">找回密码</a>
                            </div>

                            <Button className="login_btn font-16" type="primary" style={{height:"46px"}} onClick={() => this.postLogin()}
                                    size={"large"}>登录</Button>
                        </div>
                    }
									<style>
										{
											`
											.loginInputzhuche{
													width: 100%;
													background-color: #fff!important;
													height: 45px !important;
													padding: 5px;

												}
										 .loginInputzhuche .ant-input{
													width: 100%;
													background-color: #fff!important;
													height: 45px !important;
													padding: 5px;
													position: relative;
													right: 5px;
													width: 103%;
												}
												`
										}
									</style>

                    {
                        parseInt(tab[0])==1 &&
                        <div style={{width: '340px'}}>
                            <Input className="loginInputsyl color-grey-9 loginInputzhuche" placeholder="请使用手机号/邮箱账号进行注册"
                                   value={this.state.logins}
                                   type="text" autoComplete="off"
                                   onChange={this.loginInputonChanges}
                                   style={{marginTop: '30px' , height: '38px',color:'#999999',fontSize:"14px"}}></Input>
                            {
                                Phonenumberisnotcos && Phonenumberisnotcos != "" ?
                                    <p className="color-red  mt5 mb5  " style={{width: " 100%", height: "20px"}}>
                                        <span className="fl" style={{textAlign:"left",width: " 100%"}}>{Phonenumberisnotcos}</span>
                                    </p>
                                    : <div style={{height:"25px"}}></div>

                            }
                            {
                                Whethertoverify===false?
                                  <DragValidator
                                    height={38} className="loginInput" successGreenColor="#29bd8b"
                                    style={{ height: '38px'}}
                                    dragOkCallback={this.dragOkCallback}
                                  ></DragValidator>
                                  :
                               ""

                            }
                            {
                                Whethertoverify===true?
                                <DragValidatortwo
                                  height={38} className="loginInput" successGreenColor="#29bd8b"
                                  style={{ height: '38px'}}
                                  dragOkCallback={this.dragOkCallback}
                                ></DragValidatortwo>
                                :
                                ""
                            }



                            <div className="mt25">
                                <Input className="fl mr5 font-14 color-grey-9 loginInputzhuche" name="codes" type="text" autoComplete="off" readonly
                                       onfocus="this.removeAttribute('readonly')" style={{
                                    width:'210px',
                                    height:'38px',
                                }} placeholder="请输入验证码"
                                       onChange={this.codesonChange}
                                       value={codes}
                                >
                                </Input>
                                {
                                    getverificationcodes === undefined ?
                                        <Button className="fl ml5 font-14" disabled style={{"width": "120px","text-align":"center", "height": "45px",}}
                                                size={"large"}>重新发送{seconds}s</Button>
                                        : getverificationcodes === true ?
                                        <Button className="fl ml5 font-14" type="primary" style={{"width": "120px","text-align":"center", "height": "45px",}}
                                                onClick={() => this.getverificationcode()} size={"large"}>获取验证码</Button>
                                        :
                                        <Button className="fl ml5 font-14 " type="primary" style={{"width": "120px","text-align":"center", "height": "45px",}}
                                                onClick={() => this.getverificationcode()} size={"large"}>重新发送</Button>
                                }


                            </div>

                            <style>
                                {
                                    `
                                    .ant-input-affix-wrapper .ant-input-suffix {
                                        right: 12px;
                                        height: 20px;
                                    }
                                    `
                                }
                            </style>
                            <Input className="loginInput  font-14 mt25  color-grey-9 loginInputzhuche" placeholder="输入8~16位密码,区分大小写"
                                   type={classpassbool===false?"text":"password"}

                                   autoComplete="new-password"
                                   onClick={this.changeType}
                                   value={this.state.passwords} onChange={this.passwordonChanges}
                                suffix={
                                <img className={"mt5"} src={passopens} onClick={(key) => this.Showandhide(key)}>
                                </img>
                            }></Input>
                            <Checkbox onChange={this.onChange}
                                      value={Agreetotheterms}
                            ><span className="font-14 "  style={{
                                color: '#676767',
                            }}>我已阅读并同意服务协议条款</span></Checkbox>
                            <Button className="login_btn font-16" type="primary" style={{height:"46px"}} onClick={() => this.postregistered()}
                                    size={"large"}>注册</Button>


                        </div>
                    }
                </div>
            </div>
        );
    }
}

export default (LoginRegisterComponent);