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 QuantService from "./quantService/QuantService";
import TrialCase from "./graphqlService/trialCase/TrialCase";
import UserCreate from "./graphqlService/userCreate/UserCreate";
import WXTrialCase from "./wechatService/wxTrialCase/WXTrialCase";
import WXUserCreate from "./wechatService/wxUserCreate/WXUserCreate";
import Login from "../login/Login";
import './graphqlService/common/graphql/index.css';
import './index.css'
import Create from "./graphqlService/common/schema/Create";
import WxCreate from "./wechatService/wxCreate/WxCreate";


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

axios.defaults.withCredentials = true;

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

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            menuLevel1: "graphql-service",
            sideBar: "ecommerce",
            collapsed: false,
            inlineCollapsed: false,
            language: props.language,
            locale: props.language === "中文" ? zhCN : undefined,
            languageButton: props.language === "中文" ? "English" : "中文",
            visible: false,
            wxVisible: false
        };
    }

    componentWillMount() {
        let urlList = window.location.pathname.split("/");
        let urlListLength = urlList.length;
        if (urlListLength > 2) {
            this.setState({menuLevel1: urlList[1]});
            if (urlList[3] !== 'index') {
                this.setState({sideBar: urlList[3]});
            }
        }
    }

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

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

    switchMenuTab = (menuName, e) => {
        this.setState({
            [menuName]: e.key,
        });
        if (e.key === "graphql-service") {
            this.setState({sideBar: "ecommerce"});
        }
    };

    switchSidebar = (value) => {
        this.setState({
            sideBar: value,
        });
    };

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

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

    wxShowModal = () => {
        this.setState({
            wxVisible: true,
        });
    };

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

    wxHideModal = () => {
        this.setState({
            wxVisible: false,
        });
    };

    changeLocale = (e) => {
        e.stopPropagation();
        let {language} = this.state;
        // console.log('app language',language);
        let changeLanguage = language === "中文" ? "English" : "中文";
        let local = language === "中文" ? undefined : zhCN;
        let languageButton = language === "中文" ? "中文" : "English";

        sessionStorage.setItem("language", changeLanguage);
        this.props.changeLanguage(changeLanguage);
        this.setState({
            language: changeLanguage,
            locale: local,
            languageButton: languageButton
        });
        if (!local) {
            moment.locale('en');
        } else {
            moment.locale('zh-cn');
        }
    };

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

        return (
            <Router>
                <Layout style={{minHeight: '100vh'}}>
                    <Header className="header" style={{position: 'fixed', zIndex: 1, width: '100%'}}>
                        <Link to="/"
                              onClick={() => this.setState({menuLevel1: "graphql-service", sideBar: "ecommerce"})}>
                            <div className="logo-wrapper">
                                <div className='logo'/>
                            </div>
                        </Link>
                        <Menu
                            theme="dark"
                            mode="horizontal"
                            selectedKeys={[this.state.menuLevel1]}
                            style={{lineHeight: '64px'}}
                            onClick={(e) => this.switchMenuTab('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="quant-service">
                                <Link to="/quant-service/trial-case/index"><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)}>{languageButton}</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}
                                                        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}
                                    >
                                        <WxConfigSiderbar inlineCollapsed={this.state.inlineCollapsed}
                                                          sideBar={this.state.sideBar} switchMenu={this.switchMenu}
                                                          wxShowModal={this.wxShowModal}/>
                                    </Sider>
                                );
                            case 'quant-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>Case Show</span></span>}>
                                                <Menu.Item key="quant-service">
                                                    <Link to="/quant-service/trial-case/quant case">quant case</Link>
                                                </Menu.Item>
                                            </SubMenu>

                                            <Menu.Item key="instructions">
                                                <a href="https://ioobot-document.netlify.com/" title="instructions"
                                                   target="instructions">
                                                    <Icon type="file-text" theme="twoTone"/>
                                                    <span>Instructions</span>
                                                </a>
                                            </Menu.Item>
                                        </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/account"/>
                                            </Menu.Item>

                                            <Menu.Item key="cloud-settings">
                                                <Icon type="cloud" theme="twoTone"/>
                                                <span>Cloud settings</span>
                                                <Link to="/login/cloud"/>
                                            </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}
                                                        showModal={this.showModal}/>
                                    </Sider>
                                );
                        }
                    })()}
                    <Create visible={visible} hideModal={this.hideModal} switchSidebar={this.switchSidebar}/>
                    <WxCreate visible={wxVisible} hideModal={this.wxHideModal} switchSidebar={this.switchSidebar}/>

                    <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/trial-case/:case" component={WXTrialCase}/>
                                <Route path="/wechat-service/my-create/:case" component={WXUserCreate}/>
                                <Route path="/quant-service/:sidebar/:case" component={QuantService}/>
                                <Route path="/login/:setting" component={Login}/>
                                <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'),
        }
    }

    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!';
                        localStorage.setItem('ecommerce', data.caseSchema.find(obj => obj.schemaName === 'ecommerce').schemaData);
                        localStorage.setItem('subscribe', data.caseSchema.find(obj => obj.schemaName === 'subscribe').schemaData);
                        localStorage.setItem('bills', data.caseSchema.find(obj => obj.schemaName === 'bills').schemaData);
                        return (
                            <Menu
                                theme="dark"
                                mode="inline"
                                inlineCollapsed={this.props.inlineCollapsed}
                                defaultSelectedKeys={['ecommerce']}
                                defaultOpenKeys={['trial-case', 'my-create']}
                                // openKeys={['trial-case', 'my-create']}
                                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>Case Show</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.Item key="instructions">
                                    <a href="https://ioobot-document.netlify.com/" title="instructions" target="_blank"
                                       rel="noopener noreferrer">
                                        <Icon type="file-text" theme="twoTone"/>
                                        <span>Instructions</span>
                                    </a>
                                </Menu.Item>

                            </Menu>

                        )
                    }
                }
            </Query>
        )
    }
}

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

    render() {
        return (
            <Query query={gql(SHOW_ALL_WXCONFIG)} variables={{user_id: this.state.userID}}>
                {
                    ({loading, error, data}) => {
                        if (loading) return <Spin style={{marginLeft: 3}}/>;
                        if (error) return 'error!';
                        return (
                            <Menu
                                theme="dark"
                                mode="inline"
                                inlineCollapsed={this.props.inlineCollapsed}
                                defaultSelectedKeys={['my-wechat']}
                                defaultOpenKeys={['trial-case', 'my-create']}
                                // openKeys={['trial-case', 'my-create']}
                                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>Case Show</span></span>}>
                                    {
                                        data.caseWxConfig.map((config) =>
                                            <Menu.Item key={config.appName}>
                                                <Link to={{
                                                    pathname: `/wechat-service/trial-case/${config.appName}`,
                                                    state: {
                                                        appName: config.appName,
                                                        configID: config.id
                                                    }
                                                }}>{config.appName}</Link>
                                            </Menu.Item>)
                                    }
                                </SubMenu>

                                <Menu.Item key="create-config" onClick={this.props.wxShowModal}>
                                    <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.userWxConfig.map((config) =>
                                            <Menu.Item key={config.appName}>
                                                <Link to={{
                                                    pathname: `/wechat-service/my-create/${config.appName}`,
                                                    state: {
                                                        appName: config.appName,
                                                        configID: config.id
                                                    }
                                                }}>{config.appName}</Link>
                                            </Menu.Item>)
                                    }
                                </SubMenu>

                                <Menu.Item key="instructions">
                                    <a href="https://ioobot-document.netlify.com/" title="instructions" target="_blank"
                                       rel="noopener noreferrer">
                                        <Icon type="file-text" theme="twoTone"/>
                                        <span>Instructions</span>
                                    </a>
                                </Menu.Item>

                            </Menu>

                        )
                    }
                }
            </Query>
        )
    }
}