/**
 * Created by 叶子 on 2017/8/13.
 * 所有路由的入口
 */
import React, { Component } from 'react';
import { Redirect, Route, Switch } from 'react-router-dom';
import DocumentTitle from 'react-document-title';
import Components from '../components';
import AllPages from '../pages';
import routesConfig from './config';
import { getStateUri, qyWxOauthUrl, qyWxQrCodeUri } from '../const';
import { queryString } from '../utils';
import * as PropTypes from 'prop-types';
import { Modal, Skeleton } from 'antd';
import { browserType, BrowType } from '../utils/BrowserUtils';

let AllComponents = { ...Components, ...AllPages };
export default class CRouter extends Component {

    static propTypes = {
        auth: PropTypes.object,
    };

    constructor(props) {
        super(props);
        this.state = {
            isLoading: false,
            modal: {
                title: '',
                visible: false,

            },
        };
        this.browser = browserType();
        console.log('props=>', props);
    }

    /**
     * 暂时不管权限
     **/
    requireAuth = (permission, component) => {
        // const { auth } = this.props;
        // const { permissions } = auth.data;
        // if (!permissions || !permissions.includes(permission)) return <Redirect to={'404'}/>;
        return component;
    };


    requireWxOauth = (component, permission, info) => {
        let params = queryString();
        this.requestQywxUser(params, info)
            .then(() => undefined);
        return null;
    };


    requireLogin = (component, permission, info) => {
        const { auth } = this.props;
        const { user } = auth.data;
        if (!user) {
            return <Redirect to={'/login'}/>;
            // return this.requireWxOauth(component, permission, info);
        }
        return (!permission && permission === 'none') ? component : this.requireAuth(permission, component);
    };


    /**
     * 判断如果是微信或者是企业微信或者是企业微信端，则默认用Oauth静默登录
     * 如果是其它浏览器，特别是PC，则考虑用扫码登录
     * */
    async requestQywxUser(params, info) {
        this.setState({ isLoading: true });
        let { code, state, appid } = params;
        let path = getStateUri(state);
        let _this = this;
        this.props.setAlitaState({ funcName: 'qywxUserInfo', params: { code, appid } })
            .then(({ data: resp }) => {
                console.log('resp=>', resp, path);
                if (resp.code === 0) {
                    _this.props.setAlitaState({ stateName: 'auth', data: { user: resp.data } });
                    _this.setState({ isLoading: false });
                } else if (resp.code === 40029) {
                    if (_this.browser === BrowType.WX || _this.browser === BrowType.WXWORK) {
                        window.location.href = qyWxOauthUrl(info.key);
                    } else {
                        window.location.href = qyWxQrCodeUri(info.key);
                    }
                } else {
                    Promise.reject({ message: resp.message });
                }
            })
            .catch(e => {
                console.log('error=>', e);
                Modal.confirm({
                    title: '错误',
                    content: '请求用户信息错误，请重试！',
                    onOk() {
                        _this.requestQywxUser(params);
                    },
                    onCancel() {
                        window.location.href = '/';
                    },
                });
            });
    };

    render() {
        let { isLoading, modal } = this.state;
        console.log('isLoading', isLoading, modal);
        return (
            <Skeleton loading={isLoading}>
                <Switch>
                    {Object.keys(routesConfig).map(key =>
                        routesConfig[key].map(r => {
                            const route = r => {
                                let Component;
                                let component = r.component;
                                if (typeof component == 'string') {
                                    Component = AllComponents[r.component];
                                } else {
                                    Component = component;
                                }
                                return (
                                    <Route
                                        key={r.route || r.key}
                                        exact
                                        path={r.route || r.key}
                                        render={props => {
                                            const reg = /\?\S*/g;
                                            // 匹配?及其以后字符串
                                            const queryParams = window.location.hash.match(reg);
                                            // 去除?的参数
                                            const { params } = props.match;
                                            Object.keys(params).forEach(key => {
                                                params[key] =
                                                    params[key] && params[key].replace(reg, '');
                                            });
                                            props.match.params = { ...params };
                                            const merge = {
                                                ...props,
                                                query: queryParams
                                                    ? queryString.parse(queryParams[0])
                                                    : {},
                                            };
                                            // 重新包装组件
                                            const wrappedComponent = (
                                                <DocumentTitle title={r.title}>
                                                    <Component {...merge} />
                                                </DocumentTitle>
                                            );
                                            return r.login
                                                ? wrappedComponent
                                                : this.requireLogin(wrappedComponent, r.auth, r);
                                        }}
                                    />
                                );
                            };
                            return r.component ? route(r) : r.subs.map(r => route(r));
                        }),
                    )}
                    <Route render={() => <Redirect to="/404"/>}/>
                </Switch>
            </Skeleton>
        );
    }
}
