import React, {Component} from 'react';
import {FormattedMessage} from 'react-intl';
import {Route, Link, Switch, Redirect} from "react-router-dom";
import {Layout, Menu, Button, Spin, Icon, LocaleProvider, Dropdown, Avatar, Badge} from 'antd';

import '../developVersion/index.css';
import CaseShow from "./caseShow/CaseShow";
import MyDeploy from "./myDeploy/MyDeploy";
import Communication from "./communication/Communication";
import {logoutUrl} from "../../config";
import {getCookie, setCookie} from "../../cookie";
import {GET_USER} from "../../gql";

import {Query} from "react-apollo";
import gql from "graphql-tag";
import axios from 'axios';
import moment from 'moment';
import 'moment/locale/zh-cn';
import zhCN from 'antd/lib/locale-provider/zh_CN';
axios.defaults.withCredentials = true;
const {Header, Content} = Layout;

class BasicVersion extends Component {
    constructor(props) {
        super(props);
        this.state = {
            menuLevel1: "example",
            language: props.language,
            locale: props.language === "中文" ? zhCN : undefined,
            languageButton: props.language === "中文" ? "English" : "中文",
            userID: '',
            avatar: ''
        };
        // console.log('BasicVersion props',props);
        if(props.location) {
            let tabMenu = props.location.pathname.split('/')[2] || 'example';
            // console.log('tabMenu',tabMenu);
            switch(tabMenu) {
                case 'deploy':
                    this.state.menuLevel1 = 'my-deploy';
                    break;
                case 'communication':
                    this.state.menuLevel1 = 'communication';
                    break;
                default:
                    this.state.menuLevel1 = 'example';
                    break;
            }
        }
    }

    componentWillReceiveProps(props){
        if(props.location) {
            let tabMenu = props.location.pathname.split('/')[2] || 'example';
            // console.log('tabMenu1',tabMenu);
            switch(tabMenu) {
                case 'deploy':
                    this.setState({menuLevel1: 'my-deploy'});
                    break;
                case 'communication':
                    this.setState({menuLevel1: 'communication'});
                    break;
                default:
                    this.setState({menuLevel1: 'example'});
                    break;
            }
        }
    }

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

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

    componentWillMount() {
        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
            })
        }
    }

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

    changeTabBar = (menu) => {
        this.setState({
            menuLevel1: menu
        })
    };

    render() {
        let ownProps = {
            changeTabBar: this.changeTabBar
        };

        let ownPropsUser = {
            changeLocale: this.changeLocale,
            languageButton: this.state.languageButton
        };

        const PrivateRoute = ({component: Component, ownProps, ...rest}) => (
            <Route {...rest} render={(props) => {
                return <Component {...ownProps} {...props}/>
            }}/>
        );

        return (
            <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"
                        style={{lineHeight: '64px'}}
                        selectedKeys={[this.state.menuLevel1]}
                        onClick={(e) => this.switchMenuTab('menuLevel1', e)}
                    >
                        <Menu.Item key="example">
                            <Link to="/common/example"><FormattedMessage id="Example"/></Link>
                        </Menu.Item>
                        {
                            !!this.state.userID?
                                <Menu.Item key="my-deploy">
                                    <Link to="/common/deploy"><FormattedMessage id="My deploy"/></Link>
                                </Menu.Item>
                                :
                                ''
                        }

                        <Menu.Item key="communication">
                            <Link to="/common/communication"><FormattedMessage id="Communication"/></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}
                                history={this.props.history}
                            />
                    }

                </Header>

                <Layout style={{marginTop: '64px', zIndex: '0'}}>
                    <Switch>
                        <Route path="/common" exact component={CaseShow}/>
                        <Route path="/common/example" exact component={CaseShow}/>
                        <Route path="/common/deploy" component={MyDeploy}/>
                        <Route path="/common/communication" component={Communication}/>
                    </Switch>
                </Layout>

            </Layout>
        )
    }
}

export default BasicVersion;


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 className='login-nickname'/>
                        }
                        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="/common/communication">
                                            <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();
                                            this.props.history.push({
                                                pathname: '/'
                                            })
                                        }}><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>
                            )
                        }
                        return null;
                    }
                }
            </Query>
        )
    }
}