import React, {Component} from 'react';
import {Layout, Menu, Input, Button, Spin, Breadcrumb, Icon, Radio, LocaleProvider} from 'antd';
import {BrowserRouter as Router, Route, Link, Switch, Redirect} from "react-router-dom";
import gql from "graphql-tag";
import {Query} from "react-apollo";
import moment from 'moment';
import 'moment/locale/zh-cn';
import { FormattedMessage } from 'react-intl';

import CloudFunction from '../cloudFunction/CloudFunction';
import MonitorNotify from '../monitorNotify/MonitorNotify';
import DataAnalysis from '../dataAnalysis/DataAnalysis';
import DataStorage from '../dataStorage/DataStorage';

import zhCN from 'antd/lib/locale-provider/zh_CN';
import '../common/graphql/index.css';
import './index.css'
import TrialCase from "../trialCase/TrialCase";

const {SubMenu} = Menu;
const {Header, Sider} = Layout;
moment.locale('en');

class App extends Component {
    constructor(props) {
        super(props);
        sessionStorage.setItem("language","English");
        this.state = {
            menuLevel1: "trail",
            sideBar: "e-commerce",
            userID: '',
            hasLogin: false,
            user: {
                nickname: '',
                avatar: ''
            },
            collapsed: false,
            inlineCollapsed: false,
            locale: undefined,
            language: sessionStorage.getItem("language")
        };
    }

    onCollapse = (collapsed) => {
        console.log(collapsed);
        this.setState({collapsed});
    };

    switchMenu = (menuName, e) => {
        console.log('menuName', menuName, 'e', e);
        this.setState({
            [menuName]: e.key,
        });
    };

    changeLocale = (e) => {
        e.stopPropagation();
        let language = sessionStorage.getItem("language");
        console.log('now language',language);
        let local = language === "中文" ? zhCN : undefined;
        console.log('local',local);
        let changeLanguage = language === "中文" ? "English" :  "中文";
        console.log('changeLanguage',changeLanguage);
        sessionStorage.setItem("language",changeLanguage);
        this.props.changeLanguage(changeLanguage);
        this.setState({
            language:changeLanguage,
            locale:local
        });
        if (!local) {
            moment.locale('en');
        } else {
            moment.locale('zh-cn');
        }
    };

    login = (id) => {
        const GET_USER = gql`
            query USER($id: ID!) {
                user_by_id(id: $id) {
                    avatar,
                    nickname
                }
            }
        `;
        return (
            <Query query={GET_USER} variables={{id}}>
                {
                    ({loading, error, data}) => {
                        if (loading) {
                            return <Spin style={{marginLeft: 3}}/>
                        }
                        if (error) {
                            return 'error!';
                        }

                        if (data.user_by_id === null)
                            return (
                                <div>
                                    <span style={{marginRight: '10px'}}>no such person</span>
                                    <Button onClick={() => {
                                        this.setState({hasLogin: false})
                                    }}>relogin</Button>
                                </div>
                            );
                        else {
                            // 不可使用 this.setState, 会报错。
                            // Warning: Cannot update during an existing state transition (such as within `render`).
                            // Render methods should be a pure function of props and state.
                            this.state.user = {
                                avatar: data.user_by_id.avatar,
                                nickname: data.user_by_id.nickname
                            };
                            console.log(data);
                            return (
                                <div>
                                    <span style={{marginRight: '10px'}}>welcome, {data.user_by_id.nickname}</span>
                                    <Button onClick={() => {
                                        this.setState({hasLogin: false})
                                    }}>exit</Button>
                                </div>
                            );
                        }
                    }
                }
            </Query>
        )
    };

    render() {
        const { locale,language } = this.state;
        console.log('locale1',locale);
        return (
            <Router>
                <Layout style={{minHeight: '100vh'}}>
                    <Header className="header" style={{position: 'fixed', zIndex: 1, width: '100%'}}>
                        <Link to="/">
                            <div className="logo-wrapper">
                                <div className='logo'/>
                            </div>
                        </Link>
                        <Menu
                            theme="dark"
                            mode="horizontal"
                            // defaultSelectedKeys={['cloud-function']}
                            style={{lineHeight: '64px'}}
                            onClick={(e) => this.switchMenu('menuLevel1', e)}
                        >
                            <Menu.Item key="cloud-function">
                                <Link to="/cloud-function"><FormattedMessage id="Cloud Function"/></Link>
                            </Menu.Item>
                            <Menu.Item key="data-storage">
                                <Link to="/data-storage/"><FormattedMessage id="Data Storage"/></Link>
                            </Menu.Item>
                            <Menu.Item key="data-analysis">
                                <Link to="/data-analysis/"><FormattedMessage id="Data Analysis"/></Link>
                            </Menu.Item>
                            <Menu.Item key="monitor-notification">
                                <Link to="/monitor-notification/"><FormattedMessage id="Monitor Notification"/></Link>
                            </Menu.Item>
                        </Menu>

                        <div className="change-locale">
                            <Button size="small" onClick={(e)=>this.changeLocale(e)}>{language}</Button>
                        </div>

                        {/*<div className='login'>*/}
                            {/*{*/}
                                {/*this.state.hasLogin ?*/}
                                    {/*this.login(this.state.userID)*/}
                                    {/*:*/}
                                    {/*<div>*/}
                                        {/*<span style={{marginRight: 20}}>login:</span>*/}
                                        {/*<Input*/}
                                            {/*placeholder="id, eg: 'xy_1'"*/}
                                            {/*onChange={(e) => {*/}
                                                {/*// antd 获取不到 target，百度来的下面这句代码*/}
                                                {/*e.persist();*/}
                                                {/*this.setState({userID: e.target.value});*/}
                                            {/*}}*/}
                                            {/*onPressEnter={() => {*/}
                                                {/*this.setState({hasLogin: true})*/}
                                            {/*}}*/}
                                            {/*style={{width: 200}}*/}
                                        {/*/>*/}
                                    {/*</div>*/}
                            {/*}*/}
                        {/*</div>*/}
                    </Header>

                    <Sider
                        width={200}
                        style={{background: '#fff', marginTop: '64px', zIndex: '0'}}
                        collapsible
                        collapsed={this.state.collapsed}
                        onCollapse={this.onCollapse}
                    >
                        <Menu
                            theme="dark"
                            mode="inline"
                            inlineCollapsed={this.state.inlineCollapsed}
                            defaultSelectedKeys={['e-commerce']}
                            defaultOpenKeys={['trial-case']}
                            // openKeys={['cloud-function']}
                            onClick={(e) => this.switchMenu('sideBar', e)}
                            selectedKeys={[this.state.sideBar]}
                            style={{
                                borderRight: 0,
                                overflow: 'auto',
                                height: '100vh',
                                left: '0',
                                width: '200px',
                                position: 'fixed'
                            }}
                        >
                            <SubMenu key="trial-case" title={<span><Icon type="appstore" theme="twoTone"/><span>Trial Case</span></span>}>
                                <Menu.Item key="e-commerce"><Link to="/">e-commerce</Link></Menu.Item>
                                <Menu.Item key="keep accounts"><Link to="/">keep accounts</Link></Menu.Item>
                                <Menu.Item key="appointment"><Link to="/">appointment</Link></Menu.Item>
                            </SubMenu>

                            {(() => {
                                switch (this.state.menuLevel1) {
                                    case 'cloud-function':
                                        return (
                                            <SubMenu
                                                key="cloud-function"
                                                title={<span><Icon type="cloud"
                                                                   theme="twoTone"/><span>Cloud Function</span></span>}>
                                                <Menu.Item key="wechat-service">wechat-service</Menu.Item>
                                                <Menu.Item key="graphql-service">graphql-service</Menu.Item>
                                                <Menu.Item
                                                    key="quantization-service">quantization-service</Menu.Item>
                                            </SubMenu>
                                        );
                                    case 'data-storage':
                                        return (
                                            <SubMenu
                                                key="data-storage"
                                                title={<span><Icon type="database"
                                                                   theme="twoTone"/><span>Data Storage</span></span>}>
                                                <Menu.Item key="snbl-mongo">snbl-mongo</Menu.Item>
                                            </SubMenu>
                                        );
                                    case 'data-analysis':
                                        return (
                                            <SubMenu
                                                key="data-analysis"
                                                title={<span><Icon type="fund"
                                                                   theme="twoTone"/><span>data Analysis</span></span>}>
                                                <Menu.Item key="metabase">metabase</Menu.Item>
                                            </SubMenu>
                                        );
                                    case 'monitor-notification':
                                        return (
                                            <SubMenu
                                                key="monitor-notification"
                                                title={<span><Icon type="alert" theme="twoTone"/><span>Monitor Notification</span></span>}>
                                                <Menu.Item key="monitor">monitor</Menu.Item>
                                                <Menu.Item key="graphql-events">graphql-events</Menu.Item>
                                                <Menu.Item key="stock-signal">stock-signal</Menu.Item>
                                            </SubMenu>
                                        );
                                    default:
                                        return (
                                            <SubMenu
                                                key="cloud-function"
                                                title={<span><Icon type="cloud"
                                                                   theme="twoTone"/><span>Cloud Function</span></span>}>
                                                <Menu.Item key="wechat-service">wechat-service</Menu.Item>
                                                <Menu.Item key="graphql-service">graphql-service</Menu.Item>
                                                <Menu.Item
                                                    key="quantization-service">quantization-service</Menu.Item>
                                            </SubMenu>
                                        );
                                }
                            })()}
                            <SubMenu key="my-create"
                                     title={<span><Icon type="user"
                                                        theme="outlined"/><span>My Create</span></span>}>
                                <Menu.Item key="8">option9</Menu.Item>
                            </SubMenu>
                        </Menu>
                    </Sider>

                    <LocaleProvider locale={locale}>
                        <Layout style={{marginTop: '64px', zIndex: '0'}} key={locale ? locale.locale : 'en'/* Have to refresh for production environment */} >
                            <Switch>
                                <Route path="/" exact component={TrialCase}/>
                                <Route path="/cloud-function" component={CloudFunction}/>
                                <Route path="/data-storage/" component={DataStorage}/>
                                <Route path="/data-analysis/" component={DataAnalysis}/>
                                <Route path="/monitor-notification/" component={MonitorNotify}/>
                                <Redirect path="*" to="/"/>
                            </Switch>
                        </Layout>
                    </LocaleProvider>

                </Layout>
            </Router>
        );
    }
}

export default App;




