import React, { PureComponent } from 'react';
const styles = require('./style.module.styl');

import * as api from '@doctorwork/write-easy/lib/api';
const SetCookie: any = require('@doctorwork/write-easy/utils/cookie').SetCookie;
import { setCredentials } from '@doctorwork/write-easy/lib/api';
import { parseQuery } from '@doctorwork/write-easy/utils';
import toast from '../Toast';
import { withOptions } from '@doctorwork/write-easy/lib/api';
import { commonHeader } from '@doctorwork/write-easy/lib/api';


const rewriteOptions = withOptions({
    headers: {
        'Content-type': 'application/json; charset=UTF-8',
        _head: JSON.stringify({
            ...commonHeader,
            token: parseQuery(location.href).token
        })
    }
})
// 绑定手机号专用
const getApis = rewriteOptions(api.get)



const sso = process.env.REACT_APP_SSO_DOMAIN || location.origin + '/sso/v1';
const user: any = {
    smsType: 1
};
const clearData = () => {
    localStorage.removeItem('authUser');
    localStorage.removeItem('authToken');
};
const setData = res => {
    const { userId } = res;
    const { openId = '' } = parseQuery(location.href);
    setCredentials('authUser', JSON.stringify({ userId, openId }));
    setCredentials('authToken', res.token);
};
// const getApi = addHeader(api.get);
const getApi = api.get;
const postApi = api.post;

// 短信时间限制
const TIMELIMIT = 60;

const backToStart = () => {
    if (window.__wxjs_environment === 'miniprogram') {
        window.wx.miniProgram.navigateBack();
    } else {
        const redirect = localStorage.getItem('auth.redirect') || '';
        location.replace(redirect);

    }
};

const unless = (first, second) => (first ? first : second);

interface LoginState {
    pending: boolean;
    failed: number;
    countdown: number;
}

interface LoginProps {
    title?: string;
    isBind: boolean;
    onLogin?: Function;
    btnTitle?: string;
}

class Login extends PureComponent<LoginProps, LoginState> {
    constructor(props: LoginProps) {
        super(props);
        this.state = {
            pending: false,
            failed: 0,
            countdown: TIMELIMIT
        };
        clearData();
    }

    getSms = () => {
        if (this.state.pending) {
            return;
        }
        getApi(sso + '/passport/smscode', user).then(() => {
            this.setState({
                pending: true
            });
            this.startTimer();
        }).catch(({ errcode, errmsg }) => {
            toast(errmsg);
        });
    };

    startTimer() {
        let intval = setInterval(() => {
            const countdown = this.state.countdown;
            if (countdown == 1) {
                this.setState({ countdown: TIMELIMIT, pending: false });
                clearInterval(intval);
                return;
            }
            this.setState({
                countdown: countdown - 1
            });
        }, 1000);
    }

    bindPhone_pending = false;
    bindPhone = () => {
        if (this.bindPhone_pending) return;
        this.bindPhone_pending = true;

        const reLogin = () => {
            const onLogin = this.props.onLogin;
            postApi(sso + '/passport/login_no_verifycode', {
                phone: user.phone
            }).then(res => {
                setData(res);
                unless(onLogin, backToStart)(res);
            });
        };

        getApis(sso + '/passport/bind_phone_smart', {
            phone: user.phone,
            verifyCode: user.verifyCode
        }).then(res => {
            this.bindPhone_pending = false;
            reLogin();
        }).catch(({ errcode, errmsg }) => {
            this.bindPhone_pending = false;
            if (errcode === 2015001 || errcode === 2015010) {
                reLogin();
                return;
            }

            if (errcode == 2015011) {
                return toast('手机号已与其他微信号绑定');
            }
            toast(errmsg);
        });
    };
    doLogin_pending = false;
    doLogin = () => {
        const { onLogin } = this.props;
        if (this.doLogin_pending) return;
        this.doLogin_pending = true;
        postApi(sso + '/passport/login', {
            account: user.phone,
            verifyCode: user.verifyCode,
            authType: 2
        })
            .then((data: any) => {
                const { userId, openId } = data;
                localStorage.setItem('authToken', data.token);
                setCredentials('authToken', data.token);
                setCredentials(
                    'authUser',
                    JSON.stringify({
                        userId,
                        openId
                    })
                );

                postApi('/user/login')
                    .then(res => {
                        this.doLogin_pending = false;
                        unless(onLogin, backToStart)(res);
                    })
                    .catch(err => {
                        this.doLogin_pending = false;
                    });
                this.doLogin_pending = false;
            })
            .catch(err => {
                this.doLogin_pending = false;
            });
    };

    render() {
        const { isBind } = this.props;
        return (
            <div className={styles.container}>
                <div className={styles.wrapper}>
                    <h4>{this.props.title || '登录'}</h4>
                    <p>
                        <input
                            type="text"
                            placeholder="输入手机号码"
                            onChange={evt => {
                                user.phone = evt.target.value;
                            }}
                            style={styles.input}
                        />
                    </p>
                    {/* TODO: 图形验证码 */}
                    <p>
                        <input
                            type="text"
                            placeholder="短信验证码"
                            onChange={evt => {
                                user.verifyCode = evt.target.value;
                            }}
                            style={styles.input}
                        />
                        {this.state.pending ? (
                            <button className={styles.sms}>
                                {this.state.countdown}秒
                            </button>
                        ) : (
                                <button
                                    onClick={this.getSms}
                                    className={styles.sms}
                                >
                                    获取验证码
                            </button>
                            )}
                    </p>

                    <button
                        type="submit"
                        onClick={isBind ? this.bindPhone : this.doLogin}
                        className={styles.login}
                    >
                        {this.props.btnTitle || '登录'}
                    </button>
                </div>
            </div>
        );
    }
}

export default Login;
