import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { TimeNow } from 'amos-framework';
import { Tip } from '@gm/graphmod-common';
import MenusBgCanvas from './MenusBgCanvas';
import { message, eventConsts } from './../../eventConsts';
import { MenuEnum } from './../../config';

/**
 * 系统右上角（天气）
 *
 * @class Weather
 * @extends {Component}
 */
class Weather extends Component {
  static propTypes = {
    dataConfig: PropTypes.object,
    visualParams: PropTypes.object
  };

  static defaultProps = {
    dataConfig: {}
  };

  constructor(props) {
    super(props);
    this.state = {
      weather: {
        city: '西安',
        weatherInfo: '24~35 西南分4-5级转3-4级 雷阵雨转多云'
      },
      messageData: MenuEnum.ALL.value // 默认选中全国
    };

  }

  componentDidMount() {
    // getWeatherAction('101110101').then(
    //   resp => {
    //     this.setState({ weather: resp });
    //   }
    // );
    // 给应急处置添加浮层，托管事件用例进行点检的数据校验
    this.registerListener();
    // 获取当前是全国换流站还是单独换流站
    message.storageSubscribe(eventConsts.SWITCH_WHOLE_COUNTRY_STATION, (data) => {
      console.log(data);
      if (data && data.message === '') {
        this.setMenu();
      } else {
        this.setState({
          messageData: data.message ? data.message : MenuEnum.ALL.value
        }, () => this.setMenu());
      }
    });
    // 自动进入到应急处理模式，通过this.context.browserHistory.push切换页面，菜单选中未切换，所以dom操作
    message.storageSubscribe(eventConsts.EMERGENCY_MODEL, (data) => {
      console.log(data);
      this.autoIntoEmergencyModel();
    });
  }

  /**
   * 根据消息内容控制辅屏菜单
   */
  setMenu = () => {
    const { messageData } = this.state;
    // const body = document.getElementsByClassName('content-body');
    // body && body.length > 0 ? body[0].style.display = 'none' : [];
    const headerMenu = document.getElementsByClassName('dbsub-header-menu');
    const headerLiMenu = headerMenu && headerMenu.length > 0 ? headerMenu[0].getElementsByTagName('li') : [];
    for ( let i = 0; i < headerLiMenu.length; i++ ) {
      const headerLiAMenu =  headerLiMenu[i].getElementsByTagName('a');
      if (headerLiAMenu && headerLiAMenu.length > 0) {
        const hrefValue = headerLiAMenu[0].getAttribute('href');
        if (messageData === MenuEnum.ALL.value) {
          // 全国换流站，把站的菜单隐藏
          if (hrefValue.indexOf(MenuEnum.STATION.value) !== -1 ) {
            headerLiAMenu[0].style.display = 'none';
          }
        } else {
          // 单独站，把全国的菜单隐藏
          if (hrefValue.indexOf(MenuEnum.ALL.value) !== -1 ) {
            headerLiAMenu[0].style.display = 'none';
          }
        }
        // 显示当前消息的菜单
        if (hrefValue.indexOf(messageData) !== -1) {
          headerLiAMenu[0].style.display = 'flex';
        }
      }
    }

    // 点击第一个
    // const aMenu = headerLiMenu && headerLiMenu.length > 0 && headerLiMenu[0].getElementsByTagName('a');
    // aMenu && aMenu.length > 0 && aMenu[0].click();
    for ( let i = 0; i < headerLiMenu.length; i++ ) {
      const headerLiAMenu =  headerLiMenu[i].getElementsByTagName('a');
      if (headerLiAMenu && headerLiAMenu.length > 0) {
        if (headerLiAMenu[0].style.display === 'flex') {
          setTimeout(() => {
            headerLiAMenu[0].click();
            // body && body.length > 0 ? body[0].style.display = 'flex' : [];
          // eslint-disable-next-line no-magic-numbers
          }, 500);
          return;
        }
      }
    }
    // const pathname = window.location.href;
    // if (!pathname.includes('all') && !pathname.includes('station')) {
    //   console.log(pathname);
    //   body && body.length > 0 ? body[0].style.display = 'flex' : [];
    // }
  }


  registerListener = ()=>{
    const flag = this.registerLayerClick();
    !flag && window.addEventListener('storage', this.registerLayerClick);
  }


  registerLayerClick = ()=>{
    if (document.getElementsByClassName('nav-menu-item').length > 0) {
      const pathname = window.location.href;
      if (!pathname.includes('sub')) {
        // 获取应急指挥路由，通过herf加标识
        const menus = document.getElementsByClassName('dbmain-header-nav-menu-list')[0].getElementsByTagName('li') || [];
        for (let i = 0;i < menus.length;i++ ){
          // 循环判断找出应急指挥页面li标签（原理是在页面路由a上加上了‘type=wljk’）
          const aLinkArray = menus[i].getElementsByTagName('a');
          if (aLinkArray.length > 0 && aLinkArray[0].getAttribute('href').includes('type=yjcz')){
            // 创建div块覆盖原有的菜单，进行菜单点击的托管
            menus[i].appendChild(document.createElement('div'));
            menus[i].getElementsByTagName('div')[1].style.width = '100%';
            menus[i].getElementsByTagName('div')[1].style.height = '100%';
            menus[i].getElementsByTagName('div')[1].style.position = 'absolute';
            menus[i].getElementsByTagName('div')[1].style.zIndex = '9999';
            menus[i].getElementsByTagName('div')[1].addEventListener('click', (event)=>{
              event.stopPropagation();
              // 将菜单的点击交给 新div块，符合条件可以点击（原有的点击事件），不符合进行业务的提示处理
              this.floatLayerClick(menus[i].getElementsByTagName('a')[0]);
            }, false);
            break;
          }
        }
      }
      window.removeEventListener('storage', this.registerLayerClick);
      return true;
    }
  }


  autoIntoEmergencyModel = () =>{
    if (document.getElementsByClassName('nav-menu-item').length > 0) {
      const pathname = window.location.href;
      if (!pathname.includes('sub')) {
        // 获取应急指挥路由，通过herf加标识
        const menus = document.getElementsByClassName('dbmain-header-nav-menu-list')[0].getElementsByTagName('li') || [];
        for (let i = 0;i < menus.length;i++ ){
          // 循环判断找出应急指挥页面li标签（原理是在页面路由a上加上了‘type=wljk’）
          const aLinkArray = menus[i].getElementsByTagName('a');
          if (aLinkArray.length > 0 && aLinkArray[0].getAttribute('href').includes('type=yjcz')){
            menus[i].getElementsByTagName('a')[0].click();
            break;
          }
        }
      }
    }
  }

  floatLayerClick = (document)=>{
    const alarmInfo = message.getStorageData(eventConsts.ALARM_INFO);
    if (alarmInfo && Object.keys(alarmInfo).length > 0){
      // 判断stationCode不为空，进行跳转
      document.click();
      message.storageTrigger(eventConsts.FIRE_ALARM_CHANGE, alarmInfo);
    } else {
      // 判断stationCode为空，不进行跳转,进行提示
      Tip.warning('请先选择要处理的警情');
    }
  }

  render() {
    const { weather = {} } = this.state;
    const time = `HH:mm:ss yyyy-MM-dd w  ${weather.city}`;
    const pathname = window.location.href;
    if (pathname.includes('sub') || pathname.includes('ccs-weather')) {
      return (
        <div className="ccs-weather">
          <MenusBgCanvas type="subMenusBgCanvas" />
          <div className="ccs-weather-time" align="middle">
            <TimeNow fmt={time} />
          </div>
          <div className="ccs-weather-content" >
            {weather.weatherInfo}
          </div>
        </div>
      );
    } else {
      return (
        <MenusBgCanvas type="mainMenusBgCanvas" />
      );
    }
  }
}

export default Weather;
