import React, { Component } from 'react';
import Login from '../Login';
import { patchUser, setCredentials } from '@doctorwork/write-easy/lib/api';
const parseQuery = require('@doctorwork/write-easy/utils').parseQuery;
const get = require('@doctorwork/write-easy/lib/api').get;
const SSO_DOMAIN = require('@doctorwork/write-easy/lib/wechat').SSO_DOMAIN;
const wxAppId = process.env.REACT_APP_WX_APPID;

class WxAuth extends Component {
    constructor(props) {
        super(props);
        this.state = {
            needLogin: false
        };
    }

    componentWillMount = async () => {
        const { openId, token, userId } = parseQuery(location.search);
        const authUser = JSON.parse(localStorage.authUser || '{}');
        if (userId) {
            setCredentials(
                'authUser',
                JSON.stringify({ ...authUser, userId })
            );
        }
        setCredentials('authToken', token);

        const user = await get(SSO_DOMAIN + '/passport/profile');
        // 登录查询用户信息
        if (!user.phone) {
            // 清除token
            setCredentials('authToken', '', -1);
            // ！！！ 通过patch 方式传递 openId 相关信息
            // 以实现绑定相关功能
            patchUser({ openId, userId, wxAppId });
            this.setState({ needLogin: true });
        } else {
            // 保存到 localStorage
            const authUser = JSON.parse(localStorage.authUser || '{}');
            setCredentials(
                'authUser',
                JSON.stringify({ ...authUser, openId, userId, wxAppId })
            );
            this.onLogin(user);
        }
    };

    onLogin = user => {
        // 跳转
        if (this.props.done) {
            this.props.done(user);
        } else {
            if (window.__wxjs_environment === 'miniprogram') {
                window.wx.miniProgram.navigateBack();
            } else {
                location.replace(localStorage.getItem('auth.redirect'));
            }
        }
    };

    render() {
        return (
            <React.Fragment>
                {this.state.needLogin ? (
                    <Login
                        onLogin={this.onLogin}
                        isBind={true}
                        title="绑定手机号"
                    />
                ) : null}
            </React.Fragment>
        );
    }
}

export default WxAuth;
