import React, {Component} from 'react';
import {Layout, Menu, Button, Spin, Icon, LocaleProvider} from 'antd';
import {BrowserRouter as Router, Route, Link, Switch, Redirect} from "react-router-dom";
import {Query} from "react-apollo";
import gql from "graphql-tag";

import moment from 'moment';
import 'moment/locale/zh-cn';
import {FormattedMessage} from 'react-intl';
import zhCN from 'antd/lib/locale-provider/zh_CN';

import WechatService from "../wechatService/WechatService";
import QuantService from "../quantService/QuantService";
import TrialCase from "../trialCase/TrialCase";
import UserCreate from "../userCreate/UserCreate";
import Login from "../login/Login";
import '../common/graphql/index.css';
import './index.css'
import Create from "../common/schema/Create";

import {SHOW_ALL_SCHEMA} from "../gql";
import axios from 'axios';
import {getCookie} from "../cookie";

//引入案例
import ShopApp from '../../case/shopApp/src/App'


axios.defaults.withCredentials = true;

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: "graphql-service",
            sideBar: "e-commerce",
            collapsed: false,
            inlineCollapsed: false,
            locale: undefined,
            language: sessionStorage.getItem("language"),
            visible: false,
            userID: ''

        };
    }

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

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

    switchMenuLevel = (menuName, value) => {
        this.setState({
            [menuName]: value,
        });
    };

    showModal = () => {
        this.setState({
            visible: true,
        });
    };

    hideModal = () => {
        this.setState({
            visible: false,
        });
    };

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

    render() {
        const {locale, language, visible} = this.state;

        return (
            <Router>
                <Layout style={{minHeight: '100vh'}}>
                    <Header className="header" style={{position: 'fixed', zIndex: 1, width: '100%'}}>
                        <Link to="/"   onClick={() => this.switchMenuLevel('menuLevel1', "graphql-service")}>
                            <div className="logo-wrapper">
                                <div className='logo'/>
                            </div>
                        </Link>
                        <Menu
                            theme="dark"
                            mode="horizontal"
                            // defaultSelectedKeys={['graphql-service']}
                            style={{lineHeight: '64px'}}
                            onClick={(e) => this.switchMenu('menuLevel1', e)}
                        >
                            <Menu.Item key="graphql-service">
                                <Link to="/graphql-service/trial-case/index"><FormattedMessage id="Graphql Service"/></Link>
                            </Menu.Item>
                            <Menu.Item key="wechat-service">
                                <Link to="/wechat-service/trial-case/index"><FormattedMessage
                                    id="Wechat Service"/></Link>
                            </Menu.Item>
                            <Menu.Item key="quantization-service">
                                <Link to="/quant-service/"><FormattedMessage id="Quantization Service"/></Link>
                            </Menu.Item>
                        </Menu>

                        <Link to="/login">
                            <Button className='login-button' type='primary' onClick={()=>this.switchMenuLevel('menuLevel1','user')} >Login</Button>
                        </Link>

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


                    {(() => {
                        switch (this.state.menuLevel1) {
                            case 'graphql-service':
                                return (
                                    <Sider
                                        width={200}
                                        style={{background: '#fff', marginTop: '64px', zIndex: '0'}}
                                        collapsible
                                        collapsed={this.state.collapsed}
                                        onCollapse={this.onCollapse}
                                    >
                                        <GraphqlSidebar inlineCollapsed={this.state.inlineCollapsed}
                                                        sideBar={this.state.sideBar} switchMenu={this.switchMenu}
                                                        userID={this.state.userID} showModal={this.showModal}/>
                                    </Sider>
                                );
                            case 'wechat-service':
                                return (
                                    <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={['wechat']}
                                            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="wechat"><Link
                                                    to="/wechat-service/trial-case/wechat case">wechat
                                                    case</Link></Menu.Item>
                                            </SubMenu>

                                            <SubMenu key="my-create"
                                                     title={<span><Icon type="user"
                                                                        theme="outlined"/><span>My Create</span></span>}>
                                                <Menu.Item key="my wechat"><Link
                                                    to="/wechat-service/my-create/my wechat">my
                                                    wechat</Link></Menu.Item>
                                            </SubMenu>
                                        </Menu>
                                    </Sider>
                                );
                            case 'quantization-service':
                                return (
                                    <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={['quant-service']}
                                            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="quant-service"><Link to="/quant-service/">quant
                                                    case</Link></Menu.Item>
                                            </SubMenu>

                                            <SubMenu key="my-create"
                                                     title={<span><Icon type="user"
                                                                        theme="outlined"/><span>My Create</span></span>}>
                                                <Menu.Item key="my quant"><Link to="/quant-service/">my
                                                    quant</Link></Menu.Item>
                                            </SubMenu>
                                        </Menu>
                                    </Sider>
                                );
                            case 'user':
                                return (
                                    <Sider
                                        width={200}
                                        style={{background: '#fff', marginTop: '64px', zIndex: '0'}}
                                        collapsible
                                        collapsed={this.state.collapsed}
                                        onCollapse={this.onCollapse}
                                    >
                                        <Menu
                                            theme="dark"
                                            defaultSelectedKeys={['cloud-settings']}
                                            onClick={(e) => this.switchMenu('sideBar', e)}
                                            selectedKeys={[this.state.sideBar]}
                                            style={{
                                                borderRight: 0,
                                                overflow: 'auto',
                                                height: '100vh',
                                                left: '0',
                                                width: '200px',
                                                position: 'fixed'
                                            }}
                                        >
                                            <Menu.Item key="account">
                                                <Icon type="setting" theme="twoTone" />
                                                <span>Account center</span>
                                                <Link to="/login/"/>
                                            </Menu.Item>

                                            <Menu.Item key="cloud-settings">
                                                <Icon type="cloud" theme="twoTone" />
                                                <span>Cloud settings</span>
                                                <Link to="/login/"/>
                                            </Menu.Item>
                                        </Menu>
                                    </Sider>
                                );
                            default:
                                return (
                                    <Sider
                                        width={200}
                                        style={{background: '#fff', marginTop: '64px', zIndex: '0'}}
                                        collapsible
                                        collapsed={this.state.collapsed}
                                        onCollapse={this.onCollapse}
                                    >
                                        <GraphqlSidebar inlineCollapsed={this.state.inlineCollapsed}
                                                        sideBar={this.state.sideBar} switchMenu={this.switchMenu}
                                                        userID={this.state.userID} showModal={this.showModal}/>
                                    </Sider>
                                );
                        }
                    })()}

                    <Create visible={visible} hideModal={this.hideModal}/>


                    <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="/graphql-service/trial-case/:case" component={TrialCase}/>
                                <Route path="/graphql-service/my-create/:case" component={UserCreate}/>
                                <Route path="/wechat-service/:sidebar/:case" component={WechatService}/>
                                <Route path="/quant-service/" component={QuantService}/>
                                <Route path="/login" component={Login}/>
                                <Redirect path="*" to="/"/>
                            </Switch>
                        </Layout>
                    </LocaleProvider>

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

export default App;

class GraphqlSidebar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userID: getCookie('user_id'),
            show: false
        }
    }

    render() {
        return (
            <Query query={gql(SHOW_ALL_SCHEMA)} variables={{user_id: this.state.userID}}>
                {
                    ({loading, error, data}) => {
                        // console.log('user schema data',data);
                        if (loading) return <Spin style={{marginLeft: 3}}/>;
                        if (error) return 'error!';
                        return (
                            <Menu
                                theme="dark"
                                mode="inline"
                                inlineCollapsed={this.props.inlineCollapsed}
                                defaultSelectedKeys={['e-commerce']}
                                defaultOpenKeys={['trial-case', 'my-create']}
                                // openKeys={['cloud-function']}
                                onClick={(e) => this.props.switchMenu('sideBar', e)}
                                selectedKeys={[this.props.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>}>
                                    {
                                        data.caseSchema.map((schema) =>
                                            <Menu.Item key={schema.schemaName}>
                                                <Link to={{
                                                    pathname: `/graphql-service/trial-case/${schema.schemaName}`,
                                                    state:{
                                                        schemaName:schema.schemaName,
                                                        schemaID:schema.id
                                                    }
                                                }}>{schema.schemaName}</Link>
                                            </Menu.Item>)
                                    }
                                </SubMenu>

                                <Menu.Item key="create-graphql" onClick={this.props.showModal}>
                                    <Icon type="edit" theme="twoTone"/>
                                    <span>Create</span>
                                    <Icon type="plus" style={{
                                        position: 'absolute',
                                        top: '35%',
                                        right: '6px',
                                        color: 'white'
                                    }}/>
                                </Menu.Item>

                                <SubMenu key="my-create" title={<span><Icon type="user" theme="outlined"/><span>My Create</span></span>}>
                                    {
                                        data.userSchema.map((schema) =>
                                            <Menu.Item key={schema.schemaName}>
                                                <Link to={{
                                                    pathname: `/graphql-service/my-create/${schema.schemaName}`,
                                                    state:{
                                                        schemaName:schema.schemaName,
                                                        schemaID:schema.id
                                                    }
                                                }}>{schema.schemaName}</Link>
                                            </Menu.Item>)
                                    }
                                </SubMenu>
                            </Menu>

                        )
                    }
                }
            </Query>
        )
    }
}

// this.state.show ?
// :''