import React from 'react';
import ReactDOM from 'react-dom';
import {
  Router,
  useRouterHistory,
} from 'react-router';
import {
  createHashHistory,
} from 'History';
import {
  Provider,
} from 'mobx-react';
import {
  RouterStore,
  syncHistoryWithStore,
} from 'mobx-react-router';
import {
  WeaLocaleProvider,
  WeaTools,
} from 'ecCom';
import {
  Login,
  Theme,
  store as portalThemeStore,
} from 'weaPortalTheme';
import LibRoute from '../../pc4public/amain/LibRoute';
import {
  checkCasIsDeployed,
} from '../../pc4backstage/integration/apis/CommonService';

const libRouteTool = new LibRoute('main');
window.libRouteLoaded = libRouteTool.libRouteLoaded;

const browserHistory = useRouterHistory(createHashHistory)({
  queryKey: '_key',
  basename: '/',
});

const routingStore = new RouterStore();

const history = syncHistoryWithStore(browserHistory, routingStore);
window.weaHistory = history;

const getLocaleLabel = WeaLocaleProvider.getLocaleLabel.bind(this, 'theme');
function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}
const checkCasForLogin = (nextState, replace, callback) => {
  const path = `${window.location.protocol}//${window.location.host}${window.location.pathname}${window.location.search}#/main`;
  WeaTools.checkSSO('', false).then(() => {
    if (!/.*appid=.*&service=.*/.test(window.location.href) && !window.loadCas) {
      // window.loadCas = true

      checkCasIsDeployed().then((res) => {
        if (!res.hasSession && res.isDeployed && res.weaver_login_type !== 'OALogin') {
          if (/\/spa\/portal\/public\/index\.html#\/licensesubmit\?display=page/.test(window.location.href)) {
            getLocaleLabel(nextState, replace, callback);
          } else {
            let service = `${window.location.protocol}//${window.location.host}${window.ecologyContentPath || ''}/wui/cas-entrance.jsp?path=${encodeURIComponent(path)}&ssoType=${res.ssoType}`;
            if(getQueryVariable("languid")){
              service = `${window.location.protocol}//${window.location.host}${window.ecologyContentPath || ''}/wui/cas-entrance.jsp?languid=${getQueryVariable("languid")}&path=${encodeURIComponent(path)}&ssoType=${res.ssoType}`;
            }
            window.localStorage["casPath"] = service;
            window.location.href = service;
          }
        } else {
          getLocaleLabel(nextState, replace, callback);
        }
      });
    } else {
      window.localStorage.removeItem('casPath');
      getLocaleLabel(nextState, replace, callback);
    }
  });
};

const onEnter = (nextState, replace, callback) => {
  WeaTools.checkSSO('', false).then(() => {
    getLocaleLabel(nextState, replace, callback);
  });
};

const libs = [
  // [eventRegister, lib, route]
  ['f_portal', 'weaPortal', 'portal'], // 门户
  ['f_workflow', 'weaWorkflow', 'workflow'], // 流程
  ['f_workplan', 'weaWorkplan', 'wp'], // 日程 (人力、微搜、客户、项目依赖)
  ['f_smallApp', 'weaSmallApp', ['album', 'sms', 'voting']], // 小模块 (微搜依赖)
  ['f_esearch', 'weaESearch', 'esearch'], // 微搜
  ['f_document', 'weaDoc', 'document'], // 文档
  ['f_hrm', 'weaHrm', 'hrm'], // 人力
  ['f_blog', 'weaBlog', 'blog'], // 微博
  ['f_cowork', 'weaCowork', 'cowork'], // 协作
  ['f_email', 'weaEmail', 'email'], // 邮件
  ['f_cpt', 'weaCpt', 'cpt'], // 资产
  ['f_crm', 'weaCrm', 'crm'], // 客户
  ['f_crmReport', 'weaCrmReport', 'crm'], // 客户报表
  ['f_cube', 'weaCube', 'cube'], // 建模
  ['f_demo', 'weaDemo', 'demo'], // demo示例
  // ['f_develop', 'weaDevelop', 'develop'], // 二次开发 主干不需要
  ['f_fna', 'weaFna', 'fna'], // 财务
  ['f_fnaMulit', 'weaFnaMulit', 'fnaMulit'], // 财务 全面预算
  ['f_inte', 'weaInte', 'inte'], // 集成
  ['f_meeting', 'weaMeeting', 'meeting'], // 会议
  ['f_odoc', 'weaOdoc', ['workflow', 'offical']], // 公文
  ['f_prj', 'weaPrj', 'prj'], // 项目
  ['f_workrelate', 'weaWorkrelate', 'workrelate'], // 执行力
  ['f_portrait', 'weaPortrait', 'portrait'], // 组织画像
  ['f_car', 'weaCar', 'car'], // 车辆前后端
  // ['f_contract', 'weaContract_zs', 'contract'], // 合同 停止开发
  ['f_customSetting', 'weaCustomSetting', 'customsetting'], // 个性化设置
  ['f_govern', 'weaGovern', 'govern'], // 督查督办
  ['f_info', 'weaInfo', 'info'], // 信息采编
  ['f_attendance', 'weaHrmAttendance', 'attendance'], // 新考勤模块
  ['f_tax', 'weaHrmTax', 'tax'], // 新个税
  ['edc_app', 'weaEdcApp', 'edc'], // 数据中心模块
  ['edc_app_v2', 'weaEdcAppV2', 'edc_v2'], // 数据中心模块
  ['f_compared', 'weaCompared', 'compared'], // 对比
  ['f_organization', 'weaOrganization', 'organization'],
  ...(window.e9LibsConfigCustomF || []),
];


const stores = {
  routing: routingStore,
  ...portalThemeStore,
};

const routes = {
  childRoutes: [{
    path: '/',
    component: Login,
    onEnter: checkCasForLogin,
  },
  // { path: '/', component: Login},
  {
    path: 'main',
    onEnter,
    component: Theme,
    getChildRoutes({
      location: {
        pathname,
      },
    }, cb) {
      libs.forEach((lib) => {
        if (window[lib[1]]) {
          libRouteTool.getLibRoute(...lib);
          cb(null, [
            ...libRouteTool.libRouteLoaded.routes, {
              path: 'report',
              childRoutes: libRouteTool.libRouteLoaded.routes,
            },
          ]);
        } else if (lib[0]) {
          const libPath = lib[2];
          if (
            (
              typeof libPath === 'string' && (
                pathname.indexOf(`/main/${libPath}`) === 0 ||
                pathname.indexOf(`/main/report/${libPath}`) === 0
              )
            ) ||
            (
              Array.isArray(libPath) && (
                libPath.some(p =>
                  pathname.indexOf(`/main/${p}`) === 0 ||
                  pathname.indexOf(`/main/report/${p}`) === 0,
                )
              )
            )
          ) {
            libRouteTool.getLibRouteAsync(...lib).then(() => {
              cb(null, [
                ...libRouteTool.libRouteLoaded.routes, {
                  path: 'report',
                  childRoutes: libRouteTool.libRouteLoaded.routes,
                },
              ]);
            });
          }
        }
      });
    },
  },
  ],
};

class Root extends React.Component {
  render() {
    return (
      <Provider ecId={`${this && this.props && this.props.ecId || ''}_Provider@azvnc5`} {...stores}>
        <Router ecId={`${this && this.props && this.props.ecId || ''}_Router@145bc6`} history={history} routes={routes} />
      </Provider>
    );
  }
}

ReactDOM.render(<Root ecId={`${this && this.props && this.props.ecId || ''}_Root@vqlb55`} />, document.getElementById('container'));
