/* eslint-disable max-len */
/* eslint-disable no-magic-numbers */
/* eslint-disable import/no-named-as-default */
/* eslint-disable react/prop-types */
/* eslint-disable react/sort-comp */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Store,utils } from 'amos-tool';
import { Connect as UIConnect, Toast } from 'amos-framework';
import A3DDesigner, { Connect } from 'amos-3d/lib/designer';
import WorkerObjContent from 'amos-3d/lib/worker/WorkerObjContent';
import { transitionHelper } from 'amos-3d/lib/helpers';
import { ObjAnchorHelper, InfoHelper } from 'base-r3d/lib/plugins';
import { LensJumpFactory } from 'base-r3d/lib/factory';
import MaskContent from './MaskContent';
import { getObjFromNet } from 'SERVICES/3dService';
import { initView3DFromBizAction, initView3DRiskFromBizAction } from 'SERVICES/bizService';
import { getAlarms } from 'SERVICES/alarmService';
import { desigerConf, desigerHelperConfig } from './conf';
import { thirdFloor, sixthFloor, xyFloor, alarmPoint } from './alarmMarker';
import LoadingComs from './LoadingComs';
import PointsPool from './PointsPool';
import PointsAlarm from './PointsAlarm';
import CoordinatePickup from './CoordinatePickup';
import { eventTopics, isPointEvent ,isControllerEvent, isManualOperate } from './consts';
import { executeView3dCMD, parseManual } from './dataProcessor';
//import { xianCode, xianyangCode } from '../../../_mock/code';

const { resizeConnect } = Connect;
const eventConnect = UIConnect.eventConnect;
const { BaseObjHelper } = transitionHelper;
const lsTool = Store.lsTool;

const LENS_LEVEL = {
  ROOT: 'root',
  SUB: 'sub',
  SUN: 'sun'
};

const FLOOR = {
  FLOOR_0: 'floor_0',
  FLOOR_3: 'floor_3',
  XY_FLOOR_3: 'xy_floor_3',
  FLOOR_6: 'floor_6',
  FLOOR_XY:'floor_xy'

};

const layerConfig = {
  defaultSelects: '',
  layers: []
};

const createPanel = (text) => {
  const div = document.createElement('div');
  div.style.position = 'absolute';
  div.className = 'three-ui-anchor';
  div.innerText = text;
  return div;
};

/**
 * 展示三维模型
 *
 * @class View3D
 * @extends {Component}
 */
@resizeConnect
@eventConnect
class View3D extends Component {
  constructor(props) {
    super(props);
    this.objs = [];
    this.state = {
      percent: 0,
      loading: true,
      loadingResInfo: null,
      showObjSpinner: false,
      objs: null,
      asyncModels: null,
      isAllDone: false,
      startAsyncLoad: false,
      showExplain: false,
      showScreenSaver: false,
      markerList: [],
      markers: {
        patrol: [],
        risk: [],
        video: [],
        data: [],
        dynamicRingData: []
      },
      excludeObjs: null,
      currentObj: null,
      markerType: null,
      floorType: 'all',
      alarms: {
        thirdFloor: [],
        sixthFloor: [],
        xyFloor: []
      },
      alarmData: [],
      markerData: [],
      orgCode: this.props.orgCode,
      pickVisable: false,
      pickDialog: false,
      pickData: {
        pickedPosition: '',
        floorType: ''
      }
    };

    // 判断城市
    this.city = { isXian: true, isXianyang: false };
    let view3dFile = '/threeres/models/xian-ccpc/index.json';
    let cityCode = this.props.city;
    if (cityCode === 'xianyang') {
      this.city.isXian = false;
      this.city.isXianyang = true;
      this.city.isXidajie = false;
      view3dFile = '/threeres/models/xianyang-ccpc/index.json';
    } else if (cityCode === 'xidajie') {
      this.city.isXian = false;
      this.city.isXianyang = false;
      this.city.isXidajie = true;
      view3dFile = '/threeres/models/xidajie-ccpc/index.json';
    }

    // 加载三维模型文件及数据
    getObjFromNet(view3dFile, (objs, asyncModels) => {
      this.setState({
        objs,
        asyncModels
      });
    });
    this.lensLevel = this.city.isXidajie ? LENS_LEVEL.SUB : LENS_LEVEL.ROOT;

    this.loadingManager = {
      onLoad: () => {
        console.log(`load all resource success!`);
        this.setState({
          loading: false,
          showObjSpinner: false,
          loadingResInfo: null
        });
      },
      onProgress: (item, loaded, total) => {
        this.setState({
          loadingResInfo: {
            total, current: loaded, url: item
          }
        });
      }
    };

    this.layerConfig = desigerHelperConfig.layerConfig || {};
  }

  componentDidMount() {
    this._registerEvents(); // 注册事件
    this._bindPubSubEvents(); // 绑定事件
    this._bindRulesPubSubEvents();//获取风险点告警
    this.loadAlarmData();//获取告警数据
    // this.props.onRef(this);//传输子组件对象

  }


  componentWillUnmount() {

    this.objAnchorHelper && this.objAnchorHelper.destroy();
    this.infoHelper && this.infoHelper.destroy();

    //  定时器销毁
    this.interval && clearInterval(this.interval);
    this.timer && clearTimeout(this.timer);




  }

  /**
   * 事件注册
   */
  _registerEvents = () => {
    // 相机视角缩放
    this.r3d.on('camera_zoom', evt => {
      // console.log('main camera_zoom', evt);
    });

    // 相机视角改变
    this.r3d.on('camera_change', (evt) => {
      // console.log('main camera_change', evt);
    });

    // 双击事件
    this.r3d.on('dblclick', evt => {
      // console.log('dblclick', evt);
      if (evt.button !== 0) {
        return;
      }
      if (!evt.object) {
        // 返回上级（单击空白处）
        this.backPreviousLevelView();
      }
    });

    // 键盘事件
    this.r3d.on('keydown', evt => {
      // console.log('keydown', evt);
      // 返回上级（退格）
      if (evt.code === 'Backspace') {
        this.backPreviousLevelView();
      }
    });

    // 单击事件
    this.r3d.on('click', evt => {
      console.log('click', evt);

      if (LENS_LEVEL.SUB !== this.lensLevel && evt.button === 2) {
        return;
      }

      if (evt.object && evt.object.type === 'Mesh'){
        const parentObj = evt.object.parent;
        const userData = parentObj.userData;
        if (userData && this.lensLevel !== LENS_LEVEL.ROOT && userData.type === 'cabinet') {
          // 机柜点击事件
          this.onCabinetClick(parentObj, userData);

          // 清除点标记
          this.clearMarkers();

          // 信息面板
          // setTimeout(() => {this.createInfoPanel(parentObj, userData.name);}, 1500);

          // 设置当前层级
          this.lensLevel = LENS_LEVEL.SUN;

          // 当前模型对象
          this.setState({ currentObj: parentObj });
          // 处理跳跃
          this.lensJumpFactory.process(parentObj);

          this.setState({
            pickVisable: false,
            pickDialog: false
          });
        }
      }
    });

    // 鼠标右键点击事件
    this.r3d.on('mousedown', evt => {
      console.log('mousedown', evt);

      let button = evt.button;
      if (LENS_LEVEL.ROOT === this.lensLevel || button !== 2 || !evt.pickedPosition) {
        return;
      }
      const { floorType, orgCode } = this.state;
      let pickData = { pickedPosition: evt.pickedPosition, floorType, orgCode };
      this.setState({
        pickDialog: true,
        pickData
      });
    });

    // 鼠标移入事件
    this.r3d.on('mouseover', evt => {
      // console.log('mouseover', evt);
      const _this = this;
      // 设置楼层勾边标记
      _this.setToggleOutline();
      if (evt.object && evt.object.type === 'Mesh') {
        const obj = evt.object;
        const userData = obj.parent.userData;
        // 重新设置 outline 风格
        _this.setToggleOutlineSelected();
        if (userData && (userData.key === FLOOR.FLOOR_3 || userData.key === FLOOR.FLOOR_6 || userData.key === FLOOR.XY_FLOOR_3)) {
          _this.outlineFactory.toggleOutline(obj);
        } else if (_this.lensLevel === LENS_LEVEL.SUB && (userData.type === 'cabinet' || userData.type === 'cabinet_box')) {
          _this.outlineFactory.toggleOutline(obj);
        } else {
          // 重新设置 outline 风格
          _this.setToggleOutlineDefault();

          // 清除选中
          // _this.outlineFactory.toggleOutline([]);
          // info信息框不显示
          if (_this.lensLevel !== LENS_LEVEL.SUN){
            _this.infoHelper.toggleVisible(false);
          }
        }
      }
    });

  };

  /**
   * 事件绑定
   */
  _bindPubSubEvents = () => {
    this.props.subscribe(eventTopics.base3d_view, (topic, data) => {
      if (isPointEvent(topic)) {
        this.setState({ alarmData: data });
        this.transferAlarmData();
      } else if (isControllerEvent(topic)) {
        executeView3dCMD(this, topic, data);
      } else if (isManualOperate(topic)) {
        parseManual(this, topic, data);
      } else if (topic === eventTopics.view_fresh) {
        this.executeOperate({ key: 'fitview' });
        this.setState({ markers: {} });
      }
    });
  };


  _bindRulesPubSubEvents = () => {
    this.props.subscribe(eventTopics.fromws, (topic, content) => {
      let data = content.data;
      console.log('消息类型--->' + topic);
      console.log('data==' + JSON.stringify(data));
      //this.riskAlarmDataTwinkle(data);
      switch (topic){
        case 'base3d.fromws.riskSituation_flicker':
          console.log('风险触发风险点闪烁~~~~~~~~~~~~~~~~~~~~');
          this.flickerTroubleMarkers(this, data);//风险触发风险点闪烁
          break;
        case 'base3d.fromws.riskSituation_colour':
          console.log('风险触发风险点颜色改变~~~~~~~~~~~~~~~~~~~~');
          this.flickerTroubleMarkers(this, data);//风险触发风险点闪烁
          break;
        default:
          console.log(topic,'：类型不支持');
      }
    });
  };

  /**
   * 改变风险点颜色和闪烁
   *
   * @memberof View3D
   */
  flickerTroubleMarkers = (instance, content) => {
    let { markerType, orgCode } = this.state;
    let { bizobj } = content;
    initView3DRiskFromBizAction(markerType, orgCode).then(data => {
      let target;
      data.map(o => {
        if (o.id === bizobj.id) {
          target = o;
        }
      });
      this.updateMarker(target);
    });
  };

  /**
   * 图形创建完成
   *
   * @memberof View3D
   */
  onGraphCreated = ({ cache, cameraFactory, sceneFactory, outlineFactory, r3d }) => {
    this.cameraFactory = cameraFactory; // 相机控制器
    this.sceneFactory = sceneFactory; // 场景控制器
    this.outlineFactory = outlineFactory; // 勾边控制器
    this.r3d = r3d; // 核心处理器
    this.cache = cache;

    // 重新设置 outline 风格
    this.setToggleOutlineDefault();

    // 设置 UI
    this.objAnchorHelper = new ObjAnchorHelper({
      r3d,
      cameraFactory,
      sceneFactory
    });

    // 设置 Infowindow
    this.infoHelper = new InfoHelper({
      r3d,
      cameraFactory,
      sceneFactory,
      // element: this.createInfowindow('提示框')
      title: '默认标题'
    });
    this.infoHelper.toggleVisible(false);

    // 设置 摄像机跳跃
    this.lensJumpFactory = new LensJumpFactory({
      r3d,
      cameraFactory,
      sceneFactory,
      cameraEffect: this.city.isXian ? desigerHelperConfig.cameraEffect : this.city.isXianyang ? desigerHelperConfig.xyCameraEffect : desigerHelperConfig.xdjCameraEffect
    });
  };

  /**
   * 创建信息窗
   *
   * @memberof View3D
   */
  createInfowindow = (text) => {
    const div = document.createElement('div');
    div.style.position = 'absolute';
    div.className = 'three-ui-infowindow';
    div.innerText = text;
    return div;
  }

  /**
   * 创建信息面板
   *
   * @memberof View3D
   */
  createInfoPanel = (parentObj, name) => {
    // 提示信息
    this.objAnchorHelper.create({
      parent: parentObj,
      element: createPanel(name),
      position: [3.5, 4, 0]
    });
  }

  /**
   * 加载完成
   *
   * @memberof View3D
   */
  onComplete = obj => {
    const _this = this;
    if (!obj.isForceParent ) {
      obj.on('click', evt => {
        // console.log('obj click', evt);

        _this.outlineFactory.toggleOutline(evt.object);
        _this.focusObject(evt.object);
      });
    }
    // 处理跳跃
    this.lensJumpFactory.process(obj);

    // 设置玻璃半透明
    _this.setGlassReflection(obj);

    // 存储模型数据
    const baseObj = new BaseObjHelper({ obj });
    obj.baseObjHelper = baseObj;
    _this.objs.push(obj);
  };

  /**
   * 所有数据加载完成
   *
   * @memberof View3D
   */
  onAllDone = (objGroup) => {
    this.sceneFactory.level.change(objGroup);
    // this.cameraFactory.fitView(this.city.isXian ? desigerHelperConfig.cameraEffect : this.city.isXianyang ? desigerHelperConfig.xyCameraEffect : desigerHelperConfig.xdjCameraEffect);
    this.setRootFitView();
    this.setState({ startAsyncLoad: true });
    this.props.onLoadCompleted();

    // 加载告警数据
    this.timer = setTimeout(() => {
      this.transferAlarmData();
      let flag= this.props.flag;
      debugger
      if(flag&&flag===1){
        let pointName= this.props.pointName;
        let pointAttrs= this.props.pointAttrs;
        let pid= this.props.pid;
       //楼层
       let floor= this.props.floor;
       let pointtype= this.props.pointtype;

     
     
       if(this.props.city==='xian'){
        this.onAlarmClick1(pointtype,'floor_'+floor,{

          'authOrg': null,
          'code': "",
          'content': "",
          'id': 0,
          'isAlarm': 0,
          'pointAttrs': `{"position":"`+pointAttrs+`","storey":"`+floor+`"}`,
          'pointId': pid,
          'pointName': pointName,
          'pointType': "3",
          'sourceId': null,
          'updateDate': "",

        });
       }else{

        this.onAlarmClick1(pointtype,'xy_floor_'+floor,{

          'authOrg': null,
          'code': "",
          'content': "",
          'id': 0,
          'isAlarm': 0,
          'pointAttrs': `{"position":"`+pointAttrs+`","storey":"`+floor+`"}`,
          'pointId': pid,
          'pointName': pointName,
          'pointType': "3",
          'sourceId': null,
          'updateDate': "",

        });

       }



     
      }
    }, 1500);

    // 设置楼层勾边标记
    this.setToggleOutline();



  };

  /**
   * 获取告警数据
   *
   * @memberof View3D
   */
  loadAlarmData = () => {
    getAlarms().then(data => {
      this.setState({ alarmData: data });
    });
  }

  /**
   * Worker加载中
   *
   * @memberof View3D
   */
  onWorkerLoading = ({
    loading, // 加载模型
    percent, // 加载进度
    error,
    rendering // 是否正在渲染
  } = {}) => {
    this.setState({ percent });
    console.log('from worker:', loading, percent, rendering);
  }

  /**
   * Worker初始化完成
   *
   * @memberof View3D
   */
  onAfterWorkerInit = (workerObjGroup) => {
    this.setState({ isAllDone: true });
    // 处理跳跃
    this.lensJumpFactory.process(workerObjGroup);
  };

  /**
   * 加载进度
   *
   * @memberof View3D
   */
  onLoadProgress = (xhr) => {
    if (xhr.lengthComputable) {
      var percentComplete = (xhr.loaded / xhr.total) * 100;
      const percent = Math.round(percentComplete, 2);
      console.log(`model ${percent}% downloaded`);
      if (percent === 100){
        this.setState({ percent: 10 });
      } else {
        this.setState({ percent });
      }
    }
  }

  /**
   * 焦点位置设置
   *
   * @memberof View3D
   */
  focusPosition = position => {
    if (position) {
      this.cameraFactory.flyTo({
        position,
        duration: 1000
      });
    }
  };

  /**
   * 焦点对象
   *
   * @memberof View3D
   */
  focusObject = (object, isFlyToSun) => {
    const _this = this;
    this.clearMarkers();
    this.clearAlarms();
    if (object && object.foreignKey) {
      this.cameraFactory.flyTo({
        position: [269.11, 83.06, 103.80],
        target: object,
        duration: 1000,
        // 飞行到具体的 obj 之后，执行进入层级操作
        onComplete() {
          console.log('fly done!', object);
          // 进入子层级
          if (object.foreignKey) {
            _this.lensJumpFactory.jumpInByForeignKey(object.foreignKey, excludeObj => {
              // 处理非该层级的物体 （fadeOut）
              if (excludeObj.userData.type !== 'cabinet') {
                _this.fadeOut(excludeObj);
                // 如果未隐藏
                excludeObj.visible = false;
              }
            });

            // 设置天空颜色
            _this.sceneFactory.skyBox = desigerConf.sceneOptions.skyBox;

            // 设置层级
            _this.lensLevel = LENS_LEVEL.SUB;
            _this.setFloorType(object.userData.key);

            if (isFlyToSun !== undefined && isFlyToSun === true) {
              _this.flyToCabinet(object);
            }

          }
        }
      });
    }
  };

  /**
   * 机柜点击加载事件
   *
   * @memberof View3D
   */
  onCabinetClick = (parentObj, userData) => {
    // console.log('onCabinetClick', parentObj);
    this.setState({ currentObj: parentObj });

    this.outlineFactory.toggleOutline([]);

    // 隐藏其他模型
    if (parentObj.parent && parentObj.parent.children) {
      let objs = [];
      parentObj.parent.children.forEach(excludeObj => {
        objs.push(excludeObj);
        this.setState({
          excludeObjs: objs
        });
        if (excludeObj.name !== parentObj.name) {
          this.fadeOut(excludeObj);
          // excludeObj.visible = false;
        }
      });
    }

    // 显示当前模型
    if (parentObj.children) {
      const _this = this;
      // 显示当前选中机柜
      parentObj.children.forEach(obj => {
        if (obj) {
          // 进入当前模型
          this.cameraFactory.flyTo({
            position: userData.position ? userData.position : [366.68, 89.87, 160.03],
            target: userData.target ? userData.target : [348.49, 89.87, 132.55],
            duration: 1000,
            onComplete() {
              _this.lensJumpFactory.fadeIn(obj);
            }
          });
          // 设置视角
          _this.setCabinetFitView(userData);
          // 设置层级
          _this.lensLevel = LENS_LEVEL.SUN;
        }
      });
    }

    this.setCabinetFitView(userData);
  }

  /**
   * 设置楼层勾边标记
   *
   * @memberof View3D
   */
  setToggleOutline = () => {
    let _objs = [];
    this.objs.map(_obj=>{
      const userData = _obj.userData;
      if (userData && (userData.key === FLOOR.FLOOR_3 || userData.key === FLOOR.FLOOR_6 || userData.key === FLOOR.XY_FLOOR_3)) {
        _objs.push(_obj);
      }
    });
    this.outlineFactory.toggleOutline(_objs);
  }

  /**
   * 设置楼层勾边标记为默认颜色
   *
   * @memberof View3D
   */
  setToggleOutlineDefault = () => {
    this.outlineFactory.outlineConfig = {
      visibleEdgeColor: '#ffe2ad',
      hiddenEdgeColor: '#ffe2ad'
    };
  }

  /**
   * 设置楼层勾边标记为选中的颜色
   *
   * @memberof View3D
   */
  setToggleOutlineSelected = () => {
    this.outlineFactory.outlineConfig = {
      visibleEdgeColor: '#f8a303',
      hiddenEdgeColor: '#ffe2ad'
    };
  }

  /**
   * 设置楼层类型
   *
   * @memberof View3D
   */
  setFloorType = (key) => {
    // 设置初始视角
    if (key === FLOOR.FLOOR_3) {
      this.setFloorThreeFitView();
    } else if (key === FLOOR.FLOOR_6) {
      this.setFloorSixFitView();
    } else { // 咸阳
      this.setXYFloorThreeFitView();
    }
  }

  /**
   * 淡出
   *
   * @memberof View3D
   */
  fadeOut = obj => {
    const baseObjHelper = new BaseObjHelper({ obj });
    baseObjHelper.fadeOut();
  };

  /**
   * 点类型改变事件
   *
   * @memberof View3D
   */
  changeMarkerType = (item, isCancel) => {
    const { markers } = this.state;
    if (isCancel) {
      markers[item.type] = [];
      this.setState({ markers });
    } else {
      this.setState({ markerType: item.type });
      if (this.lensLevel === LENS_LEVEL.SUN && item.type === 'impEquipment') {
        // 网络设备、服务器和虚拟设备
        this.asyncLoadMarkerData(item.type);
      } else if (this.lensLevel === LENS_LEVEL.SUB) {
        this.asyncLoadMarkerData(item.type);
      }
    }
  };

  /**
   * 异步加载点数据
   *
   * @memberof View3D
   */
  asyncLoadMarkerData = markerType => {
    // 加载告警数据
    this.loadAlarmData();
    const { orgCode } = this.state;
    this.clearMarkers();
    //风险点访问风险模块
    if (markerType === 'riskSource'){
      initView3DRiskFromBizAction(markerType, orgCode).then(data => {
        this.initView3DData(markerType, data);
      });
    } else {
      initView3DFromBizAction(markerType, orgCode).then(data => {
        this.initView3DData(markerType, data);
      });
    }
  }

  /**
   * 重构数据
   *
   * @memberof View3D
   */
  initView3DData = (markerType, data) =>{
    const { markers, floorType, alarmData } = this.state;
    let markerData = [];
    if (data) {// 点数据按楼层显示
      if (LENS_LEVEL.SUB === this.lensLevel || LENS_LEVEL.SUN === this.lensLevel) {
        data.forEach(item=> {
          if (floorType === item.objKey) {
            markerData.push(item);
          }
        });
      } else {
        markerData = data;
      }

      if (alarmData) {
        markerData.forEach(marker => {
          const markerId = parseInt(marker.id);
          alarmData.forEach(alarm => {
            const pointType = parseInt(alarm.pointType);
            const alarmMarkerType = pointType === 3 ? 'patrol' : pointType === 2 ? 'dynamicRingData' : 'impEquipment';
            if (alarm.pointId === markerId && markerType === alarmMarkerType) {
              marker.twinkle = true;
            }
          });
        });
      }

      // 点数据分类
      markers[markerType] = markerData;
      this.setState({ markers, markerData });
    }
  }

  /**
   * 风险点闪烁
   *
   * @memberof View3D
   */
  riskAlarmDataTwinkle = (alarmData) =>{
    const { markers, markerData, markerType } = this.state;
    if (alarmData.bizobj) {
      markerData.forEach(marker => {
        const markerId = parseInt(marker.id);
        const pointId = parseInt(alarmData.bizobj.id);
        if (pointId === markerId) {
          marker.twinkle = true;
        }
      });
    }

    // 点数据分类
    markers[markerType] = markerData;
    this.setState({ markers });
  }

  /**
   * 设置初始视角
   *
   * @memberof View3D
   */
  setRootFitView = () => {
    this.cameraFactory.fitView(this.city.isXian ? desigerHelperConfig.cameraEffect :
      this.city.isXianyang ? desigerHelperConfig.xyCameraEffect : desigerHelperConfig.xdjCameraEffect);
  }

  /**
   * 设置西大街初始视角
   *
   * @memberof View3D
   */
  setXidajieFitView = () => {
    this.cameraFactory.fitView(desigerHelperConfig.xdjCameraEffect);
  }

  /**
   * 设置三楼初始视角
   *
   * @memberof View3D
   */
  setFloorThreeFitView = () => {
    this.cameraFactory.fitView(desigerHelperConfig.thirdFloorCameraEffect);
    this.setState({ floorType: FLOOR.FLOOR_3 });
  }

  /**
   * 设置三楼初始视角 - 咸阳
   *
   * @memberof View3D
   */
  setXYFloorThreeFitView = () => {
    this.cameraFactory.fitView(desigerHelperConfig.xyThirdFloorCameraEffect);
    this.setState({ floorType: FLOOR.FLOOR_3 });
  }

  /**
   * 设置六楼初始视角
   *
   * @memberof View3D
   */
  setFloorSixFitView = () => {
    this.cameraFactory.fitView(desigerHelperConfig.thirdFloorCameraEffect);
    this.setState({ floorType: FLOOR.FLOOR_6 });
  }

  /**
   * 设置机柜初始视角
   *
   * @memberof View3D
   */
  setCabinetFitView = (userData) => {
    this.cameraFactory.fitView({
      position: userData.position ? userData.position : desigerHelperConfig.cabinetCameraEffect.position,
      target: userData.target ? userData.target : desigerHelperConfig.cabinetCameraEffect.target,
      duration: desigerHelperConfig.cabinetCameraEffect.duration
    });
    this.setState({ floorType: FLOOR.FLOOR_0 });
  }

  /**
   * 设置玻璃透明度
   *
   * @param {*} obj
   * @memberof View3D
   */
  setGlassReflection(obj) {
    if (obj.userData.type === 'glass') {
      const baseObjHelper = new BaseObjHelper({ obj });
      baseObjHelper.fade({ duration: 1000 }, 0.77);
    }
  }

  /**
   * 设置楼的展示效果
   *
   * @param {*} obj
   * @memberof View3D
   */
  setFloorViewEffect(obj, isAlert) {
    if (obj.userData.type === 'floor') {
      const baseObj = obj.baseObjHelper;
      baseObj.style.color = isAlert > 0 ? '#FF5252' : '#66BB6A';
      // baseObj.style.opacity = 0.8;
      // baseObj.style.emissive = '#F56968';

      if (isAlert) {
        this.interval = setInterval(() => {
          obj.baseObjHelper.style.color = obj.baseObjHelper.style.color === '#FF5252' ? '' : '#FF5252';
        }, 800);
      }
    }
  }

  /**
   * 清除楼层展示效果
   *
   * @memberof View3D
   */
  clearFloorViewEffect() {
    this.objs.forEach(obj=>{
      if (obj.userData.type === 'floor') {
        obj.baseObjHelper.style.color = '';
      }
    });
  }

  /**
   * 返回三维最顶层
   *
   * @memberof View3D
   */
  backRootView = () => {
    const _this = this;
    this.lensJumpFactory.jumpRoot(obj => {
      _this.lensJumpFactory.fadeIn(obj);
      _this.setGlassReflection(obj);
    });
    // this.cameraFactory.fitView(this.city.isXian ? desigerHelperConfig.cameraEffect : this.city.isXianyang ? desigerHelperConfig.xyCameraEffect : desigerHelperConfig.xdjCameraEffect);
    this.setRootFitView();
    this.lensLevel = this.city.isXidajie ? LENS_LEVEL.SUB : LENS_LEVEL.ROOT;
    this.clearMarkers();

    this.timer = setTimeout(() => {
      this.loadAlarmData();
      this.transferAlarmData();
    }, 1000);

    // 设置楼层标记
    this.setToggleOutline();
  }

  /**
   * 返回三维第二层
   *
   * @memberof View3D
   */
  backSubView = () => {
    this.state.excludeObjs.forEach(obj => {
      this.lensJumpFactory.fadeIn(obj);
    });
    // 设置初始视角
    this.city.isXian ? this.setFloorThreeFitView() : this.setXYFloorThreeFitView();
    // 设置层级
    this.lensLevel = LENS_LEVEL.SUB;
    // this.clearMarkers();
  }

  /**
   * 返回上级
   *
   * @memberof View3D
   */
  backPreviousLevelView = () => {
    if (this.lensLevel === LENS_LEVEL.SUN) {
      this.backSubView();
      this.lensLevel = LENS_LEVEL.SUB;
      if (this.state.floorType === FLOOR.FLOOR_0) {this.setState({ floorType: FLOOR.FLOOR_3 });}
    } else if (this.lensLevel === LENS_LEVEL.SUB && !this.city.isXidajie) {
      this.backRootView();
      this.lensLevel = LENS_LEVEL.ROOT;
    } else if (this.lensLevel === LENS_LEVEL.SUB && this.city.isXidajie) {
      this.props.indexViewChange(false);
    } else if (this.lensLevel === LENS_LEVEL.ROOT) {
      this.props.indexViewChange(false);
    }
    // 清除地图上的点
    // this.clearMarkers();
    this.clearAlarms();

    // 清除选中
    // this.outlineFactory.toggleOutline([]);
    // info信息框不显示
    this.infoHelper.toggleVisible(false);

    this.setState({
      pickVisable: false,
      pickDialog: false
    });
  }

  /**
   * 执行操作
   *
   * @memberof View3D
   */
  executeOperate = ({ key, value }) => {
    // 最佳视角，即恢复默认视角
    if (key === 'fitview') {
      if (LENS_LEVEL.ROOT === this.lensLevel) {
        // this.cameraFactory.fitView(this.city.isXian ? desigerHelperConfig.cameraEffect : this.city.isXianyang ? desigerHelperConfig.xyCameraEffect : desigerHelperConfig.xdjCameraEffect);
        this.setRootFitView();
      } else if (LENS_LEVEL.SUB === this.lensLevel) {
        this.city.isXian ? this.setFloorThreeFitView() :  this.city.isXianyang ? this.setXYFloorThreeFitView() : this.setXidajieFitView();
      } else if (LENS_LEVEL.SUN === this.lensLevel) {
        this.setCabinetFitView(this.state.currentObj.userData);
      }
    }
    // 操作说明
    else if (key === 'explain') {
      this.setState({
        showExplain: value
      });
    }
    // 返回上一级
    else if (key === 'back') {
      this.backPreviousLevelView();
    }
    // 坐标拾取
    else if (key === 'pick') {
      if (LENS_LEVEL.ROOT === this.lensLevel) {
        return;
      }

      let { pickVisable, pickDialog } = this.state;
      if (!pickVisable) {
        pickVisable = true;
        pickDialog = false;
        Toast['success']({ title: '坐标拾取已启用', content: '在三维上点击鼠标右键，即可获取该点的坐标。' });
      } else {
        pickVisable = false;
        pickDialog = false;
        Toast['success']({ title: '坐标拾取已关闭' });
      }

      this.setState({
        pickVisable,
        pickDialog
      });
    }
  };

  /**
   * 控件说明关闭事件
   *
   * @memberof View3D
   */
  handleExplainClose = () => {
    this.setState({
      showExplain: false
    });
  };

  /**
   * 清除点标记
   *
   * @memberof View3D
   */
  clearMarkers = () => {
    const { markers } = this.state;
    markers['patrol'] = [];
    markers['riskSource'] = [];
    markers['impEquipment'] = [];
    markers['monitorEquipment'] = [];
    markers['dynamicRingData'] = [];
    markers['video'] = [];

    this.setState({
      markers
    });
  };

  /**
   * 更新点标记
   *
   * @memberof View3D
   */
  updateMarker = data => {
    //console.log(data, 'updateMarker');
    const { type, id } = data;
    const { markers } = this.state;
    const markersArr = markers[type] || [];
    if (markersArr.length > 0) {
      let needUpdate = false;
      const newArr = markersArr.map(marker => {
        if (marker.id === id) {
          needUpdate = true;
          return {
            ...marker,
            ...data
          };
        }
        return marker;
      });
      if (needUpdate) {
        markers[type] = newArr;
        this.setState({
          markers
        });
      }
    }
  };

  /**
   * 清除告警
   *
   * @memberof View3D
   */
  clearAlarms = () => {
    const { alarms } = this.state;
    alarms['thirdFloor'] = [];
    alarms['sixthFloor'] = [];
    alarms['xyFloor'] = [];

    // 清除楼层颜色标记
    this.clearFloorViewEffect();
    this.interval && clearInterval(this.interval);

    this.setState({
      alarms
    });
  };

  /**
   * 加载告警数据
   *
   * @memberof View3D
   */
  transferAlarmData = () => {

    let { alarmData, orgCode } = this.state;
    const { isAllDone, alarms, markerType } = this.state;
    if (!isAllDone || this.city.isXidajie) {
      return;
    }
    this.clearMarkers();
    this.clearAlarms();

    if (!utils.isEmpty(alarmData) && utils.isArray(alarmData)){
      alarmData = alarmData.filter(e=>{ //过滤通道信息
        return e.pointType !== '4';
      });
    }
    const thirdFloorAlarmData = [];
    const sixthFloorAlarmData = [];
    const xyFloorAlarmData = [];
    let thirdFloorAlarmStatus = false;
    let sixthFloorAlarmStatus = false;
    let xyFloorAlarmStatus = false;

    let dictionaryList = lsTool.read('dictionaryList');
    let dicCodeList = JSON.parse(dictionaryList);
    let city = this.getSelectCityByOrgCode(orgCode,dicCodeList);

    if (alarmData && !utils.isEmpty(alarmData) && utils.isArray(alarmData)) {
      alarmData.forEach(item => {
        const pointAttrs = JSON.parse(item.pointAttrs);
        if (city === 'xian' && (item.code.startsWith(orgCode) || item.authOrg && item.authOrg.indexOf(orgCode)!==-1) && pointAttrs && pointAttrs !== '' && pointAttrs !== undefined) {
          if (pointAttrs.storey === '3' || pointAttrs.storey === 'floor_3') {// 三楼数据
            thirdFloorAlarmData.push(item);
          } else if (pointAttrs.storey === '6' || pointAttrs.storey === 'floor_6') {// 六楼数据
            sixthFloorAlarmData.push(item);
          }
        } else if (city === 'xianyang' && (item.code.startsWith(orgCode)|| item.authOrg &&item.authOrg.indexOf(orgCode)!==-1)) {// 咸阳数据
          xyFloorAlarmData.push(item);
        }
      });
    }


    if (this.lensLevel === LENS_LEVEL.ROOT) {
      // 三楼告警
      if (thirdFloorAlarmData && thirdFloorAlarmData.length > 0) {
        let thirdFloorAlarms = [];
        thirdFloor.panel.data = thirdFloorAlarmData;
        thirdFloorAlarms.push(thirdFloor.panel);
        // thirdFloorAlarms.push(thirdFloor.alarm);
        alarms['thirdFloor'] = thirdFloorAlarms;
        thirdFloorAlarmStatus = true;
        console.log(thirdFloorAlarms);
      }

      // 六楼告警
      if (sixthFloorAlarmData && sixthFloorAlarmData.length > 0) {
        let sixthFloorAlarms = [];
        sixthFloor.panel.data = sixthFloorAlarmData;
        sixthFloorAlarms.push(sixthFloor.panel);
        // sixthFloorAlarms.push(sixthFloor.alarm);
        alarms['sixthFloor'] = sixthFloorAlarms;
        sixthFloorAlarmStatus = true;
      }

      // 咸阳告警
      if (xyFloorAlarmData && xyFloorAlarmData.length > 0) {
        let xyFloorAlarms = [];
        xyFloor.panel.data = xyFloorAlarmData;
        xyFloorAlarms.push(xyFloor.panel);
        alarms['xyFloor'] = xyFloorAlarms;
        xyFloorAlarmStatus = true;
        console.log(xyFloorAlarms);
      }

      this.setState({ alarms });

        // 设置楼层预警颜色
      this.objs.forEach(obj => {
        // 设置三楼楼层颜色
        if (obj.userData.key === FLOOR.FLOOR_3) {
          this.setFloorViewEffect(obj, thirdFloorAlarmStatus);
        }
        // 设置六楼楼层颜色
        if (obj.userData.key === FLOOR.FLOOR_6 && obj.userData.type === 'floor') {
          this.setFloorViewEffect(obj, sixthFloorAlarmStatus);
        }
        // 设置咸阳楼层颜色
        if (obj.userData.key === FLOOR.XY_FLOOR_3) {
          this.setFloorViewEffect(obj, xyFloorAlarmStatus);
        }
      });

    } else if (this.lensLevel === LENS_LEVEL.SUB) {
      let item = { 'type': markerType };
      this.changeMarkerType(item, false);
    } else if (this.lensLevel === LENS_LEVEL.SUN && markerType === 'impEquipment') {
      let item = { 'type': 'impEquipment' };
      this.changeMarkerType(item, false);
    }
  }


  /**
   * 根据城市的orgCode，返回城市名称
   */
  getSelectCityByOrgCode = (orgCode,dictionaryList) => {
    let city = null;
    dictionaryList.map(item =>{
    if(item.dictDataValue === orgCode){
        city=item.dictDataKey;
      }
    })
    return city;
 }


  /**
   * 告警信息点击事件
   *
   * @memberof View3D
   */
  onAlarmClick = (type, item) => {
    console.log(item);
    this.clearAlarms();
    this.clearMarkers();
    const _this = this;
    const pointType = parseInt(item.pointType);
    if (type === FLOOR.FLOOR_3) {
      _this.objs.forEach( obj => {
        if (obj.userData && obj.userData.key === FLOOR.FLOOR_3) {
          if (!obj.isForceParent ) {
            _this.outlineFactory.toggleOutline(obj);
            if (pointType === 1) {
              _this.focusObject(obj, true);
              setTimeout(() => {_this.executeOperate({ key: 'fitview' });}, 1200);
            } else {
              _this.focusObject(obj);
            }

            // 延迟显示告警点
            setTimeout(() => {_this.renderAlarmMarker(type, item);}, 1100);
          }
        }
      });
    }

    if (type === FLOOR.FLOOR_XY) {
      _this.objs.forEach( obj => {
        if (obj.userData && obj.userData.key === FLOOR.XY_FLOOR_3) {
          if (!obj.isForceParent ) {
            _this.outlineFactory.toggleOutline(obj);
            if (pointType === 1) {
              _this.focusObject(obj, true);
              setTimeout(() => {_this.executeOperate({ key: 'fitview' });}, 1200);
            } else {
              _this.focusObject(obj);
            }

            // 延迟显示告警点
            setTimeout(() => {_this.renderAlarmMarker(type, item);}, 1100);
          }
        }
      });
    }
  }


  onAlarmClick1 = (pointtype,type, item) => {
    this.clearAlarms();
     this.clearMarkers();
    const _this = this;
    const pointType = parseInt(item.pointType);
    if (type === FLOOR.FLOOR_3) {
      _this.objs.forEach( obj => {
        if (obj.userData && obj.userData.key === FLOOR.FLOOR_3) {
          if (!obj.isForceParent ) {
            _this.outlineFactory.toggleOutline(obj);

              _this.focusObject(obj);


            // 延迟显示告警点
            setTimeout(() => {_this.renderAlarmMarker1(pointtype,type, item);}, 1100);
          }
        }
      });
    }


    if (type === FLOOR.FLOOR_6) {
      _this.objs.forEach( obj => {
        if (obj.userData && obj.userData.key === FLOOR.FLOOR_6) {
          if (!obj.isForceParent ) {
            _this.outlineFactory.toggleOutline(obj);

              _this.focusObject(obj);


            // 延迟显示告警点
            setTimeout(() => {_this.renderAlarmMarker1(pointtype,type, item);}, 1100);
          }
        }
      });
    }





    if (type === FLOOR.XY_FLOOR_3) {
      _this.objs.forEach( obj => {
        if (obj.userData && obj.userData.key === FLOOR.XY_FLOOR_3) {
          if (!obj.isForceParent ) {
            _this.outlineFactory.toggleOutline(obj);

              _this.focusObject(obj);

            // 延迟显示告警点
            setTimeout(() => {_this.renderAlarmMarker1(pointtype,type, item);}, 1100);
          }
        }
      });
    }
  }


  /**
   * 进入机柜
   *
   * @memberof View3D
   */
  flyToCabinet = (object) => {
    const _this = this;
    _this.lensLevel = LENS_LEVEL.SUN;
    object.parent.children.forEach(childrenObj => {
      if (childrenObj.primaryKey === object.foreignKey) {
        childrenObj.children.forEach(obj => {
          if (obj){
            const userData = obj.userData;
            if (userData && userData.type === 'cabinet') {
              _this.onCabinetClick(obj, userData);
            }
          }
        });
      }
    });
  }




  renderAlarmMarker1 = (pointtype,type, item) => {
    const { markers } = this.state;
    const pointAttrs = JSON.parse(item.pointAttrs);
    if (pointAttrs.position) {
      let strs = new Array();
      strs = pointAttrs.position.split(',');
      let pointPosition = {
        x: strs[0],
        y: strs[1],
        z: strs[2]
      };
      const pointType = parseInt(item.pointType);

      alarmPoint.id = item.pointId;
      let levelType = '';
      if (pointType === 3){//巡检
        levelType = '3';
      } else if (pointType === 2){//动环
        levelType = '01';
      } else if (pointType === 6){ //火探
        levelType = '02';
      } else if (pointType === 1){//网络设备
        levelType = '01';
      } else if (pointType === 5){//虚拟设备（自动巡检设备）
        levelType = '03';
      }
      alarmPoint.level = levelType;
      alarmPoint.objType = levelType;
      alarmPoint.objKey = type;
      alarmPoint.position = pointPosition;
      alarmPoint.title = item.pointName;
      alarmPoint.sourceId = item.sourceId;
      alarmPoint.twinkle = pointtype;
      alarmPoint.type = pointType === 3 ? 'patrol' : ((pointType === 2)||(pointType === 6)) ? 'dynamicRingData' : 'impEquipment';
      let points = [];
      points.push(alarmPoint);
      markers[alarmPoint.type] = points;

      //console.log(markers);

      if (this.lensLevel === LENS_LEVEL.SUB || this.lensLevel === LENS_LEVEL.SUN) {
        this.setState({
          markers
        });
      }
    }
  }

  /**
   * 生成告警点
   *
   * @memberof View3D
   */
  renderAlarmMarker = (type, item) => {
    const { markers } = this.state;
    const pointAttrs = JSON.parse(item.pointAttrs);
    if (pointAttrs.position) {
      let strs = new Array();
      strs = pointAttrs.position.split(',');
      let pointPosition = {
        x: strs[0],
        y: strs[1],
        z: strs[2]
      };
      const pointType = parseInt(item.pointType);

      alarmPoint.id = item.pointId;
      let levelType = '';
      if (pointType === 3){//巡检
        levelType = '3';
      } else if (pointType === 2){//动环
        levelType = '01';
      }else if(pointType === 6){ //火探
        levelType = '02';
      }
       else if (pointType === 1){//网络设备
        levelType = '01';
      } else if (pointType === 5){//虚拟设备（自动巡检设备）
        levelType = '03';
      }
      alarmPoint.level = levelType;
      alarmPoint.objType = levelType;
      alarmPoint.objKey = type;
      alarmPoint.position = pointPosition;
      alarmPoint.title = item.pointName;
      alarmPoint.sourceId = item.sourceId;
      alarmPoint.twinkle = true;
      alarmPoint.type = pointType === 3 ? 'patrol' : ((pointType === 2)||(pointType === 6)) ? 'dynamicRingData' : 'impEquipment';
      let points = [];
      points.push(alarmPoint);
      markers[alarmPoint.type] = points;

      //console.log(markers);

      if (this.lensLevel === LENS_LEVEL.SUB || this.lensLevel === LENS_LEVEL.SUN) {
        this.setState({
          markers
        });
      }
    }
  }

  /**
   * 弹出框关闭事件
   *
   * @memberof View3D
   */
  onDialogClose = () => {
    this.setState({
      pickDialog: false,
      pickData: {}
    });
  }

  /**
   * 渲染控制区
   *
   * @memberof View3D
   */
  renderMaskContent  = () => {
    const { showExplain } = this.state;
    const { hiddenScreenSaver } = this.props;
    return (<MaskContent
      onItemClick={this.changeMarkerType}
      layerConfig={layerConfig}
      showExplain={showExplain}
      onExplainClose={this.handleExplainClose}
      hiddenScreenSaver={hiddenScreenSaver}
    />);
  }

  afterRender = () => {
    this.objAnchorHelper && this.objAnchorHelper.update();
    this.infoHelper && this.infoHelper.update();
  }

  render() {
    const {
      loading,
      showObjSpinner,
      percent,
      objs,
      asyncModels,
      markers,
      startAsyncLoad,
      isAllDone,
      alarms,
      pickVisable,
      pickDialog,
      pickData,
      orgCode
    } = this.state;
    const { dimension } = this.props;
    // 图形对象
    const graphicProps = {
      ...dimension,
      ...desigerConf,
      enableAnimator: true,
      enableOutline: true,
      enableCSS2D: true,
      onCreated: this.onGraphCreated,
      afterRender: this.afterRender
    };
    // 模型加载
    const modelContentProps = {
      onAllDone: this.onAllDone,
      onComplete: this.onComplete,
      onProgress: this.onLoadProgress
    };

    return (
      <A3DDesigner
        {...graphicProps}
        enableModelParser
        disabledEdit
        defaultLoading={false}
        ref={node => this.a3dRef = node}
        baseObjs={objs}
        options={desigerConf.options}
        maskContent={isAllDone && this.renderMaskContent()}
        modelContentProps={modelContentProps}
        loading={loading}
        showObjSpinner={showObjSpinner}
        percent={percent}
        loadingManager={this.loadingManager}
        customLoading={<LoadingComs percent={percent} tip="正在搭载模型..." />}
      >
        {startAsyncLoad && <WorkerObjContent objs={asyncModels} onWorkerMessage={this.onWorkerLoading} enableLoading={false} afterInit={this.onAfterWorkerInit} />}
        <PointsPool markers={markers} orgCode={orgCode} updateMarker={this.updateMarker} />

        {isAllDone && <PointsAlarm alarms={alarms} onAlarmClick={this.onAlarmClick} visible />}

        {pickVisable && <CoordinatePickup visible={pickDialog} data={pickData} onClose={this.onDialogClose} />}
      </A3DDesigner>
    );
  }
}

View3D.propTypes = {
  dimension: PropTypes.shape({
    width: PropTypes.number,
    height: PropTypes.number
  }),
  subscribe: PropTypes.func,
  hiddenScreenSaver: PropTypes.func,
  onLoadCompleted: PropTypes.func
};

export default View3D;
