/* eslint-disable no-magic-numbers */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import installGIS3D, { GIS3DEventType } from 'amos-3d/lib/gis3d';
import installGIFPlugin from 'amos-3d/lib/gis3d/GIFPlugin';
import { Connect as UIConnect, Modal } from 'amos-framework';
import { tileUrl } from './../../consts/urlConsts';
import { loadScripts, cesiumScripts, loader, dynamicLoader, cesiumStyles, getGlobalConf, text2Speech } from './_tools';
import { getAreas } from './_areas';
import { eventTopics } from './consts';
import { changeGoodView, initView, riskFlashing } from './ruleActionTools';
import BindTileViewModel from './BindTileViewModel';
import { bindTileViewAction } from '../../services/3dService'

const eventConnect = UIConnect.eventConnect;

@eventConnect
class GIS3DView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modal: false,
      tilePosition: '',//当前坐标
    };
    // 加载样式
    // loader.loadCSS(cesiumStyles.url);
    dynamicLoader.loadCSS(cesiumStyles.url);
  }

  componentDidMount() {
    const rootDIV = this.rootRef;
    loadScripts.asyncLoadScript(cesiumScripts, () => {
      const GIS3DRenderer = installGIS3D(Cesium);
      // 安装插件, 可以独立使用 GIFPlugin，也可以采用 Cesium.GIFPlugin
      this.GIFPlugin = installGIFPlugin(Cesium);
      this.gis3DRenderer = new GIS3DRenderer({
        rootDIV,
        tileUrl
      });
      this.initView();
      this.props.onViewerCreated && this.props.onViewerCreated(this.gis3DRenderer, this.GIFPlugin);

      // -- 添加事件
      // 左键单击
      this.gis3DRenderer.bindEvent(GIS3DEventType.LEFT_CLICK, this.handleClick);
      // 右键单击，拾取坐标
      this.gis3DRenderer.bindEvent(GIS3DEventType.RIGHT_CLICK, this.handleRightClick);
      this._bindRulesPubSubEvents();

      // test gif
      // this.gis3DRenderer.createMarker({
      //   name: 'test',
      //   label: {
      //     text: ''
      //   },
      //   billboard: {
      //     image: new Cesium.GIFPlugin({
      //       url: '/src/assets/loading/toip-loading.gif'
      //     })
      //   },
      //   position: { x: 109.43647426, y: 34.49717592, z: 90.825485 },
      //   description: 'testsdgsadfgsadgadsg'
      // });
    });
  }

  componentWillUnmount() {
    // 移除事件
    this.gis3DRenderer.unbindEvent(GIS3DEventType.LEFT_CLICK);
    this.gis3DRenderer.unbindEvent(GIS3DEventType.RIGHT_CLICK);
  }

  initView() {
    const { showBaseMap = false, enableTilt = true } = getGlobalConf();
    const gis3dRenderer = this.gis3DRenderer;
    const _viewerOptions = {};
    if (!showBaseMap){
      // 配置街道地图，如果无需接到地图，设置 url 为 空即可,注意，不可设置为 null
      _viewerOptions.imageryProvider = new Cesium.SingleTileImageryProvider({
        // url: 'https://a.tile.openstreetmap.org/'
        url: ''
      });
    }
    gis3dRenderer.create({
      beforeInit(viewer) {
        // 设置区域范围
        Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(109.4251498, 34.4943254, 109.4387737, 34.5019288);
        Cesium.Camera.DEFAULT_VIEW_FACTOR = 0;
        viewer.bottomContainer.innerHTML = '';
        Cesium.Transforms.eastNorthUpToFixedFrame(Cesium.Cartesian3.fromDegrees(109.39626, 34.49505, 120));
      },
      onTileDone(tileset) {
        const heightOffset = -385.0;
        const boundingSphere = tileset.boundingSphere;
        const cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
        const surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 2.0);
        const offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
        const translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
        tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
      },
      tileParam: {
        maximumScreenSpaceError: 1,
        maximumNumberOfLoadedTiles: 1000
      },
      viewerOptions: _viewerOptions
    });

    // flyTo
    gis3dRenderer.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(109.432085, 34.490333, 800),
      orientation: {
        heading: Cesium.Math.toRadians(-2.0),
        pitch: Cesium.Math.toRadians(-45.5),
        roll: 0
      },
      pitchAdjustHeight: -90,
      maximumHeight: 5000,
      flyOverLongitude: 100
    });

    // area
    gis3dRenderer.createArea(getAreas());

    this.viewer = this.gis3DRenderer.getViewer();
    const scene = this.viewer.scene;
    // 禁止 rotate
    // scene.screenSpaceCameraController.enableRotate = false;
    // 禁止倾斜相机
    scene.screenSpaceCameraController.enableTilt = enableTilt;

    // 设置效果
    scene.globe.enableLighting = false;
    scene.fog.enabled = false; // 禁用 雾
    scene.skyAtmosphere.hueShift = 0.0;
    scene.skyAtmosphere.saturationShift = 0.0;
    scene.skyAtmosphere.brightnessShift = 0.0;
    scene.globe.atmosphereHueShift = 0.0;
    scene.globe.atmosphereSaturationShift = 0.0;
    scene.globe.atmosphereBrightnessShift = 0.0;

  }

  handleClick = (event) => {
    const pickedObject = this.gis3DRenderer.pickObject(event.position);
    if (pickedObject && Cesium.defined(pickedObject)) {
      // 拾取到对象，并且 Cesium 中已定义该对象
      console.log(pickedObject);
    }
  }

  handleRightClick = (event) => {
    const { pickable } = this.props;
    let { tilePosition } = this.state;
    if (pickable){
      const pos = this.gis3DRenderer.pickPosition(event.position);
      tilePosition = pos.lng + ',' + pos.lat + ',' + pos.height;
      console.log(pos);
      this.state.modal = true;
      this.setState({modal: true, tilePosition: tilePosition })
      // this.props.trigger('tileViewMapRightClick', { tilePosition:tilePosition });
    }
  }

  _bindRulesPubSubEvents = () => {
    this.props.subscribe(eventTopics.fromws, (topic, content) => {
      let data = content.data;
      // console.log('消息类型--->', topic);
      // console.log('data==', JSON.stringify(data));
      //通用:
      // actionName: "action1-1"
      // batchNo: "76a4dbee-962e-4623-80d1-62effe5c7c72"
      // contingencyRo:
      // adminName: "admin"
      // batchNo: "76a4dbee-962e-4623-80d1-62effe5c7c72"
      // cameraCodes: "SP002,SP003,SP004,SP005"
      // cameraIds: "61,64,65,66"
      // confirm: "NONE"
      // dateTime: "Aug 14, 2019 6:20:45 PM"
      // equipmentId: "2"
      // equipmentName: "极Ⅰ高端换流阀A项"
      // fireCount: 1
      // fireEquipmentId: "14"
      // fireEquipmentLayer: 0
      // fireEquipmentName: "感温探测器"
      // fireEquipmentPosition: "-133.6823,0,-86.922"
      // fireTruckRoute: "[[-60, -14, 95], [-60, -14, 76],[-120, -14, 76],[-120, -14, -65],[-125, -14, -65]]"
      // isDelete: false
      // layer: 0
      // mobile: "13259783333"
      // packageId: "消防专项预案/converter1"
      // picture1: "upload\fireEquipment\2\1.png"
      // picture2: "upload\fireEquipment\2\2.png"
      // picture3: "upload\fireEquipment\2\3.png"
      // picture4: "upload\fireEquipment\2\4.png"
      // runstep: false
      // step: "0"
      switch (topic) {
        case 'baseTile.fromws.mapArea_action1-2': //镜头切换（拉近）到压缩机组附近
          changeGoodView(this, data);
          break;
        case 'baseTile.fromws.mapArea_action1-5': //切换为预案执行场景
          this.props.trigger(eventTopics.alarm_confirm_msg, { data });
          break;
        case 'baseTile.fromws.mapArea_action1-7': //恢复至预控系统监控初始界面
          initView(this, data, this.props.removeByMarkerId);
          this.props.trigger(eventTopics.plan_end, { data });
          break;
        case 'baseTile.fromws.voice': //语音播报
          text2Speech(data);
          break;
        case 'baseTile.fromws.map_icon':  //风险点闪烁，（替换图标）
          riskFlashing(this, data, this.props.addMarkerId, this.props.removeByMarkerId, this.props.createEquip);
          break;
        case 'baseTile.fromws.monitor':  //实时转速值
          this.props.trigger(eventTopics.monitor_speed_view, { data });
          break;
        case 'baseTile.fromws.topArea_MESSAGE': //消防报警
          this.props.trigger(eventTopics.top_afe_msg, { content: data.content });
          break;
        case 'baseTile.fromws.topArea_CONTINGENCY': //顶部标题
          // batchNo: "76a4dbee-962e-4623-80d1-62effe5c7c72"
          // content: "消防报警：极I高端8111换流变A相 感温传感器报警，请前去确认！"
          // contingencyRo: {dateTime: "Aug 14, 2019 6:20:45 PM", batchNo: "76a4dbee-962e-4623-80d1-62effe5c7c72", fireTruckRoute: "[[-60, -14, 95], [-60, -14, 76],[-120, -14, 76],[-120, -14, -65],[-125, -14, -65]]", runstep: false, isDelete: false, …}
          // messageType: "CONTINGENCY"
          this.props.trigger(eventTopics.top_ae_msg, { content: data });
          break;
        case 'baseTile.fromws.recordArea_refresh': //记录区刷新
          // dataList:
          //   batchNo: "76a4dbee-962e-4623-80d1-62effe5c7c72"
          //   refresh: "refresh"
          this.props.trigger(eventTopics.record_view, data);
          break;
        case 'baseTile.fromws.stepArea_overview': //步骤区推数据
          // batchNo: "76a4dbee-962e-4623-80d1-62effe5c7c72"
          // contingencyRo: {dateTime: "Aug 14, 2019 6:20:45 PM", batchNo: "76a4dbee-962e-4623-80d1-62effe5c7c72", fireTruckRoute: "[[-60, -14, 95], [-60, -14, 76],[-120, -14, 76],[-120, -14, -65],[-125, -14, -65]]", runstep: false, isDelete: false, …}
          // nextStepCode: "1"
          // nextStepName: "停运换流阀、拨打报警电话"
          // stepCode: "0"
          // stepName: "确认灾情"
          this.props.trigger(eventTopics.stepArea_view, content);
          break;
        case 'baseTile.fromws.helpArea': //辅助区推数据
          // batchNo: "76a4dbee-962e-4623-80d1-62effe5c7c72"
          // content: "S2和 A2 携带必要器材（ 防毒面具、 对讲机、 万能 钥匙） 查看火情， 其向主控室传达现场情况， 立即开展现场 应急处置。"
          // contingencyRo: {dateTime: "Aug 14, 2019 6:20:45 PM", batchNo: "76a4dbee-962e-4623-80d1-62effe5c7c72", fireTruckRoute: "[[-60, -14, 95], [-60, -14, 76],[-120, -14, 76],[-120, -14, -65],[-125, -14, -65]]", runstep: false, isDelete: false, …}
          // icon: "无"
          // tirggerPlanTopic(CONSTS.plan_detail, { type: 'helpArea', data });
          this.props.trigger(eventTopics.plan_detail, content);
          break;
        case 'baseTile.fromws.optionArea': //交互区推数据
          this.props.trigger(eventTopics.optionArea_view, data);
          break;
        case 'baseTile.fromws.default_refreshTimeLine':
          this.props.trigger(eventTopics.plan_step, {
            key: 'broadcast',
            batchNo: data.paramObj.batchNo,
            type: 'equipment',
            equipmentId: data.paramObj.equipmentId
          }); //时间轴数据刷新
          break;
        default:
          console.log(topic + '：类型不支持');
      }
    });
  };

  getContext = (tilePosition) => {
    return <BindTileViewModel tilePosition={tilePosition} ref={component => this.bindModel = component}/>
  };

  cancel = () => {
    this.state.modal = false;
    this.setState({ modal: false });
  };

  onOk = () => {
    let { form } = this.bindModel;
    if (form) {
      this.bindModel.handleSubmit();
    }
    this.setState({ modal: false });
  };

  render() {
    let { modal, tilePosition } = this.state;
    return <div className="tileview-root" style={{ width: '100%', height: '100%' }} ref={node => this.rootRef = node} >
            <Modal
              header={'坐标绑定'}
              visible={modal}
              className="param-model"
              destroyContent
              content={this.getContext(tilePosition)}
              onCancel={() => this.cancel()}
              onOk={() => this.onOk()}
              okText="确定"
              cancelText="取消"
              outterClosable={false}
            />
            </div>;
  }
}

GIS3DView.propTypes = {
  // 是否处于拾取坐标状态
  pickable: PropTypes.bool,
  onViewerCreated: PropTypes.func,
  subscribe: PropTypes.func,
  trigger: PropTypes.func,
  addMarkerId: PropTypes.func,
  removeByMarkerId: PropTypes.func,
  createEquip: PropTypes.func
};

export default GIS3DView;
