'use strict';
import React, { useEffect, useRef } from 'react';
import { connect } from "react-redux";
import authAction from '../actions'

const Cross = ({ dispatch, actions }) => {

    useEffect(async () => {
        function preLogout () {
            localStorage.removeItem('fs_iot_cross_user')
            sessionStorage.removeItem('user')
        }

        function messageListen (e) {
            // 此处需做 域名 验证
            const { data } = e
            if (data && data.action) {
                if (data.action == 'logout') {
                    preLogout()
                } else if (data.action = 'login') {
                    localStorage.setItem('fs_iot_cross_user', JSON.stringify(data.user))
                }
            }
        }
        function storageListen (e) {
            console.log(e);
            if (e.key == 'fs_iot_cross_user') {
                if (!e.newValue) {
                    // IOT AUTH 退出
                    window.parent.postMessage({ action: 'logout' }, '*');
                }
            }
        }
        if (window.parent) {
            window.addEventListener('message', messageListen);
            window.addEventListener("storage", storageListen);
            let user = localStorage.getItem('fs_iot_cross_user')

            if (user) {
                user = JSON.parse(user)
                const crossRslt = await dispatch(authAction.crossCheck({ token: user.token }))
                window.parent.postMessage({ action: 'initUser', user: user }, '*');
                if (crossRslt.success && crossRslt.payload.data.cross) {
                    window.parent.postMessage({ action: 'initUser', user: user }, '*');
                } else {
                    window.parent.postMessage({ action: 'logout' }, '*');
                    preLogout()
                }
            } else {
                window.parent.postMessage({ action: 'initNotice' }, '*');
            }
        }
        return () => {
            window.removeEventListener('message', messageListen);
            window.removeEventListener('storage', storageListen);
        }
    }, [])

    return (
        <div>FS_IOT_AUTH_CROSS</div>
    )
}

function mapStateToProps (state) {
    const { global, auth, webSocket } = state;
    return {
        actions: global.actions,
        user: auth.user,
    };
}

export default connect(mapStateToProps)(Cross);