/*登录页面*/
import { connect } from 'react-redux';
import React, { Component } from 'react';
import BkHeader from './elements/BkHeader';
import { checkTel } from 'jrbasic';
import { STATUS_SUCCESS } from './../common/MifengConst';
import { ajaxGetCode, ajaxGetAgreement, ajaxLogin } from './../common/MifengRequest';
import {setCookie, getCookie } from './../common/SmallFun';
const SEND_CODE_TEXT = '发送验证码';
const SENDING_CODE_TEXT = '发送中';
const SEND_RETRY = '重新获取';
const TIME_TIP = 60;
import { loginSet } from '../redux/actions/count';

import read1 from './../common/imgs/read1.png';
import read2 from './../common/imgs/read2.png';
import xPng from './../common/imgs/x.png';
import loginbkPng from './../common/imgs/login-bk.png';/*其他*/
import fengrongPng from './../common/imgs/jianrong-bk.png';/*峰融*/
import  SPECIAL_B_PNG from './../common/imgs/SPECIAL_B.png';/*峰融*/
import  SPECIAL_C_PNG from './../common/imgs/login3.png';/*峰融*/
import  SPECIAL_D_PNG from './../common/imgs/login4.png';/*峰融*/



import { searchToObj } from 'jrbasic';
const SPECIAL_A = '001';
const SPECIAL_B = '002';
const SPECIAL_C = '003';
const SPECIAL_D = '004';
const fengrongBk = 'fengrong';



class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            sendCodeText: SEND_CODE_TEXT,
            timeTip: TIME_TIP,
            loginIng: false,
            readed: true,
            readDisplay: false,
            sending: false,
            agreement: ''
        }
    }

    componentDidMount() {
        ajaxGetAgreement({}).then((ret) => {
            this.setState({
                agreement: decodeURI(ret.data)
            })
        })
    }

    clickSendCode() {
        let that = this;
        let mobileVal = this.refs['mobile']['value'];
        const { sendCodeText, timeTip } = this.state;
        if(!mobileVal) {
            alert('请输入手机号');
            return false
        }
        if(!checkTel(mobileVal)) {
            alert('手机号码格式不正确');
            return false
        }
        if(this.state.sendCodeText === SEND_CODE_TEXT) {
            this.setState({
                sending: true,
                sendCodeText: SENDING_CODE_TEXT
            });
        }

        if (sendCodeText === SEND_CODE_TEXT || sendCodeText === SEND_RETRY) {
            /*如果当前的是文字，那么，可以点进去发送请求，进行计时*/

            console.log('获取验证码')
            ajaxGetCode({
                phone: mobileVal,
                dev_num: 'ffffffff-a153-7df6-ffff-ffffd76f23cb'
            }).then( (ret) => {
                if (ret.status === STATUS_SUCCESS) {
                    window.timeRunning = window.setInterval(function () {
                        that.setState({
                            sending: false,
                            sendCodeText: ' ' + that.state.timeTip + 's',
                            timeTip: that.state.timeTip - 1
                        })
                    }, 1000)
                }else {
                    this.setState({
                        sending: false,
                        sendCodeText: SEND_CODE_TEXT
                    });
                    alert(ret.message)
                }
                }
            )
        }
    }

    componentWillUnmount() {
        window.clearInterval(window.timeRunning);
    }

    componentWillUpdate(np, nextState) {
        if(nextState.timeTip < 0) {
            /*清除计时器，重新设置成可点的状态*/
            window.clearInterval(window.timeRunning);
            this.setState({
                sendCodeText: SEND_RETRY,
                timeTip: TIME_TIP
            })
        }
    }

    toLogin() {
        const [ mobileVal, codeVal ] = [ this.refs['mobile']['value'], this.refs['code']['value'] ];

        if(!mobileVal) {
            alert('请输入手机号');
            return false
        }
        if(!checkTel(mobileVal)) {
            alert('手机号码格式不正确');
            return false
        }
        if(!codeVal) {
            alert('请输入验证码');
            return false
        }

        if(!this.props.location['query']['pic'] && !this.state.readed ){
            alert('您还没有同意用户登录注册协议呢');
            return false
        }

        this.setState({
            loginIng: true
        });

        const envPrm = searchToObj(window.location['search']);
        ajaxLogin({
            phone: mobileVal,
            code: codeVal,
            app_name: '借吧h5版',
            app_union_name: 'jieba',
            device_id: 'ffffffff-a153-7df6-ffff-ffffd76f23cb',
            net_info: 'web',
            dev_no: 'web',
            dev_sys: 'web',
            cid: envPrm.cid
        }).then((ret) => {
            this.setState({
                loginIng: false
            });
            if(ret.status === STATUS_SUCCESS ) {
                setCookie('uid', ret.data.user_info['id'], 365);
                setCookie('token', ret.data.token, 365);
                this.props.loginSet(true);
                this.context.router.push(this.props.loginNextUrl)
            } else {
                window.clearInterval(window.timeRunning);
                this.setState({
                    sendCodeText: SEND_CODE_TEXT,
                    timeTip: TIME_TIP,
                    loginIng: false,
                    sending: false,
                });
                alert(ret.message)
            }
        } )
    }

    setRead() {
        this.setState({
            readed: !this.state.readed
        })
    }
    openReadInfo() {
        this.setState({
            readDisplay: true
        })
    }
    closeInfo() {
        this.setState({
            readDisplay: false
        })
    }




    getOtherLoginStyle(thisPic) {
        const { sendCodeText, readed, agreement, loginIng, readDisplay, sending } = this.state;


        switch (thisPic){
            case SPECIAL_A:
                return <div className="login-other">
                    <img src={ loginbkPng }/>
                    <input type="number" ref="mobile" className="mobile" placeholder="请输入手机号码"/>
                    <input type="number" ref="code" className="code" placeholder="请输入验证码" />
                    <p className="sedMsg" onClick={sending? undefined : this.clickSendCode.bind(this)}> { sendCodeText } </p>
                    <p style={{clear:'both'}} />
                    <div onClick={ loginIng ? undefined : this.toLogin.bind(this)  } className="btn"/>
                </div>;
            case SPECIAL_B:
                return <div className="login-other">
                    <img src={ SPECIAL_B_PNG }/>
                    <input type="number" ref="mobile" className="mobile" placeholder="请输入手机号码"/>
                    <input type="number" ref="code" className="code" placeholder="请输入验证码" />
                    <p className="sedMsg" onClick={sending? undefined : this.clickSendCode.bind(this)}> { sendCodeText } </p>
                    <p style={{clear:'both'}} />
                    <div onClick={ loginIng ? undefined : this.toLogin.bind(this)  } className="btn"/>
                </div>;
            case SPECIAL_C:
                return <div className="login-other">
                    <img src={ SPECIAL_C_PNG }/>
                    <input type="number" ref="mobile" className="mobile" placeholder="请输入手机号码"/>
                    <input type="number" ref="code" className="code" placeholder="请输入验证码" />
                    <p className="sedMsg" onClick={sending? undefined : this.clickSendCode.bind(this)}> { sendCodeText } </p>
                    <p style={{clear:'both'}} />
                    <div onClick={ loginIng ? undefined : this.toLogin.bind(this)  } className="btn"/>
                </div>;
            case SPECIAL_D:
                return <div className="login-other">
                    <img src={ SPECIAL_D_PNG }/>
                    <input type="number" ref="mobile" className="mobile" placeholder="请输入手机号码"/>
                    <input type="number" ref="code" className="code" placeholder="请输入验证码" />
                    <p className="sedMsg" onClick={sending? undefined : this.clickSendCode.bind(this)}> { sendCodeText } </p>
                    <p style={{clear:'both'}} />
                    <div onClick={ loginIng ? undefined : this.toLogin.bind(this)  } className="btn"/>
                </div>;
            default:
                return <div className="login-other">
                    <img src={ fengrongPng }/>
                    <input type="number" ref="mobile" className="mobile" placeholder="请输入手机号码"/>
                    <input type="number" ref="code" className="code" placeholder="请输入验证码" />
                    <p className="sedMsg" onClick={sending? undefined : this.clickSendCode.bind(this)}> { sendCodeText } </p>
                    <p style={{clear:'both'}} />
                    <div onClick={ loginIng ? undefined : this.toLogin.bind(this)  } className="btn"/>
                </div>
        }


    }




    getShow() {
        const { sendCodeText, readed, agreement, loginIng, readDisplay, sending } = this.state;

        const thisPic = this.props.location['query']['pic'];

        if ( thisPic ) {
            /*落地页登录*/
            return this.getOtherLoginStyle(thisPic)
        }else {
            return <div className="login-normal">
                <BkHeader location={this.props.location} />
                <div className="content">
                    <div className="brd btn-size">
                        <input  type="number" className="inputpos"  ref="mobile" placeholder="手机号码"/>
                    </div>
                    <div className="brd btn-size">
                        <input className="inputpos"  type="number" ref="code" placeholder="验证码"/>
                        <p className="sed-msg" onClick={sending? undefined : this.clickSendCode.bind(this)}>
                            { sendCodeText }
                        </p>
                    </div>
                    <p className="read" style={readed ? {
                        backgroundImage: 'url(' + read1 + ')'
                    }:{
                        backgroundImage: 'url(' + read2 + ')'
                    }}><span onClick={ this.setRead.bind(this) }>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                        <span onClick={ this.openReadInfo.bind(this) }>我已阅读并同意《用户登录注册协议》</span></p>
                    <p className="btn-size login-btn" onClick={ loginIng ? undefined : this.toLogin.bind(this)  }>登录</p>

                </div>
                { readDisplay ? <div className="read-tip">
                    <div className="content-box">
                        <p className="header">《用户登录注册协议》<img onClick={this.closeInfo.bind(this)} src={ xPng }/></p>
                        <div>
                            <p>{ agreement }</p>
                        </div>
                    </div>
                </div>:[]}
            </div>;

        }
    }

    render() {
        return this.getShow()
    }
}

Login.contextTypes = {
    router: React.PropTypes.object.isRequired
};

const getRedux = state => {
    return {
        loginNextUrl: state.update.loginNextUrl
    }
};

export default connect(
    getRedux, { loginSet }
)(Login)

