import React, {Component} from 'react';
import {Layout, Menu, Button, Spin, Icon, LocaleProvider, Dropdown, Avatar, Badge} 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";
import UserCreate from "./graphqlService/UserCreate";
import WxTrialCase from "./wechatService/WxTrialCase";
import WxUserCreate from "./wechatService/WxUserCreate";
import Login from "../../login/Login";
import Ticket from '../../ticket/Ticket';
import './graphqlService/component/graphql/index.css';
import './index.css'
import Create from "./graphqlService/component/schema/Create";
import WxCreate from "./wechatService/wxCreate/WxCreate";

import {CASE_AND_PROJECT, GET_USER} from "../../gql";
import axios from 'axios';
import {getCookie, setCookie} from "../../cookie";
import {logoutUrl} from "../../config";
import Graphiql from "./common/Graphiql";

axios.defaults.withCredentials = true;

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

class DevelopVersion 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,
            userID: '',
            avatar: ''
        };
    }

    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]});
            }
        }

        let userID = getCookie('user_id');
        if (userID === undefined || '') {
            axios.get(this.state.getIdUrl)
                .then((res) => {
                    if (res.data !== '') {
                        setCookie("user_id", res.data);
                        this.setState({
                            userID: res.data
                        })
                    }
                })
                .catch(function (err) {
                    console.log(err);
                });
        } else {
            this.setState({
                userID
            })
        }
    }

    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;
        console.log(language);
        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 (
            <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="/developer/graphql-service/trial-case/index"><FormattedMessage
                                id="Graphql Service"/></Link>
                        </Menu.Item>
                        <Menu.Item key="wechat-service">
                            <Link to="/developer/wechat-service/trial-case/index"><FormattedMessage
                                id="Wechat Service"/></Link>
                        </Menu.Item>
                        <Menu.Item key="quant-service">
                            <Link to="/developer/quant-service/trial-case/index"><FormattedMessage id="Quantization Service"/></Link>
                        </Menu.Item>
                    </Menu>

                    {
                        this.state.userID === '' ?
                            <Link to="/login">
                                <Button className='login-button' type='primary'
                                        onClick={() => this.switchMenuLevel('menuLevel1', 'user')}>
                                    <FormattedMessage id="Login"/></Button>
                            </Link>
                            :
                            <User
                                userID={this.state.userID}
                                languageButton={this.state.languageButton}
                                changeLocale={this.changeLocale}
                                switchMenuLevel={this.switchMenuLevel}
                            />
                    }

                </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={['quant-service']}
                                        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><FormattedMessage id="Case Show"/></span></span>}>
                                            <Menu.Item key="quant-service">
                                                <Link to="/developer/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><FormattedMessage id="Instructions"/></span>
                                            </a>
                                        </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="/developer" exact component={TrialCase}/>
                            <Route path="/developer/graphql-service/trial-case/:case" component={TrialCase}/>
                            <Route path="/developer/graphql-service/my-create/:case" component={UserCreate}/>
                            <Route path="/developer/wechat-service/trial-case/:case" component={WxTrialCase}/>
                            <Route path="/developer/wechat-service/my-create/:case" component={WxUserCreate}/>
                            <Route path="/developer/quant-service/:sidebar/:case" component={QuantService}/>
                            <Route path="/developer/login/:setting" component={Login}/>
                            <Route path="/developer/login" component={Login}/>
                            <Route path="/developer/ticket" component={Ticket}/>
                            <Route path="/developer/graphiql" component={Graphiql}/>
                            <Redirect path="*" to="/"/>
                        </Switch>
                    </Layout>
                </LocaleProvider>
            </Layout>
        );
    }
}

export default DevelopVersion;

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

    render() {
        return (
            <Query query={gql(CASE_AND_PROJECT)} variables={{projectType: 'graphql', user_id: this.state.userID}}>
                {
                    ({loading, error, data}) => {
                        if (loading) return (
                            <Menu
                                theme="dark"
                                mode="inline"
                                style={{
                                    borderRight: 0,
                                    overflow: 'auto',
                                    height: '100vh',
                                    left: '0',
                                    width: '200px',
                                    position: 'fixed'
                                }}
                            >
                                <Menu.Item >
                                    <Icon type="loading" />
                                    <span><FormattedMessage id="loading"/></span>
                                </Menu.Item>
                            </Menu>
                        );
                        if (error) return 'error!';
                        // console.log('CASE_AND_PROJECT data', data);
                        data.caseProject.forEach((project) => {
                            switch (project.schema_id.schemaName) {
                                case 'ecommerce' :
                                    localStorage.setItem('ecommerce', project.schema_id.schemaData);
                                    break;
                                case 'order':
                                    localStorage.setItem('order', project.schema_id.schemaData);
                                    break;
                                case 'bills':
                                    localStorage.setItem('bills', project.schema_id.schemaData);
                                    break;
                                default:
                                    break;
                            }
                        });
                        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><FormattedMessage
                                        id="Case Show"/></span></span>}>
                                    {
                                        data.caseProject.map((project) =>
                                            <Menu.Item key={project.projectName}>
                                                <Link to={{
                                                    pathname: `/developer/graphql-service/trial-case/${project.projectName}`,
                                                    state: {
                                                        schemaName: project.projectName,
                                                        schemaID: project.schema_id.id,
                                                        projectID: project.id
                                                    }
                                                }}><FormattedMessage id={project.projectName}/></Link>
                                            </Menu.Item>)
                                    }
                                </SubMenu>

                                <Menu.Item key="create-graphql" onClick={this.props.showModal}>
                                    <Icon type="edit" theme="twoTone"/>
                                    <span><FormattedMessage id="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><FormattedMessage
                                        id="My Create"/></span></span>}>
                                    {
                                        data.project.map((project) =>
                                            <Menu.Item key={project.projectName}>
                                                <Link to={{
                                                    pathname: `/developer/graphql-service/my-create/${project.projectName}`,
                                                    state: {
                                                        schemaName: project.projectName,
                                                        schemaID: project.schema_id.id,
                                                        projectID: project.id
                                                    }
                                                }}>{project.projectName}</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><FormattedMessage id="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(CASE_AND_PROJECT)} variables={{projectType: 'wx', user_id: this.state.userID}}>
                {
                    ({loading, error, data}) => {
                        // console.log('CASE_WXCONFIG_AND_PROJECT data', data);
                        if (loading) return (
                            <Menu
                                theme="dark"
                                mode="inline"
                                style={{
                                    borderRight: 0,
                                    overflow: 'auto',
                                    height: '100vh',
                                    left: '0',
                                    width: '200px',
                                    position: 'fixed'
                                }}
                            >
                                <Menu.Item >
                                    <Icon type="loading" />
                                    <span><FormattedMessage id="loading"/></span>
                                </Menu.Item>
                            </Menu>
                        );
                        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><FormattedMessage id="Case Show"/></span>
                                </span>}>
                                    {
                                        data.caseProject.map((project) => {
                                            if (project) {
                                                let appName = project.projectName;
                                                let configID = project.wxConfig_id.id;
                                                let projectID = project.id;
                                                return (
                                                    <Menu.Item key={appName}>
                                                        <Link to={{
                                                            pathname: `/developer/wechat-service/trial-case/${appName}`,
                                                            state: {
                                                                appName,
                                                                configID,
                                                                projectID
                                                            }
                                                        }}><FormattedMessage id={appName}/></Link>
                                                    </Menu.Item>
                                                )
                                            }
                                            return false;
                                        })
                                    }
                                </SubMenu>

                                <Menu.Item key="create-config" onClick={this.props.wxShowModal}>
                                    <Icon type="edit" theme="twoTone"/>
                                    <span><FormattedMessage id="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><FormattedMessage id="My Create"/></span>
                                </span>}>
                                    {
                                        data.project.map((project) => {
                                            if (project) {
                                                let appName = project.projectName;
                                                let configID = project.wxConfig_id.id;
                                                let projectID = project.id;
                                                return (
                                                    <Menu.Item key={appName}>
                                                        <Link to={{
                                                            pathname: `/developer/wechat-service/my-create/${appName}`,
                                                            state: {
                                                                appName,
                                                                configID,
                                                                projectID
                                                            }
                                                        }}>{appName}</Link>
                                                    </Menu.Item>
                                                )
                                            }
                                            return false;
                                        })
                                    }
                                </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><FormattedMessage id="Instructions"/></span>
                                    </a>
                                </Menu.Item>

                            </Menu>

                        )
                    }
                }
            </Query>
        )
    }
}

class User extends Component {
    constructor(props) {
        super(props);
        this.state = {
            show: false
        }
    }

    logout = () => {

        axios.get(logoutUrl)
            .then((res) => {
               console.log('logout success',res);
                setCookie("user_id", '');
            })
            .catch((err) => {
        });
    };

    render() {
        return (
            <Query query={gql(GET_USER)} variables={{id: this.props.userID}}>
                {
                    ({loading, error, data}) => {
                        if (loading) {
                            return <Spin style={{marginLeft: 3}}/>
                        }
                        if (error) {
                            return 'error!';
                        }
                        let user = data.user_by_id;
                        if (user !== null) {
                            const menu = (
                                <Menu className={'user-detail'}>
                                    <Menu.Item className={'user-info'}>
                                        <p className={'user-info-nickname'}>{user.nickname}</p>
                                        <p className={'user-info-email'}>{user.email}</p>
                                    </Menu.Item>
                                    <Menu.Item>
                                        <a href='https://www.ioobot.com' onClick={(e) => {
                                            e.preventDefault();
                                            this.props.changeLocale(e)
                                        }}>{this.props.languageButton}</a>
                                    </Menu.Item>
                                    <Menu.Item>
                                        <Link to="/login">
                                            <div>
                                                <FormattedMessage id="Account center"/>
                                            </div>
                                        </Link>
                                    </Menu.Item>
                                    <Menu.Item>
                                        <Link to="/ticket">
                                            <div>
                                                <FormattedMessage id="Submit Support Ticket"/>
                                            </div>
                                        </Link>
                                    </Menu.Item>
                                    <Menu.Item className={'login-out'}>
                                        <a href='https://www.ioobot.com' onClick={(e) => {
                                            e.preventDefault();
                                            this.logout();
                                        }}><FormattedMessage id="exit"/></a>
                                    </Menu.Item>
                                </Menu>
                            );
                            return (
                                <div className='login-nickname' onClick={()=>{}}>
                                    <Dropdown overlay={menu} placement="bottomRight" trigger={['click']}>
                                        <div>
                                            <span style={{ marginRight: 5 }}>
                                                <Badge dot><Avatar shape="user" icon="user" /></Badge>
                                            </span>
                                            {/*<Icon type="down" />*/}
                                        </div>
                                    </Dropdown>
                                </div>
                            )
                        }
                    }
                }
            </Query>
        )
    }
}