import React from 'react';
// import PropTypes, { func } from 'prop-types';
import {
  Layout,
  Menu,
  Icon,
  Avatar,
  Dropdown,
  Modal,
} from 'antd';
import DocumentTitle from 'react-document-title';
import { connect } from 'dva';
import { Link, Route, Redirect, Switch } from 'dva/router';
import { gup } from '../utils/utils';
import { ContainerQuery } from 'react-container-query';
import classNames from 'classnames';
import Debounce from 'lodash-decorators/debounce';
import GlobalFooter from '../components/GlobalFooter';
import NotFound from '../routes/Exception/404';
import styles from './BasicLayout.less';
import IconS from '../components/IconS';
import Utils from '../common/bcx_utils';
import {
  systemComVaseInfoGet,
  systemPerAccountInfoGetUserAccount,
  usersMyprofile,
} from '../services/api';
import {
  domainConfig
} from '../utils/config';
import moment, { calendarFormat } from 'moment';
import Welcome from '../routes/Enterprise/Organization/Welcome';
import IEReminder from '../routes/Enterprise/Organization/IEReminder';
import { query } from '../constants/formItemLayout';
import $modal from '../utils/modal';
import "moment/locale/zh-cn";
moment.locale('zh-cn');
const store = require('store');
// 默认头像
const defaultAvatar = require('../assets/images/avatar.png');
let slideMenuPath = [];

const { Header, Sider, Content } = Layout;
const { SubMenu } = Menu;

//  侧边一级导航
const menugroup = {
  0: ['企业首页'],
  1: ['驻勤管理'],
  2: ['云会议'],
  3: ['企业保险','金融钱包'],
  // 4: ['防控指挥']
};

/**
 * iverry remark
 * 头部导航，以及导航对应左边的菜单栏
 */
const topMenu = [
  {
    to: '/enterprise/company',
    text: '',
    // items: ['企业首页']
  },
  {
    to: '/taskmanager/tasklist',
    text: '人事',
    // items: ['驻勤管理']
  },
  {
    to: '/meeting/buy-setMeal',
    text: '会议',
    // items: ['云会议']
  },
  {
    to: '/insurancemanagement/insurance-mart',
    text: '金融保险',
    // items: ['金融钱包']
  },{
    to: '/command/prevention-and-control',
    text: '防控指挥',
  },
];

@connect(state => ({
  companyInfo: state.global.companyInfo,
  imIsLogin: state.global.imIsLogin,
  lMenu: state.global.lMenu,
  tMenu: state.global.tMenu,
  footer: state.global.footer,
  im: state.im,
  loginAccount:state.login.loginAccount
}))
class BasicLayout extends React.PureComponent {
  // static childContextTypes = {
  //   location: PropTypes.object,
  //   breadcrumbNameMap: PropTypes.object
  // };
  constructor(props) {
    super(props);
    // 把一级 Layout 的 children 作为菜单项
    this.menus = props.navData.reduce(
      (arr, current) => arr.concat(current.children),
      []
    );
    this.state = {
      menuauth: [], //后台返回的菜单
      openKeys: this.getDefaultCollapsedSubMenus(props),
      currentGroup: 0, //当前组
      topMenu,
      record: {},
      popupVisible: false, //消息通知弹窗是否显示
      isShowIEPrompt: false, //是否IE浏览器
      currentKey: '0',
      userMobilePhone: null,//用户登录手机号码
      noticeIsInit: false, //消息弹窗是否已经弹出
      commandWindow: null,//浏览器上是否新增了防控指挥的窗口，用于后续退出登录的时候，将防控指挥的窗口关闭
    };
    this.loginOut();
    //this.systemComVaseInfoGet();
    if (store.get('saas') !== undefined) {
      this.systemOauthGetUserMenus();
    }

    // 判断url上是否带上token （防控指挥需要跳转到https页面，url上会携带token）
    const access_token = gup('access_token', window.location.href);
    if (!!access_token) {
      const saas = store.get('saas') || {};
      store.set('saas', { ...saas, access_token });
      store.set('isShowContent', { isShowContent: true });
      /**
       * 有token的时候走的是驻勤信息
       * 没有的时候走的是v5的接口
       */
      this.systemComVaseInfoGet();
    }
    //v5的token直接进入防控指挥的页面
    const v5_access_token = gup('v5_access_token', window.location.href);
    if (!!v5_access_token) {
      const saas = store.get('saas') || {};
      store.set('saas', { ...saas, v5_access_token });
      store.set('isShowContent', { isShowContent: true });
    }
  }
  componentWillMount() {
    // const pathName = window.location.pathname;
    // if (/^\/bbdweb.*/.test(pathName)) {
    //   const path = window.location.pathname.replace(/^\/bbdweb(\/#\/)?/, '');
    //   this.props.history.replace(path);
    // }
  }
  componentDidMount() {
    this.isShowIEPrompt(); //调用判断浏览器方法
    // 临时调用修复消息和名字获取失败问题
    // 获取消息
    // this.props.dispatch({
    //   type: 'global/changeNoticeLoading',
    //   payload: false
    // });
    this.props.dispatch({ type: "global/menuChange" });
    // 获取用户信息
    /******此接口还没调好********/
    try {
      // systemPerAccountInfoGetUserAccount({}).then(data => {
      //   console.log(data)
        // this.setState({
        //   userMobilePhone: data.data.mobilePhone
        // })
        // this.props.dispatch({
        //   type: 'user/saveCurrentUser',
        //   payload: {}
        // });
      // });
    } catch (err) {
      console.log(err);
    }

    
  }

  componentDidCatch() {
    console.log('有点小错误');
  }

  componentWillUpdate() {
    this.loginOut();
  }

  componentWillReceiveProps(props) {
    if (props.currentKey !== this.state.currentKey) {
      const {
        location: { pathname }
      } = props || this.props;
      this.setState({
        currentGroup: Number(props.currentKey),
        currentKey: props.currentKey,
        openKeys: pathname.split('/').slice(1)
      });
    }
  }

  componentWillUnmount() {
    this.triggerResizeEvent.cancel();
  }

  //调用判断浏览器方法
  isShowIEPrompt = () => {
    if (Utils.isIEBrowser()) {
      this.setState({
        isShowIEPrompt: true
      });
    }
  };
  log = (key, value) => {
    if (typeof key == 'object') {
      key = JSON.stringify(key);
    }
    if (typeof key == 'object') {
      value = JSON.stringify(value);
    }
  };

  systemComVaseInfoGet = () => {
    // console.log("这里")
    // if (systemComVaseInfoGet({}) !== undefined) {
    if (!!this.props.companyInfo.comName) {
      // const topMenu1 = this.state.topMenu;
      // topMenu1[0].text = this.props.companyInfo.comName;
      this.props.dispatch({
        type: 'global/companyInfo',
        payload: this.props.companyInfo,
        // topMenu: [...topMenu1]
      });
    } else {
      systemComVaseInfoGet({}).then(
        response => {
          // const topMenu1 = this.state.topMenu;
          // topMenu1[0].text = response.data.comName;
          this.props.dispatch({
            type: 'global/companyInfo',
            payload: response.data,
            // topMenu: [...topMenu1]
          });
        },
        err => {
          console.log(err, 'systemComVaseInfoGet-err-获取企业详情');
        }
      );
      // }
    }
  };

  //获取用户登陆菜单
  systemOauthGetUserMenus = () => {
    if (store.get('saas') !== undefined) {
      const menuauth = [];
      const setMenus = (arr,type) => {
        arr.forEach(val => {
            // 忽略的菜单列表
            // const ignoreList = ['异常','帐户'];
          if(val.to){
            if (menuauth.indexOf(val.text)=== -1) {
              menuauth.push(val.text);
            }
            // if(val.items.length>0){
            //   menuauth.concat(val.items)
            // }
          }else{
            if (menuauth.indexOf(val.name)=== -1&&!val.noShow) {
              menuauth.push(val.name);
            }
            // if(val.children&&val.children.length>0){
            //   setMenus(val.children)
            // }
          }
        });
        this.setState({ menuauth });
      }
      setTimeout(() => {
        let menusData= []
        menusData=menusData.concat(this.state.topMenu)
        this.menus.map(item=>{
          menusData.push(item)
          if(item.children&&item.children.length>0){
            menusData=menusData.concat(item.children)
          }
        })
        setMenus(menusData)
        // setMenus(this.state.topMenu.concat(this.menus)||[])
      }, 200);
    }
  };


  onCollapse = collapsed => {
    this.props.dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed
    });
  };
  onMenuClick = ({ key }) => {
    if (key === 'logout') {
      this.logout();
    }
  };
  logout = () => {
    store.clearAll();
    this.props.dispatch({
      type: 'login/logout'
    });
    //im的退出
    if(this.props.im && this.props.im.isSDKReady){
      tim.logout();
    }
    //如果有防控指挥的窗口，一并关闭
    if(this.state.commandWindow){
      this.state.commandWindow.close()
    }
    this.props.dispatch({
      type: 'global/changeShowSystemNotice',
      payload: false,
    });
  };
  getDefaultCollapsedSubMenus(props) {
    const currentMenuSelectedKeys = [...this.getCurrentMenuSelectedKeys(props)];
    currentMenuSelectedKeys.splice(-1, 1);
    if (currentMenuSelectedKeys.length === 0) {
      return ['dashboard'];
    }
    return currentMenuSelectedKeys;
  }
  getCurrentMenuSelectedKeys(props) {
    const {
      location: { pathname }
    } = props || this.props;
    const keys = pathname.split('/').slice(1);
    if (keys.length === 1 && keys[0] === '') {
      return [this.menus[0].key];
    }
    return keys;
  }
  getNavMenuItems(menus, parentPath = '') {
    if (!menus) {
      return [];
    }
    let menusData = menus;
    if (!parentPath) {
      menusData = menus.filter(val => {
        return menugroup[this.state.currentGroup].indexOf(val.name) !== -1;
      });
    }

    return menusData.map(item => {
      if (this.state.menuauth.indexOf(item.name) === -1) {
        return null;
      }
      if (!item.name) {
        return null;
      }
      let itemPath;
      if (item.path.indexOf('http') === 0) {
        itemPath = item.path;
      } else {
        itemPath = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
      }
      if (item.children && item.children.some(child => child.name)) {
        return (
          <SubMenu
            title={
              item.icon ? (
                <span>
                  <IconS type={item.icon} />
                  <span>{item.name}</span>
                </span>
              ) : (
                  item.name
                )
            }
            key={item.key || item.path}
          >
            {this.getNavMenuItems(item.children, itemPath)}
          </SubMenu>
        );
      }
      const icon = item.icon && <IconS type={item.icon} />;
      slideMenuPath.push(itemPath);
      return (
        <Menu.Item key={item.key || item.path.split('/')[0]}>
          {/^https?:\/\//.test(itemPath) ? (
            <a href={itemPath} target={item.target}>
              {icon}
              <span>{item.name}</span>
            </a>
          ) : (
              <Link
                to={itemPath}
                target={item.target}
                replace={itemPath === this.props.location.pathname}
              >
                {icon}
                <span>{item.name}</span>
              </Link>
            )}
        </Menu.Item>
      );
    });
  }
  getPageTitle() {
    const { location, getRouteData, companyInfo } = this.props;
    const { pathname } = location;
    let title = '';
    // let title = domainConfig.getName(companyInfo.regProvince,companyInfo.regCity);
    getRouteData('BasicLayout').forEach(item => {
      // 修改网页title显示
      if (
        item.path === pathname && item.name
      ) {
        title = item.name;
      }
    });
    return title;
  }
 

  loginOut = () => {
    if (store.get('saas') === undefined) {
      this.props.dispatch({
        type: 'login/logout'
      });
    }
  };

  mainmenu = key => {
    //登录后是否是否展示内容,默认 欢迎页面
    if (
      store.get('isShowContent') &&
      !store.get('isShowContent')['isShowContent']
    ) {
      store.set('isShowContent', { isShowContent: true });
    }

    slideMenuPath = [];
    this.setState({
      currentGroup: key
    });
    setTimeout(() => {
      this.setState(
        {
          openKeys: this.getDefaultCollapsedSubMenus(this.props)
        },
        () => {
          this.props.history.replace(slideMenuPath[0]);
        }
      );
    }, 10);
  };

  handleOpenChange = openKeys => {
    const lastOpenKey = openKeys[openKeys.length - 1];
    const isMainMenu = this.menus.some(
      item =>
        lastOpenKey && (item.key === lastOpenKey || item.path === lastOpenKey)
    );
    this.setState({
      openKeys: isMainMenu ? [lastOpenKey] : [...openKeys]
    });
  };
  toggle = () => {
    const { collapsed } = this.props;
    this.props.dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: !collapsed
    });
    this.triggerResizeEvent();
  };

  @Debounce(600)
  triggerResizeEvent() {
    // eslint-disable-line
    const event = document.createEvent('HTMLEvents');
    event.initEvent('resize', true, false);
    window.dispatchEvent(event);
  }
  render() {
    const {
      currentUser,
      collapsed,
      getRouteData
    } = this.props;
    const isShowContent = store.get('isShowContent')
      ? store.get('isShowContent')['isShowContent']
      : '';
    currentUser.avatar = currentUser.photoUrl
      ? currentUser.photoUrl
      : defaultAvatar;

    const menu = (
      <Menu
        className={styles.menu}
        selectedKeys={[]}
        onClick={this.onMenuClick}
      >
        <Menu.Divider />
        <Menu.Item key="logout">
          <Icon type="logout" />
          退出登录
        </Menu.Item>
      </Menu>
    );
    const menuProps = collapsed
      ? {}
      : {
        openKeys: this.state.openKeys
      };

    const __renderTopMenu = (val, index) => {
       // 防空指挥跳转到https地址
        if (/\/command\//.test(val.to) && store.get('saas')) {
        const hostName = domainConfig.https;
        return (
          <a onClick={() => {
            //利用此方法，让只打开一个新窗口，并记录下防控指挥的打开窗口
            // const commandWindow = window.open(store.get('saas') ? `${hostName}${val.to}` : '', "scrollbars=yes,resizable=1,modal=false,alwaysRaised=yes");
            const commandWindow = window.open(store.get('saas') ? `${hostName}${val.to}?access_token=${store.get('saas')['access_token']}` : '', "scrollbars=yes,resizable=1,modal=false,alwaysRaised=yes");
            this.setState({commandWindow})
            //获取并登录im
            this.props.dispatch({
              type: `global/imLogin`,
              payload: {
                username: this.state.userMobilePhone,
                name:''
              }
            });
          }}>{val.text}</a>
        );
      }else{
         return (
          <Link
            key={val.to + index}
            onClick={() => {
              if (val.to === '/command/prevention-and-control') {
                // //获取并登录im
                this.props.dispatch({
                  type: `global/imLogin`,
                  payload: {
                    username: gup('mobilePhone',window.location.href),
                    name: decodeURI(gup('username',window.location.href))
                  }
                });
              }
              this.mainmenu(index);
            }}
            className={
              this.state.currentGroup === index ? 'selected' : ''
            }
            to={val.to}
            replace={val.to === this.props.location.pathname}
          >
            {val.text}
          </Link>
        );
      }
    }
    const layout = (
      <Layout>
        {this.state.isShowIEPrompt && <IEReminder />}
        <Header style={{ display: this.props.tMenu ? 'block' : 'none' }} className={styles.header}>
          <div className={styles.logo}>
            <IconS type="logo-"/>
            <h1>
              {this.state.topMenu.map((val, index) => {
                if (index === 0) {
                  return (
                    <span key={index}>
                      {store.get('isHasEnterpriseMenu') !== undefined ? (
                        <Link
                          key={val.to + index}
                          onClick={() => {
                            this.mainmenu(index);
                          }}
                          to={val.to}
                          replace={val.to === this.props.location.pathname}
                          title={
                            this.props.companyInfo.comName ||
                            this.state.topMenu[0].text
                          }
                        >
                          {this.props.companyInfo.comName ||
                            this.state.topMenu[0].text}
                        </Link>
                      ) : (
                          <a
                            style={{ cursor: 'default' }}
                            title={
                              this.props.companyInfo.comName ||
                              this.state.topMenu[0].text
                            }
                          >
                            {this.props.companyInfo.comName ||
                              this.state.topMenu[0].text}
                          </a>
                        )}
                    </span>
                  );
                } else {
                  return '';
                }
              })}
              <Icon type="setting" />
            </h1>
          </div>
          <div className={styles.topmenu}>
            {this.state.topMenu.map((val, index) => {
              if (this.state.menuauth.indexOf(val.text) === -1) {
                return null;
              }
              if (index === 0) {
                return '';
              }
              return (
                __renderTopMenu(val, index)
              );
            })}
          </div>

          <div className={styles.right}>
            <Dropdown overlay={menu}>
              <span className={`${styles.action} ${styles.account} `}>
                <Avatar
                  size="biger"
                  className={styles.avatar}
                  src={currentUser.avatar}
                />
                <span>{currentUser.name}</span>
              </span>
            </Dropdown>
          </div>
        </Header>

        {isShowContent || this.props.companyInfo.isInit === '0' ? (
          <Layout>
            <Sider
              trigger={null}
              collapsible
              collapsed={collapsed}
              breakpoint="md"
              onCollapse={this.onCollapse}
              width={254}
              className={styles.sider}
              style={{ display: this.props.lMenu ? 'block' : 'none' }}
            >
              <Icon
                className={styles.trigger}
                type={collapsed ? 'menu-unfold' : 'menu-fold'}
                onClick={this.toggle}
              />
              <Menu
                className="sidemenu"
                theme="light"
                mode="inline"
                {...menuProps}
                onOpenChange={this.handleOpenChange}
                selectedKeys={this.getCurrentMenuSelectedKeys()}
                style={{ margin: '16px 0', width: '100%' }}
              >
                {/* 传入前端配置的路由 */}
                {this.getNavMenuItems(this.menus)}
              </Menu>
            </Sider>
            <Content
              className={`layout - content${
                this.getDefaultCollapsedSubMenus(this.props)[0]
                } `}
            >
              <Switch>
                {getRouteData('BasicLayout').map(item => (
                  <Route
                    exact={item.exact}
                    key={item.path}
                    path={item.path}
                    component={item.component}
                  />
                ))}

                <Route component={NotFound} />
              </Switch>

              {
                this.props.footer &&
                <GlobalFooter
                  className="oneKeySearchHidden"
                  copyright={
                    <div>
                      平台运营与技术支持&nbsp;&nbsp;
                      <Icon type="copyright" />{' '}
                      {new Date().getFullYear()}
                      百川信（厦门）网络信息服务有限公司
                    </div>
                  }
                />
              }
            </Content>
          </Layout>
        ) : (
            <Layout style={{ height: 'calc(100vh - 72px)', background: '#fff' }}>
              <Welcome
                ok={() => {
                  this.props.companyInfo.isInit = '1';
                  store.set('isShowContent', { isShowContent: true });
                  this.props.history.push(`/PoliceDeclare/DeclarationList`);
                }}
              />
            </Layout>
          )}
        
      </Layout>
    );

    return (
      <DocumentTitle title={this.getPageTitle()}>
        <ContainerQuery query={query}>
          {params => <div className={classNames(params)}>{layout}</div>}
        </ContainerQuery>
      </DocumentTitle>
    );
  }
}

export default connect(state => ({
  currentUser: state.user.currentUser,
  collapsed: state.global.collapsed,
  companyInfo: state.global.companyInfo,
  currentKey: state.global.currentKey
}))(BasicLayout);
