import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { utils, LocationParam } from 'amos-tool';
import classlist from 'dt2react/lib/class/classList2';
import isDev from 'ray-visutil/lib/env';
import { GlobalConfig } from '@gm/graphmod-utils';

function toggleBodyTheme(toggle, cls) {
  if (toggle) {
    cls.forEach(i => {
      classlist(document.body).add(i);
    });
  } else {
    cls.forEach(i => {
      classlist(document.body).remove(i);
    });
  }
}


/**
 * 初始化组件需要获取的系统应用的全局信息
 * @param {Object} param
 * @param {Object} param.testOauthConfig
 * @param {Object} param.testRouteState
 * @param {Object} param.testDataConfig
 * @param {Object} param.testVisualParams
 * @param {Function} param.toolbar 顶部导航条，(props, ) => ReactNode
 * @param {*} isExcueGloabMethod
 * @returns
 */
export default function connectGlobalPage({ system, testOauthConfig, testRouteState, testDataConfig, testVisualParams, toolbar } = {}, isExcueGloabMethod) {
  return function (WrappedComponent) {
    class WithGlobalComponent extends Component {
      constructor(props) {
        super(props);
        this.init();
      }

      getChildContext() {
        let { appConfig, visualParams = {} } = this.props;
        const { browserHistory, token } = appConfig || {};
        return {
          browserHistory: {
            ...browserHistory ? browserHistory : {},
            goBack: () => {
              const browserHistoryIntercept = GlobalConfig.getCustomData('browserHistoryIntercept');
              // 页面全局跳转拦截器
              if (browserHistoryIntercept) {
                browserHistoryIntercept(() => {
                  browserHistory.goBack();
                });
              } else {
                browserHistory.goBack();
              }
            },
            push: (data) => {
              console.log('跳转信息:', data);
              if (!browserHistory || !browserHistory.push) {
                return;
              }

              let paramsdata = null;
              if (utils.isObject(data)) {
                let path = location.pathname;
                const params = LocationParam.getLocationParams();
                const pathList = (data.pathname || '').split('?');
                let newPath = pathList[0];
                newPath = newPath.replace('vizmixpub', 'mixuap');
                if (path.endsWith(newPath)) {
                  newPath = path;
                }
                if (newPath) {
                  let search = '';
                  if (pathList[1]) {
                    search = pathList[1];
                    if (data.search) {
                      // 处理业务组件被当做amos或者studio的模块使用
                      if (params.lfrom) {
                        search = `${search}&lfrom=${params.lfrom}&${data.search}&token=${token}`;
                      } else {
                        search = `${search}&${data.search}&token=${token}`;
                      }
                    } else {
                      if (search) {
                        // 处理业务组件被当做amos或者studio的模块使用
                        if (params.lfrom) {
                          search = `?${search}&lfrom=${params.lfrom}&token=${token}`;
                        } else {
                          search = `?${search}&token=${token}`;
                        }
                      } else {
                        search = data.search;
                      }
                    }
                  }
                  paramsdata = {
                    pathname: newPath.replace('vizmixpub', 'mixuap'),
                    state: data.state,
                    search: utils.isEmpty(search) ? `?token=${token}` : search
                  };
                }
              } else {
                paramsdata = data;
              }
              // 页面全局跳转拦截器
              const browserHistoryIntercept = GlobalConfig.getCustomData('browserHistoryIntercept');
              if (browserHistoryIntercept) {
                browserHistoryIntercept(() => {
                  paramsdata && browserHistory.push(paramsdata);
                });
              } else {
                paramsdata && browserHistory.push(paramsdata);
              }
            }
          },
          imgThemeUrl: (url) => {
            if (!isDev) {
              testVisualParams = {};
            }
            visualParams = { ...testVisualParams || {}, ...visualParams || {} };
            if (visualParams.theme) {
              const list = [
                (url || '').substring(0, (url || '').lastIndexOf('.')),
                (url || '').substring((url || '').lastIndexOf('.') + 1)
              ];
              return `${list[0]}_${visualParams.theme}.${list[1]}`;
            }
            return url;
          },
          theme: isDev ? (testVisualParams || {}).theme : (visualParams || {}).theme
        };
      }

      componentDidMount() {
        this.cls = [];
        let { visualParams = {} } = this.props;
        if (!isDev) {
          testVisualParams = {};
        }
        visualParams = { ...testVisualParams, ...visualParams };
        const prefix = system ? `${system}-` : '';
        const suffix = visualParams.theme ? `-theme-${visualParams.theme}` : '';
        const cls1 = visualParams.theme ?
          `${prefix}custom${suffix}` : '';
        const cls2 = visualParams.theme ?
          `${prefix}gmcommon${suffix}` : '';
        const cls3 = visualParams.theme ?
          `${prefix}graph${suffix}` : '';
        this.cls.push(cls1);
        this.cls.push(cls2);
        this.cls.push(cls3);
        toggleBodyTheme(true, this.cls);
      }

      componentWillUnmount() {
        toggleBodyTheme(false, this.cls);
      }

      /**
       * 初始化组件需要获取的系统应用的全局信息
       */
      init = () => {
        const { appConfig, dataConfig } = this.props;
        const { browserHistory, pubSub, $router, ...other } = appConfig || {};
        const { URI } = dataConfig || {};
        console.log('--------->', browserHistory, URI);

        if (!other) {
          return;
        }
        GlobalConfig.setRequestHeader(other);
        GlobalConfig.setURI(URI);
        GlobalConfig.setCustomData('pubSub', pubSub);
        isExcueGloabMethod && GlobalConfig.execuAllInitialMethod();

      }

      render() {
        const props = { ...this.props };

        let { children, oauthConfig = {}, dataConfig, routeState, style, visualParams = {} } = props;

        if (!isDev) {
          testOauthConfig = {};
          testRouteState = {};
          testDataConfig = {};
          testVisualParams = {};
        }

        let newAuthConfig = {};
        Object.keys(oauthConfig || {}).forEach(e => {
          if (oauthConfig[e].hasPermission) {
            newAuthConfig[e] = true;
          }
          return e;
        });

        oauthConfig = { ...testOauthConfig || {}, ...newAuthConfig || {} };
        routeState = { ...testRouteState || {}, ...routeState || {} };
        dataConfig = { ...testDataConfig || {}, ...style || {}, ...dataConfig || {} };
        visualParams = { ...testVisualParams, ...visualParams };

        const newProps = {
          ...props,
          visualParams,
          dataConfig,
          oauthConfig,
          routeState
        };

        const header = toolbar ? toolbar(newProps) : null;
        const prefix = system ? `${system}-` : '';
        const suffix = visualParams.theme ? `-theme-${visualParams.theme}` : '';
        const cls = visualParams.theme ?
          `${prefix}custom${suffix} ${prefix}gmcommon${suffix} ${prefix}graph${suffix}` : '';
        return (
          <div className={cls} style={{ width: visualParams.width, height: visualParams.height }}>
            {header}
            <WrappedComponent {...newProps}>
              {children}
            </WrappedComponent>
          </div>
        );
      }
    }

    WithGlobalComponent.propTypes = {
      children: PropTypes.any,
      appConfig: PropTypes.object,
      dataConfig: PropTypes.object,
      visualParams: PropTypes.object
    };

    WithGlobalComponent.childContextTypes = {
      browserHistory: PropTypes.object,
      imgThemeUrl: PropTypes.func,
      theme: PropTypes.string
    };

    return WithGlobalComponent;
  };
}
