/*
 * @Author: 吴文洁
 * @Date: 2019-07-10 10:30:49
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-11 17:22:58
 * @Description:
 */
import React, { useContext, useEffect, useState } from 'react';
import { withRouter } from 'react-router-dom';
import { ConfigProvider, message, Layout, DatePicker } from 'antd';
import Header from './Header'
import Menu from './Menu'
import Main from './Main'
import zhCN from 'antd/lib/locale/zh_CN'
import User from '@/common/js/user';
import BaseService from "@/domains/basic-domain/baseService";
import moment from 'moment';
import { VersionContext, VersionInfo, XMContext } from '@/store/context';
import { setStoreGroupPermission, setStorePermission, setStoreGroupList, setStoreList, setWechatLogin } from '@/store/actions/index';
import Service from "@/common/js/service";
import Bus from '@/core/tbus';
import WechatApi from '@/common/js/wechatApi';
import { func } from 'prop-types';

const { Footer, Sider, Content } = Layout;

declare var window: any;

const App: React.FC = (props: any) => {
  const [storeUserId, setStoreUserId] = useState('')
  const ctx: any = useContext(XMContext);
  const [versionInfo, setVersionInfo] = useState<VersionInfo | null>(null)
  const userId = User.getUserId();
  const [menuType, setMenuType] = useState(true);
  const [initWechat, setInitWechat] = useState(false);
  const enterpriseId = User.getEnterpriseId();
  window.ctx = ctx;


  useEffect(() => {
    getStorePermission();
    initWechatConfig();
  
    getStoreAndUserInfo();
    getVersion();
    if (window.location.hash === "#/") {
      window.RCHistory.replace({
        pathname: '/home',
      })
    }
  }, [])
  async function initWechatConfig() {
    WechatApi.initConfig({ isAgentConfig: true, url: window.location.href.split('#')[0] }).then(() => {
      ctx.dispatch(setWechatLogin(true))

    })
  }
  useEffect(() => {
    getStorePermission();
  }, [window.location.hash])

  function getStorePermission() {
    const params = {
      storeId: User.getStoreId(),
    };
    Service.Hades('public/customerHades/whetherStopStore', params).then((res) => {
      if (res.result) {
        window.RCHistory.replace({
          pathname: '/error-college',
        })
      }
    });
  }
  function getVersion() {
    BaseService.getLesseeVersionMsg().then((res) => {
      let version = res.result;
      User.setVersion(version);
      User.setExpirationTime(res.result.validEndTime)
      let versioninfo: VersionInfo = {
        dayTime: version.dayTime,
        stateEnum: version.stateEnum,
        userNum: version.userNum === -1 ? '不限人数' : version.userNum,
        surplusUserNum: version.userNum === -1 ? '不限人数' : version.surplusUserNum,
        surplusDayTime: version.surplusDayTime,
        validEndTime: moment(version.validEndTime).format('YYYY-MM-DD'),
        validStartTime: moment(version.validStartTime).format('YYYY-MM-DD'),
        validEndTimeST: version.validEndTime,
        validStartTimeST: version.validStartTime,
        whetherReachUserNum: version.whetherReachUserNum,
      };
      setVersionInfo(versioninfo)
    });
  }

  async function getStoreAndUserInfo() {
    await (enterpriseId ? getStoreInfo() : getStoreGroupAndStoreList());
  }

  function getStoreInfo() {
    console.log("currentStoreUserInfo", window.currentStoreUserInfo);
    const params = {
      storeId: User.getStoreId(),
      userId: User.getUserId(),
    };
    Service.Hades('public/customerHades/getStoreAndUserMsg', params).then((res) => {
      if (res.success) {
        const { id, storeUserId, storeName, userRole, storeType } = res.result;
        User.setStoreId(id);
        User.setStoreUserId(storeUserId);
        User.setStoreName(storeName);
        Bus.trigger('storeNameChange', storeName);
        User.setUserRole(userRole);
        User.setStoreType(storeType);
        setCurrentStoreUserInfo(id, storeUserId)
        setStoreUserId(storeUserId);
        getUserPermission();
      }
    })
  }

  function setCurrentStoreUserInfo(storeId: any, storeUserId: any) {
    window.currentStoreUserInfo.storeId = storeId;
    window.currentStoreUserInfo.storeUserId = storeUserId;
    window.currentStoreUserInfo.userId = User.getUserId();
    window.currentStoreUserInfo.token = User.getToken();
    window.currentStoreUserInfo.enterpriseId = User.getEnterpriseId();
  }

  function getStoreGroupAndStoreList() {

    BaseService.getUserStore({ userId }).then((res) => {

      const { storeGroupVOS = [], storeVOS = [] } = res.result;
      if (storeVOS.length < 1) {
        message.warning('店铺不存在');
        window.RCHistory.replace('/login');
        return
      }
      const { id, storeUserId, storeName, userRole, storeType } = storeVOS[0];

      User.setStoreId(id);
      User.setStoreUserId(storeUserId);
      User.setStoreName(storeName);
      Bus.trigger('storeNameChange', storeName);
      User.setUserRole(userRole);
      User.setStoreType(storeType);
      setCurrentStoreUserInfo(id, storeUserId);
      ctx.dispatch(setStoreGroupList(storeGroupVOS))
      ctx.dispatch(setStoreList(storeVOS));
      setStoreUserId(storeUserId)
      getUserPermission();
    });
  }

  function getUserPermission() {
    BaseService.getUserPermission({}).then((res) => {
      console.log(res.result);
      const { storePermission, storePermissionGroup, storeUserPermission, storeUserPermissionGroup } = res.result;
      ctx.dispatch(setStoreGroupPermission(storePermissionGroup))
      ctx.dispatch(setStorePermission(storeUserPermissionGroup))
    });
  }
  function handleMenuType() {
    setMenuType(!menuType);
  }

  if (!storeUserId) {
    return <div></div>
  }

  return (
    <div id="home">
      {/* <Layout>
        <Sider><Menu menuType={menuType} handleMenuType={handleMenuType} /></Sider>
        <Layout>
        <Header id="app" handleMenuType={handleMenuType} menuType={menuType} />
        <ConfigProvider locale={zhCN} autoInsertSpaceInButton={false}>
        <Main menuType={menuType} />
        </ConfigProvider>
        </Layout>
      </Layout> */}
      <Header id="app" handleMenuType={handleMenuType} menuType={menuType} />
      <VersionContext.Provider value={versionInfo}>
        <ConfigProvider locale={zhCN} autoInsertSpaceInButton={false}>
          <Main menuType={menuType} />
        </ConfigProvider>
        <Menu menuType={menuType} handleMenuType={handleMenuType} />
      </VersionContext.Provider>

    </div>
  )
}

export default withRouter(App)
