import React from 'react';
import i18next from 'i18next';
import {Grid, Header} from 'semantic-ui-react';
import LoginForm from './Form.js';
import Dialog from '../../containers/DialogControl';
import {add_dialog_msg, toggle_loading} from '../../actions';
import {connect} from 'react-redux';
import Loading from '../../containers/LoadingControl';

class Root extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            i18n: {}
        };
    }

    handleSubmit = (data) => {
        let {i18n} = this.state;
        if (typeof data.account != 'string' || !data.account.trim() || typeof data.password != 'string' || !data.password.trim()) {
            // show dialog
            this.props.dispatch(add_dialog_msg(i18n && 't' in i18n ? i18n.t('tip.input_empty') : ''));
            return;
        }

        this.props.dispatch(toggle_loading(1));
        fetch('/api/system/login', {
            method: 'post',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
                body: JSON.stringify({data})
            })
            .then(res => res.json())
            .then(json => {
                this.props.dispatch(toggle_loading(0));
                if(json.status != 1) {
                    this.props.dispatch(add_dialog_msg(json.message));
                    return ;
                }

                sessionStorage.setItem('write_privilege', json.data.record[0].write_privilege);
                sessionStorage.setItem('read_privilege', json.data.record[0].read_privilege);
                sessionStorage.setItem('account', json.data.record[0].account);

                sessionStorage.setItem('token', json.data.token);
                if(json.data.rt.permission && json.data.rt.permission.length > 0) {
                    sessionStorage.setItem('permissions', JSON.stringify(json.data.rt.permission[0]));
                }

                // this.props.dispatch(add_dialog_msg('登入成功', () => {
                    location.replace('/admin');
                // }))
            })
            .catch(err => this.props.dispatch(add_dialog_msg('登入失敗')));

    }

    componentDidMount() {
        let lang = navigator
            .language
            .substring(0, 2);
        fetch(`/locales/${lang}.json`).then(response => {
            if (response.status == 200) 
                return response.json();
            return {}
        }).then(json => {
            let lang = Object.keys(json)[0] || '';
            i18next.init({
                lng: lang,
                resources: json
            }, () => {
                this.setState({i18n: i18next});
            })
        })
    }

    render() {
        const {i18n} = this.state;
        const page = 'page.login';
        return (
            <div style={{
                height: '100%'
            }}>
                <Loading />
                <Dialog/>
                <Grid verticalAlign="middle" centered className="login-grid">
                    <Grid.Column className="login-column">
                        <Header textAlign="center" content={'JCNet WebIO'} as="h2" color="teal"/>
                        <LoginForm i18n={this.state.i18n} page={page} onSubmit={this.handleSubmit}/>
                    </Grid.Column>
                </Grid>
            </div>
        );
    }
}

export default connect()(Root)