import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Store } from 'amos-tool';
import * as endConf from 'amos-processor/lib/config/endconf';
import formatUrl from 'amos-processor/lib/utils/urlFormat';
import SysConsts from 'amos-processor/lib/config/consts';
import { getRegion } from './../../utils/cacheUtils';
import CardItem from './CardItem';
import { getBizMenusAction } from './../../services/securityService';
import commonConsts  from './../../consts/commonConsts';

const AmosConfig = endConf.AmosConfig;
const xunjian = AmosConfig.outterURI.xunjian;
const lsTool = Store.lsTool;

/**
 * 控制台
 *
 * @class Console
 * @extends {Component}
 */
class Console extends Component {

  constructor(props) {
    super(props);
    this.state = {
      navList: [],
      showCardItem: this.preloadNav()
    };
  }

  componentDidMount() {
    this.initMenus();
  }

  onItemClick = (url, code) => {
    if (code === 'patrolConfig'){
      const userId = lsTool.read(SysConsts.userId);
      const token = lsTool.read(SysConsts.token);
      const region = getRegion();
      const regionObj = JSON.parse(region) || {};
      const cityCode = regionObj.cityCode;
      let regionSelect ;
      if(cityCode){
        regionSelect = commonConsts.regionSelect.chooseYes;
      }else{
        regionSelect = commonConsts.regionSelect.chooseNo;
      }
      window.open(formatUrl(xunjian, { userId, token, regionSelect }));  
    } else {
      window.open(`${url}?rootnav=${code}`, '_blank');
    }
  }

  preloadNav = () => {
    let showCardItem = true;
    const pathname = location.pathname;
    if (pathname !== '/console'){
      showCardItem = false;
    }
    return showCardItem;
  }

  initMenus = () => {
    getBizMenusAction('console').then(d => {
      this.setState({
        navList: d
      });
    });
  }

  renderCardItem = () => { 
    const { navList } = this.state;
    return navList.map(nl => <CardItem key={nl.id} {...nl} onClick={this.onItemClick} />);
  }

  render() {
    const { showCardItem } = this.state;
    const { children } = this.props;
    if (children){
      return children;
    } else {
      return (
        <div className="console-list">
          {showCardItem && this.renderCardItem()}
        </div>
      );
    }
  }
}

Console.propTypes = {
  children: PropTypes.node
};

export default Console;
