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涓婃槸鍚﹀甫涓妕oken 锛堥槻鎺ф寚鎸ラ渶瑕佽烦杞埌https椤甸潰锛寀rl涓婁細鎼哄甫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 });
      /**
       * 鏈塼oken鐨勬椂鍊欒蛋鐨勬槸椹诲嫟淇℃伅
       * 娌℃湁鐨勬椂鍊欒蛋鐨勬槸v5鐨勬帴鍙�
       */
      this.systemComVaseInfoGet();
    }
    //v5鐨則oken鐩存帴杩涘叆闃叉帶鎸囨尌鐨勯〉闈�
    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" });
    // 鑾峰彇鐢ㄦ埛淇℃伅
    /******姝ゆ帴鍙h繕娌¤皟濂�********/
    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) => {
       // 闃茬┖鎸囨尌璺宠浆鍒癶ttps鍦板潃
        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})
            //鑾峰彇骞剁櫥褰昳m
            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') {
                // //鑾峰彇骞剁櫥褰昳m
                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);