import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Connect, Modal } from 'amos-framework';
import AmosWebSocket from 'amos-websocket';
import * as endConf from 'amos-processor/lib/config/endconf';
import PilotController from 'amos-viz/lib/board/PilotController';
import SysWsURL, { completeToken } from 'CONSTS/wsUrlConsts';
import ScreenSaverView from './screenSaver/ScreenSaverView';

import Three3dView from './View3D';
import { eventTopics } from './consts';
import IndexChart from './indexChart';
import loadScripts from 'dt2react/lib/utils/loadScripts';

const eventConnect = Connect.eventConnect;
const AmosConfig = endConf.AmosConfig;
const enableScreenSaver = AmosConfig.screenSaverConf.enable;
const delayTime = AmosConfig.screenSaverConf.delayTime;
const outMap = AmosConfig.sysConf.outMap;

@eventConnect
class View3DRoot extends Component {
  constructor(props) {
    super(props);

    this.state = {
      showScreenSaver: false, //是否打开屏保
      is3DPage: false,
      city: '',
      orgCode: '',
      loadAmap: false,
      BasicMap: null,
      flag:"0",
      pid:null,
      pointName:"",
      pointAttrs:"",
      floor:"",
      pointtype:false,
    };
    this.pushTimeOutId = null;
  }

  componentDidMount() {
    if (outMap) {
      Object.keys(localStorage).map(e => {
        if (e.indexOf('_AMap') === 0) {
          localStorage.removeItem(e);
        }
      });
      let script = null;
      let mainUI = null;

      script = {
        key: 'amapscripts',
        url: `/extra/amap/js/outamap.1.4.6.js?rnd= ${Math.random()}`
      };
      mainUI = {
        key: 'mainUI',
        //url: '//10.56.28.228/webapi.amap.com/ui/1.0/main.js'
        url: '/extra/amap/js/outmain.1.4.6.js'
      };

      loadScripts.asyncLoadScript(script, () => {
        loadScripts.asyncLoadScript(mainUI, () => {
          setTimeout(() => {
            this.setState({
              loadAmap: true,
              BasicMap: require('./indexMap')
            });
          }, 2000);
        });
      });
    } else {
      this.setState({
        loadAmap: true,
        BasicMap: require('./indexMap')
      });
    }
  }

  componentWillUnmount() {
    if (this.pushTimeOutId){
      clearTimeout(this.pushTimeOutId);
      this.pushTimeOutId = null;
    }
  }

  onLoadCompleted = () => {
    console.log('3d resources load completed');
    this.setState({
      showScreenSaver: true
    });
  };

  getScreenSaverContext = () => {
    return <ScreenSaverView />;
  };

  getScreenSaver() {
    const { showScreenSaver } = this.state;
    return enableScreenSaver && showScreenSaver && (
      <PilotController delayTime={delayTime}>
        <Modal
          className="screen-saver-view-modal"
          width="100%"
          height="100%"
          closable={false}
          noDefaultHeader
          visible
          destroyContent
          noDefaultFooter
          content={this.getScreenSaverContext()}
        />
      </PilotController>
    );
  }

  hiddenScreenSaver = () => {
    this.setState({ showScreenSaver: false });
    if (enableScreenSaver) {
      this.pushTimeOutId = setTimeout(() => {
        this.setState({
          showScreenSaver: true
        });
      }, 1000);
    }
  }

  /**
   * 监控视图消息 (view3d ws)
   */
  handleData = (data = {}) => {
    console.log('view3d ws data:', data);
    const topic = data.topic || eventTopics.point_alarm;
    this.props.trigger(topic, data);
  };

  indexViewChange = (status) => {
    if(status.hasOwnProperty("flag") ){

      this.setState({
        is3DPage: status.is3DPage,
        city: status.city,
        orgCode: status.orgCode,
        flag:status.flag,
        pid:status.pid,
        pointName:status.pointName,
        pointAttrs:status.pointAttrs,
        floor:status.floor,
        pointtype:status.pointtype,


      });
    }else{
      this.setState({
        is3DPage: status.is3DPage,
        city: status.city,
        orgCode: status.orgCode,
        flag:0,

      });
    }


  }



  render() {
    let BasicMap = this.state.BasicMap;
    const wsURL = completeToken(SysWsURL.view3dws);
    if (this.state.is3DPage) {
      return (
        <div className="sys-view-3d">
          <AmosWebSocket ref={node => this.aws = node} url={wsURL} onMessage={this.handleData} reconnect debug />
          <Three3dView onLoadCompleted={this.onLoadCompleted} hiddenScreenSaver={this.hiddenScreenSaver} indexViewChange={this.indexViewChange} city={this.state.city} orgCode={this.state.orgCode} pointName={this.state.pointName} pointAttrs={this.state.pointAttrs} flag={this.state.flag} pid={this.state.pid}   floor={this.state.floor} pointtype={this.state.pointtype}/>
          {this.getScreenSaver()}
        </div>
      );
    } else {
      return (
        <div className="content-body-2d">
          {/* <IndexChart indexViewChange={this.indexViewChange} /> */}
          { this.state.loadAmap && <BasicMap indexViewChange={this.indexViewChange}/> }
        </div>
      );
    }
  }
}

View3DRoot.propTypes = {
  subscribe: PropTypes.func,
  trigger: PropTypes.func
};

export default View3DRoot;
