<template>
    <!-- 外层样式添加 position:relative 样式 -->
    <div class="btnLogin" @click="login"></div>
</template>

<script>
import { getStorage, setStorage, removeStorage, storageKey, getOauthUrl, jumpUrl } from '../utils/help';
import { postRequest } from '../http';

export default {
    name: 'buttonLogin',
    computed: {
        userInfo() {
			return getStorage(storageKey.userInfo);
		}
    },
    data() {
        return {
            timer: null,
        }
    },
    unmounted() {
        clearInterval(this.timer);
    },
    methods: {
        login() {
            if (!!this.userInfo) {
                // 已登录
                this.$emit('success', this.userInfo)
            } else {
                // 未登录
                this.twitterAuth()
            }
        },
        async twitterAuth() {
            let win;
            let isiOS = !!window.navigator.userAgent.match(/\(i\[^;]+;( U;)? CPU.+Mac OS X/);
            if (isiOS) {
                win = window.open();
                win.opener = null;
            }
            // post
            postRequest(`/denet/user/twitterRequestToken`, {
				params: {
					oauthCallback: `${jumpUrl}authlogin`,
				},
			}).then(({ code, data }) => {
                if (code == 0) {
                    if (isiOS) {
                        win.location.href = getOauthUrl(data.authToken);
                    } else {
                        win = window.open(getOauthUrl(data.authToken));
                    }
                    
                    // timer
                    this.timer = setInterval(() => {
						if (win && win.closed) {
							clearInterval(this.timer);
							this.twitterLogin(data);
						}
					}, 500);
                } else {
                    this.$emit('error')
                }
            })
        },
        twitterLogin(authData) {
            let verifier = getStorage(storageKey.verifier);
            if (verifier) {
				postRequest(`/denet/user/twitterLogin`, {
					params: {
						consumerKey: authData.consumerKey,
						oauthToken: authData.authToken,
						oauthVerifier: verifier,
					},
				}).then(({ code, data }) => {
					if (code == 0) {
						setStorage(storageKey.userInfo, data);
						removeStorage(storageKey.verifier);
                        this.$emit('success', data)
					} else {
                        this.$emit('error')
					}
				});
			} else {
                this.$emit('error')
			}
        }
    }
}
</script>

<style lang="scss" scoped>
.btnLogin {
    position: absolute;
    z-index: 10;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
</style>
