import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BaseMap, Marker, Polyline } from 'amos-amap';
import { _picURI, _mapCenter, _showZoom } from './../../../consts/urlConsts';
import { browserHistory } from 'amos-react-router';
import xaMapData from '../../../_mock/indexMap_xa';
import xyMapData from '../../../_mock/indexMap_xy';
//import { xianCode, xianyangCode } from '../../../_mock/code';
import LeftCharts from './indexCharts/leftCharts';
import RightCharts from './indexCharts/rightCharts';
import LeftDown from './indexMaps/leftDown';
import TwoDimensionalMap from './../monitor/2d/index';
import { Col } from 'amos-framework';
import PatrolDetail from './indexCharts/rightChartChild/patrolDetail';
import { getPermissionsCompanyData } from 'SERVICES/securityService';
import { queryAisleDataByCity, getBankInfoListData } from 'SERVICES/indexMapService';
import message from 'amos-framework/lib/message';
// import { SidePane } from 'amos-framework';
// import Drawer from './indexCharts/Drawer';
import IndexSidePane from './indexCharts/rightPane/index';
import AlarmMarquee from './alarmMarquee';
import AmosWebSocket from 'amos-websocket';
import SysWsURL, { completeToken } from 'CONSTS/wsUrlConsts';
import { getAlarms } from 'SERVICES/alarmService';
import { Store, utils } from 'amos-tool';
import * as endConf from 'amos-processor/lib/config/endconf';
import { isArray } from 'amos-pluggable/lib/_utils';
import { calcCoorArrUtil } from 'UTILS/CalcCoorArrUtil';
import { insertDistrict } from './common/mapUtils';
import { getDictionaryList } from './../../../services/securityService';
import { fetchJsonAction } from './../../../services/3dService';
import TwinkleDiv from './map/TwinkleDiv';
import mqtt from 'mqtt';
const AmosConfig = endConf.AmosConfig;
const outMap = AmosConfig.sysConf.outMap;
const lsTool = Store.lsTool;
const mqttURI = AmosConfig.wsURI.mqttURI;

const mapConfig = {
  zoom: _showZoom[0],
  resizeEnable: true,
  zoomEnable: true,
  // plugins: ['Scale', 'MapType', 'OverView', 'ControlBar'],
  plugins: ['Scale'],
  zooms: [_showZoom[0], _showZoom[2]],
  expandZoomRange: true,
  doubleClickZoom: false,
  showIndoorMap: false, //隐藏地图自带的室内地图图层
  features: ['bg', 'road', 'point'] //隐藏默认楼块
};

const options = {
  //默认 30 * 1000毫秒，收到 CONNACK 之前等待的时间，即连接超时时间。
  connectTimeout: 40000,
  // 客户端 ID,随机生成
  clientId:
    'bank_mqtt' +
    Math.random()
      .toString(16)
      .substr(2, 8),
  clean: true,
  //默认 1000 毫秒，两次重新连接之间的间隔，客户端 ID 重复、认证失败等客户端会重新连接；
  reconnectPeriod: 1000 * 50
};
let client = mqtt.connect(mqttURI, options);

const layers = [
  new AMap.TileLayer({
    getTileUrl(x, y, z) {
      return `${_picURI}shanxi/amap/${z}/${x}/${y}.png`;
    },
    zIndex: 0
  })
];

const twoDimensionalMapConfig = {
  zooms: [_showZoom[0], _showZoom[2]],
  showIndoorMap: false, //隐藏地图自带的室内地图图层
  features: ['bg', 'road', 'point'] //隐藏默认楼块
};

const LineColors = ['#00A2FF', '#19FF00', '#959595', '#FF8800', '#FF0000', '#02E3FC', '#FFF948', '#FFAA00'];

/**
 * @class IndexMap
 * @extends {Component}
 * @description 首页地图
 */
class IndexMap extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mapCenter: _mapCenter,
      markerList: [],
      center: { longitude: 108.93984, latitude: 34.34127 },
      radius: 7000,
      visible: true,
      style: { strokeColor: '#10A100', fillColor: '#10A100' },
      linePath: [],
      isShow: true,
      isIndexMap: true,
      patrolView: false,
      patrolDescData: [],
      city: 'xian',
      selectStyle: { strokeColor: '#1AFF00', fillColor: '#1AFF00', strokeWeight: '3' },
      unSelectStyle: { strokeColor: '#1B950D', fillColor: '#1B950D', strokeWeight: '1' },
      orgCode: '',
      sequenceNbr: '',
      companys: [],
      currentCard: 1,
      currentCss: 1,
      chartsViewFlag: [],
      type: 'small', //当前图层展示的末端marker标识
      styleCss: {
        //末端marker样式
        background: `url('/src/assets/sy/afterbody.png')`,
        backgroundSize: 'contain',
        backgroundRepeat: 'no-repeat',
        backgroundPosition: '',
        width: '15px',
        height: '15px',
        color: '#000',
        textAlign: 'center',
        lineHeight: '40px'
      },
      dotTipNum: 0,
      pmdList: [], //跑马灯集合
      xianVisible: false,
      xianyangVisible: false,
      xianAisleList: [], //西安通道集合
      xianyangAisleList: [], //咸阳通道集合
      centerList: [], //中心点集合
      bankInfoList: [],
      isEncircleShow: false, //是否环绕显示
      isOnClickCity: false //是否点击的城市
    };
  }

  componentWillMount() {
    this.getPermissionsCompany();
    this.getBankInfoList();
    this.queeryAlarms();
    this.queryAisleList('西安');
    this.queryAisleList('咸阳');
    this.receivcemqtt();
  }

  //mqtt接收可删除
  receivcemqtt = () => {
    client.on('connect', e => {
      console.log('连接成功！！！');
      //QoS0，最多一次送达。也就是发出去就fire掉，没有后面的事情了。
      // QoS1，至少一次送达。发出去之后必须等待ack，没有ack，就要找时机重发
      // QoS2，准确一次送达。消息id将拥有一个简单的生命周期。
      // client.subscribe('bank/equipment/ping', { qos: 1 }, (res) => {
      client.subscribe('bank/aisle/alarm', { qos: 1 }, res => {
        if (!res) {
          console.log('订阅成功');
          // fetchJsonAction('/src/_mock/map/eqp.json', (data) => {
          //   let metricJson = JSON.parse(data.metricDatas[0].metricJson);
          //   let eqpId = data.metricDatas[0].eqpId;
          //   let status = metricJson.status === '通' ? 0 : 1;
          //   this.initBankInfoList(null, eqpId, status);
          // });
        } else {
          console.log('订阅失败');
        }
      });

      // 接收消息处理
      client.on('message', (topic, message) => {
        //console.log('收到来自', topic, '的消息', message.toString());
        this.msg = message.toString();
        let data = JSON.parse(message);
        let metricJson = JSON.parse(data.metricDatas[0].metricJson);
        let eqpId = data.metricDatas[0].eqpId;
        let status = metricJson.communication === '正常' ? 0 : 1;
        //this.initBankInfoList(null, eqpId, status);
      });

      // 断开发起重连
      client.on('reconnect', error => {
        console.log('正在重连:', error);
      });
      // 链接异常处理
      client.on('error', error => {
        console.log('连接失败:', error);
      });
    });
  };
  /**
   * 初始化登录用户权限
   */
  getPermissionsCompany = () => {
    //公司orgCode  selectedCompanyOrg
    let orgCode = lsTool.read('selectedCompanyOrg');
    //公司uuid
    let sequenceNbr = lsTool.read('companySequenceNbr');
    let reginCompany = JSON.parse(lsTool.read('company'));
    this.setState({
      orgCode,
      sequenceNbr,
      //companys,
      reginCompany,
      currentCard: 1
    });

    lsTool.write('orgCode', orgCode);
  };

  /**
   * 查询银行经纬度列表
   */
  getBankInfoList = () => {
    let { bankInfoList } = this.state;
    getBankInfoListData().then(data => {
      if (data) {
        data.centerList.map(e => {
          bankInfoList.push(e);
        });
        data.unCenterList.map(e => {
          bankInfoList.push(e);
        });
        this.setState({
          centerList: data.centerList,
          bankInfoList
        });
      }
    });
  };

  /**
   * 初始化数据，判断权限
   */
  // initCompanysData = (companys) => {
  //   if (companys.length === 2 && companys[0].companyName.indexOf('咸阳') === 0) {
  //     companys = companys.reverse();
  //   }
  //   if (companys.length === 1) {
  //     if (companys[0].companyName.indexOf('西安') === 0) {
  //       let xianyangCompany = { "companyOrgCode": "3", "companyName": "咸阳备份中心", "level": "subsidiary", "orgCode": "1*3", "sequenceNbr": "1251083542213996546" }
  //       companys.push(xianyangCompany);
  //     }
  //   }
  //   return companys;
  // }

  /**
   * 查询通道信息及状态
   */
  queryAisleList = city => {
    if (city === '西安') {
      queryAisleDataByCity(city).then(data => {
        let temp = this.isExist(xaMapData, data);
        this.setState({
          xianAisleList: temp
        });
      });
    } else {
      queryAisleDataByCity(city).then(data => {
        let temp = this.isExist(xyMapData, data);
        this.setState({
          xianyangAisleList: temp
        });
      });
    }
  };

  /**
   * 重构数据，增加alarmState字段，渲染不同曲线颜色
   */
  isExist = (mapData, data) => {
    mapData.map(item => {
      let alarmState;
      if (isArray(data)) {
        const flag = data.some(e => {
          if (e.ename === item.alias) {
            alarmState = e.alarmState;
            return true;
          }
        });
        if (flag) {
          item.alarmState = alarmState;
        } else {
          item.alarmState = '正常';
        }
      }
    });
    return mapData;
  };

  /**
   * 经纬度获取坐标曲线
   * @param {point_start} 起点经纬度
   * @param {point_end} 终点经纬度
   * @param {num} 生成点个数
   * @param {key} 曲线弯曲程度
   */
  calcCoorArr = (point_start, point_end, num, key) => {
    return calcCoorArrUtil(point_start, point_end, num, key);
  };

  /**
   * 监听图层
   */
  initMap = () => {
    let thisMap = this;
    window.map.on('zoomchange', () => {
      thisMap.setStyleC(window.map.getZoom());
    });
  };

  /**
   * 根据传入的名称查询匹配orgCode
   */
  // getOrgCode = (city, companys) => {
  //   let company;
  //   if (city === 'xian') {
  //     companys.map(o => {
  //       if (o.companyName.indexOf('西安') === 0) {
  //         company = o;
  //       }
  //     });
  //   } else {
  //     companys.map(o => {
  //       if (o.companyName.indexOf('咸阳') === 0) {
  //         company = o;
  //       }
  //     });
  //   }
  //   return company;
  // }

  // getOrgCode = (jsonObjDep) => {
  //    if(jsonObjDep && jsonObjDep !==null ){
  //      let orgCode = jsonObjDep.orgCode;
  //      let list = orgCode.split("-")|| [];
  //      return list[0];
  //    }
  // }

  getCompanyId = jsonObjDep => {
    if (jsonObjDep && jsonObjDep !== null) {
      let companyId = jsonObjDep.companySeq;
      return companyId;
    }
  };

  /**
   * 点
   */
  markerEvents = {
    click: e => {
      let map = { is3DPage: true, city: e.target.F.extData.city };
      //this.props.indexViewChange(map);
    }
  };

  /**
   * 圆
   */
  circleEvents = { click: () => { } };

  /**
   * 线
   */
  lineEvents = {
    click: e => {
      let line = e.target.F.extData;
      let pointData = { citys: line.name };
      setTimeout(() => {
        //设置延时判断点击的线还是点
        let { isOnClickCity } = this.state;
        if (isOnClickCity === false && line.name[0] === '西安') {
          browserHistory.push({ pathname: '/biz/defaultRoute', state: { cityLine: JSON.stringify(pointData) } });
        }
      }, 500);
    }
  };

  /**
   * 根据城市返回字典中配置的组织orgCode
   */
  getSelectOrgCode = (city, dictionaryList) => {
    let orgCode = null;
    dictionaryList.map(item => {
      if (item.dictDataKey === city) {
        orgCode = item.dictDataValue;
      }
    });
    return orgCode;
  };

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

  /**
   * 切换城市
   */
  // showCityInfo = (city, currentCard) => {

  //   // let { companys } = this.state;
  //   let userCity = this.state.userCity;
  //   let company = this.state.reginCompany;
  //   let dictionaryList = lsTool.read('dictionaryList');
  //   let dicCodeList = JSON.parse(dictionaryList);
  //   let orgCode = this.getSelectOrgCode(city, dicCodeList);
  //   // if((userCity ==="xian" && city ==="xian") ||(userCity ==="xianyang" && city ==="xianyang") ){
  //   //   this.setState({
  //   //     city,
  //   //     orgCode: company.orgCode,
  //   //     sequenceNbr: company.sequenceNbr,
  //   //     currentCard
  //   //   });
  //   // }else if(userCity ==="xian-xianyang"){
  //   //   this.setState({
  //   //     city,
  //   //     orgCode: company.orgCode,
  //   //     sequenceNbr: company.sequenceNbr,
  //   //     currentCard
  //   //   });
  //   //   console.log("您是所属西安CCPC，西安和咸阳数据都可以查看")
  //   // }else if(userCity ==="xian" && city ==="xianyang"){
  //   //   message.danger('您没有咸阳的权限，请联系管理员');
  //   // }else if(userCity ==="xianyang" && city ==="xian"){
  //   //   message.danger('您没有西安的权限，请联系管理员');
  //   // }
  //   this.setState({
  //     city,
  //     orgCode: orgCode,
  //     sequenceNbr: company.sequenceNbr,
  //     currentCard
  //   });
  // }

  /**
   * 展示陕西省地图
   */
  showIndexMap(status) {
    let { currentCss } = this.state;
    this.setState({ isIndexMap: true, currentCss: status });
    if (currentCss !== status) {
      this.setState({ visible: true });
    }
  }

  /**
   * 展示全国地图
   */
  show2dMap(currentCss) {
    this.setState({ isIndexMap: false, currentCss });
  }

  /**
   * 加载全局地图
   */
  setInstanceToGlobal = inst => {
    this.map = inst;
    window.map = inst;
    insertDistrict(window.map, 100000);
    this.queeryAlarms();
    this.initMap();
  };

  patrolDetailView = (serviceData, technologyData) => {
    if (serviceData && technologyData) {
      this.setState({
        patrolView: true,
        patrolDescData: [serviceData, technologyData]
      });
    } else {
      message.danger('当前没有巡检计划');
    }
  };

  closePatrol = () => {
    this.setState({
      patrolView: false
    });
  };
  chartsView = itemKey => {
    if (itemKey.length < 1 || itemKey[0] === 'dangerMsg' || itemKey[0] === 'applyMsg') {
      this.setState({
        chartsViewFlag: itemKey,
        patrolView: false
      });
    } else {
      this.setState({
        chartsViewFlag: itemKey
      });
    }
  };

  /**
   * 不同图层渲染图标大小
   */
  setStyleC = zoom => {
    if (zoom >= 8) {
      this.setState({
        type: 'middle',
        styleCss: {
          ...this.state.styleCss,
          width: '25px',
          height: '25px'
        }
      });
      if (zoom >= 13) {
        this.setState({ isEncircleShow: true });
      } else {
        this.setState({ isEncircleShow: false });
      }
    } else {
      this.setState({
        type: 'small',
        styleCss: {
          ...this.state.styleCss,
          width: '15px',
          height: '15px'
        }
      });
    }
  };

  /**
   * 13层以上设置地名环绕
   */
  setMakerName = () => {
    this.setState({
      isEncircleShow: true
    });
  };

  /**
   * 通道末端marker点
   */
  setBodyMarker = bankInfoList => {
    let { styleCss, type, isEncircleShow } = this.state;
    if (isEncircleShow) {
      // return xaMapData.map((item, index) => {
      //   if (item.id !== 7 && item.id !== 10) {
      //     return (<Marker zIndex={19} position={{ longitude: item.center[0], latitude: item.center[1] }} events={this.markerEvents}>
      //       <div className={`after_line_${type} line${item.id}`} style={styleCss} ></div>
      //       <div className={`after_circle_title`}>
      //         <span>{item.alias}</span>
      //       </div>
      //     </Marker>)
      //   }
      // });
      return bankInfoList.map((item, index) => {
        if (
          item.eName !== 'xian' &&
          item.eName !== 'xianyang' &&
          item.eName !== 'xidajie' &&
          item.eName !== 'bj-bank' &&
          item.eName !== 'wx-bank' &&
          item.eName !== 'sh-bank'
        ) {
          return (
            <Marker zIndex={19} position={{ longitude: item.lng, latitude: item.lat }} events={this.markerEvents}>
              <div className={`after_line_${type} line${item.id}`} style={styleCss}></div>
              <div className={`after_circle_title`}>
                <span>{item.aName}</span>
                {item.status === 1 && <div className={`pulse-spread-circle`} />}
              </div>
            </Marker>
          );
        }
      });
    } else {
      // return xaMapData.map((item, index) => {
      //   if (item.id !== 7 && item.id !== 10) {
      //     return (<Marker zIndex={19} position={{ longitude: item.center[0], latitude: item.center[1] }} events={this.markerEvents}>
      //       <div className={`after_line_${type} line${item.id}`} style={styleCss} ></div>
      //       {/*<div className={`after_circle_${type} title${item.id}`}>
      //         <img src={item.imgSrc} ></img>
      //         <span>{item.alias}</span>
      //     </div>*/}
      //     </Marker>);
      //   }
      // });
      return bankInfoList.map((item, index) => {
        if (
          item.eName !== 'xian' &&
          item.eName !== 'xianyang' &&
          item.eName !== 'xidajie' &&
          item.eName !== 'bj-bank' &&
          item.eName !== 'wx-bank' &&
          item.eName !== 'sh-bank'
        ) {
          return (
            <Marker zIndex={19} position={{ longitude: item.lng, latitude: item.lat }} events={this.markerEvents}>
              <div className={`after_line_${type} line${item.id}`} style={styleCss}></div>
              {/*<div className={`after_circle_${type} title${item.id}`}>
              <img src={item.imgSrc} ></img>
              <span>{item.alias}</span>
          </div>*/}
            </Marker>
          );
        }
      });
    }
  };

  /**
   *设置中心点的marker点
   *
   * @memberof IndexMap
   */
  setCenterMarker = centerList => {
    let { isEncircleShow, xianVisible, xianyangVisible } = this.state;
    if (isEncircleShow) {
      return centerList.map((item, index) => {
        if (item) {
          return (
            <Marker key={item} zIndex={20} position={{ longitude: item.lng, latitude: item.lat }} events={this.markerEvents} extData={{ city: item.eName }}>
              <div className={`after_circle_title_center`}>
                <span
                  onClick={() => {
                    this.markerOnClick(item.eName);
                  }}
                >
                  {item.aName}
                </span>
                {item.eName === 'xian' && xianVisible && <div className="pulse-spread-xian" />}
                {item.eName === 'xianyang' && xianyangVisible && <div className="pulse-spread-xianyang" />}
              </div>
              <div className={`after_circle_center`}>
                <img
                  src="/src/assets/sy/center.png"
                  onClick={() => {
                    this.markerOnClick(item.eName);
                  }}
                ></img>
              </div>
            </Marker>
          );
        }
      });
    } else {
      return centerList.map((item, index) => {
        if (item) {
          return (
            <Marker key={item} zIndex={20} position={{ longitude: item.lng, latitude: item.lat }} events={this.markerEvents} extData={{ city: item.eName }}>
              <div className={`after_circle_small center`}>
                <img
                  src="/src/assets/sy/center.png"
                  onClick={() => {
                    this.markerOnClick(item.eName);
                  }}
                ></img>
              </div>
            </Marker>
          );
        }
      });
    }
  };

  /**
   * 根据状态匹配不同通道颜色
   * @param {} alarmState
   */
  setSelectAisleStyle = alarmState => {
    switch (alarmState) {
      case '正常':
        return this.state.selectStyle;
      case '异常':
        return this.setSelectColor(4);
    }
  };

  setUnSelectAisleStyle = alarmState => {
    switch (alarmState) {
      case '正常':
        return this.state.unSelectStyle;
      case '异常':
        return this.setUnSelectColor(4);
    }
  };

  setSelectColor = index => {
    let colorStyle = { strokeColor: LineColors[index], fillColor: LineColors[index], strokeWeight: '3' };
    return colorStyle;
  };

  setUnSelectColor = index => {
    let colorStyle = { strokeColor: LineColors[index], fillColor: LineColors[index], strokeWeight: '1' };
    return colorStyle;
  };

  /**
   * 点击名称切换三维
   */
  markerOnClick = (city, sourceIdStr) => {
    //跳转告警页面
    if (city !== 'xian' && city !== 'xianyang' && city !== 'xidajie') {
      if (!sourceIdStr) {
        message.danger('该银行未绑定设备');
        return;
      }
      let path = {
        pathname: '/main/warn',
        state: { sourceId: sourceIdStr }
      };
      browserHistory.push(path);
      return;
    }

    this.state.isOnClickCity = true;
    let selectedCompanyOrg = lsTool.read('selectedCompanyOrg');
    let dictionaryList = lsTool.read('dictionaryList');
    let dicCodeList = JSON.parse(dictionaryList);
    let companyName = this.getSelectCityByOrgCode(selectedCompanyOrg, dicCodeList);
    let map = null;

    if (companyName && companyName.indexOf('清算中心') !== -1) {
      let orgCode = this.getSelectOrgCode(city, dicCodeList);
      if (city === 'xian' || city === 'xianyang' || city === 'xidajie') {
        map = { is3DPage: true, city: city, orgCode: orgCode };
      } else {
        map = { is3DPage: true, city: '', orgCode: '' };
      }
    } else if (companyName && companyName.indexOf('科技处') !== -1) {
      // map = { 'is3DPage': true, 'city': '', 'orgCode': selectedCompanyOrg };
      let newOrgCode = null;
      if (city === 'xian') {
        newOrgCode = this.getSelectOrgCode('科技处西安', dicCodeList);
      }

      if (city === 'xianyang') {
        newOrgCode = this.getSelectOrgCode('科技处咸阳', dicCodeList);
      }

      if (city === 'xian' || city === 'xianyang' || city === 'xidajie') {
        map = { is3DPage: true, city: city, orgCode: newOrgCode };
      } else {
        map = { is3DPage: true, city: '', orgCode: '' };
      }
    } else {
      map = { is3DPage: true, city: '', orgCode: '' };
    }

    this.props.indexViewChange(map);
  };

  markerOnClick1 = (city, flag, id, pointName, pointAttrs, floor, pointtype) => {
    this.state.isOnClickCity = true;
    let selectedCompanyOrg = lsTool.read('selectedCompanyOrg');
    let dictionaryList = lsTool.read('dictionaryList');
    let dicCodeList = JSON.parse(dictionaryList);
    let companyName = this.getSelectCityByOrgCode(selectedCompanyOrg, dicCodeList);
    let map = null;

    if (companyName && companyName.indexOf('清算中心') !== -1) {
      let orgCode = this.getSelectOrgCode(city, dicCodeList);
      if (city === 'xian' || city === 'xianyang' || city === 'xidajie') {
        map = {
          is3DPage: true,
          city: city,
          orgCode: orgCode,
          flag: flag,
          pid: id,
          pointName: pointName,
          pointAttrs: pointAttrs,
          floor: floor,
          pointtype: pointtype
        };
      } else {
        map = { is3DPage: true, city: '', orgCode: '', flag: flag, pid: id, pointName: pointName, pointAttrs: pointAttrs, floor: floor, pointtype: pointtype };
      }
    } else if (companyName && companyName.indexOf('科技处') !== -1) {
      // map = { 'is3DPage': true, 'city': '', 'orgCode': selectedCompanyOrg };
      let newOrgCode = null;
      if (city === 'xian') {
        newOrgCode = this.getSelectOrgCode('科技处西安', dicCodeList);
      }

      if (city === 'xianyang') {
        newOrgCode = this.getSelectOrgCode('科技处咸阳', dicCodeList);
      }

      if (city === 'xian' || city === 'xianyang' || city === 'xidajie') {
        map = {
          is3DPage: true,
          city: city,
          orgCode: newOrgCode,
          flag: flag,
          pid: id,
          pointName: pointName,
          pointAttrs: pointAttrs,
          floor: floor,
          pointtype: pointtype
        };
      } else {
        map = { is3DPage: true, city: '', orgCode: '', flag: flag, pid: id, pointName: pointName, pointAttrs: pointAttrs, floor: floor, pointtype: pointtype };
      }
    } else {
      map = { is3DPage: true, city: '', orgCode: '', flag: flag, pid: id, pointName: pointName, pointAttrs: pointAttrs, floor: floor, pointtype: pointtype };
    }

    this.props.indexViewChange(map);
  };

  dotTipNumChange = num => {
    if (num !== this.state.dotTipNum) {
      this.setState({
        dotTipNum: num
      });
    }
  };

  existData = (code, orgCode) => {
    let xianshi = false;
    if (code) {
      if (code.indexOf('#') !== -1) {
        let split = code.split('#') || [];
        split.map(item => {
          if (item.indexOf('-') !== -1) {
            let array = item.split('-') || [];
            if (array.length > 0 && array[0] === orgCode) {
              xianshi = true;
            }
          } else {
            if (item === orgCode) {
              xianshi = true;
            }
          }
        });
      } else {
        let arr = code.split('-') || [];
        if (arr.length > 0 && arr[0] === orgCode) {
          xianshi = true;
        }
      }
    }
    return xianshi;
  };


  //处理告警数据
  handleAlarmData = () => {
    getAlarms().then(data => {
      this.processingAlarmData(data);
    });
  }

  //过滤告警列表
  processingAlarmData = data => {
    let { orgCode } = this.state;
    if (orgCode !== '') {
      let dictionaryList = lsTool.read('dictionaryList');
      let dicCodeList = JSON.parse(dictionaryList);
      let xianCode = this.getSelectOrgCode('xian', dicCodeList);
      let xianyangCode = this.getSelectOrgCode('xianyang', dicCodeList);
      // let kejichuCode = this.getSelectOrgCode('科技处', dicCodeList);
      //  let qingsuanzhongxin = this.getSelectOrgCode('清算中心', dicCodeList);
      let kejichuxianCode = this.getSelectOrgCode('科技处西安', dicCodeList);
      let kejichuxianyangCode = this.getSelectOrgCode('科技处咸阳', dicCodeList);
      //过滤该公司没有权限的设备（有则跑马灯显示，否则不显示）
      let newData = [];
      data.map(e => {
        let xianshi = this.existData(e.code, orgCode);
        let authOrgXianshi = this.existData(e.authOrg, orgCode);
        if (xianshi || authOrgXianshi) {
          newData.push(e);
        }
      });

      if (!utils.isEmpty(newData) && utils.isArray(newData)) {
        const xianFlag = newData.some(e => {
          // if (e.code === xianCode) {
          if (e.code.startsWith(xianCode) || e.code.startsWith(kejichuxianCode) || ((e.authOrg && e.authOrg.indexOf(xianCode) !== -1) || (e.authOrg && e.authOrg.indexOf(kejichuxianCode) !== -1))) {
            return true;
          }
        });
        const xianyangFlag = newData.some(e => {
          if (
            e.code.startsWith(xianyangCode) || e.code.startsWith(kejichuxianyangCode) ||
            ((e.authOrg && e.authOrg.indexOf(xianyangCode) !== -1) || (e.authOrg && e.authOrg.indexOf(kejichuxianyangCode) !== -1))
          ) {
            return true;
          }
        });

        this.setState({
          pmdList: newData,
          xianVisible: xianFlag,
          xianyangVisible: xianyangFlag
        });

        this.initBankInfoList('xian', null, xianFlag);
        this.initBankInfoList('xianyang', null, xianyangFlag);
      } else {
        this.setState({
          pmdList: newData,
          xianVisible: false,
          xianyangVisible: false
        });
        this.initBankInfoList('xian', null, false);
        this.initBankInfoList('xianyang', null, false);
      }
    }
  };


  /**
   * 初始化告警数据
   */
  queeryAlarms = () => {
    this.handleAlarmData();
  };

  /**
   * 根据告警city或者eqpId的重构数据
   *
   * @memberof IndexMap
   */
  initBankInfoList = (city, eqpId, status) => {
    let { bankInfoList } = this.state;
    bankInfoList.forEach(bankInfo => {
      if (eqpId && bankInfo.sourceIdStr && bankInfo.sourceIdStr.indexOf(eqpId) >= 0) {
        bankInfo.status = status;
      } else if (city && bankInfo.eName === city) {
        status = status ? 1 : 0;
        bankInfo.status = status;
      }
    });
    this.setState({
      bankInfoList
    });
  };

  /**
   * webSocket接收数据
   */
  handleData = data => {
    this.handleAlarmData();
  };

  /**
   * webSocket接收通道状态数据
   */
  aisleIndexHandleData = data => {
    //data = data.index;
    console.log('aisleWS', data);
    if (data) {
      this.initBankInfoList(null, data.eqpId, data.status);
      this.queryAisleList('西安');
      this.queryAisleList('咸阳');
      // const flag = data.some(e => {
      //   if (e.sname === '西安') {
      //     return true;
      //   }
      // });
      // if (!utils.isEmpty(data) && utils.isArray(data) && flag) {
      //   let temp = this.isExist(xaMapData, data);
      //   this.setState({
      //     xianAisleList: temp
      //   });
      // } else {
      //   let temp = this.isExist(xyMapData, data);
      //   this.setState({
      //     xianyangAisleList: temp
      //   });
      // }
    }
  };

  render() {
    const events = {
      created: this.setInstanceToGlobal
    };
    let {
      mapCenter,
      isIndexMap,
      patrolView,
      patrolDescData,
      city,
      selectStyle,
      unSelectStyle,
      orgCode,
      sequenceNbr,
      companys,
      currentCard,
      currentCss,
      chartsViewFlag,
      dotTipNum,
      pmdList,
      xianVisible,
      xianyangVisible,
      xianAisleList,
      xianyangAisleList,
      centerList,
      isEncircleShow,
      bankInfoList,
      styleCss
    } = this.state;
    let cardCss1 = 'small-card-css';
    let cardCss2 = 'small-card-css';
    // 旧版点击样式，正式上线前需删除
    // let fwCss = 'fw-css-selected';
    // let trackCss = 'track-css';

    if (currentCard === 1) {
      cardCss1 = 'small-card-css-selected';
    } else if (currentCard === 2) {
      cardCss2 = 'small-card-css-selected';
    }

    // if (currentCss === 2) {
    //   fwCss = 'fw-css';
    //   trackCss = 'track-css-selected';
    // }

    // const fwSelectImg = '/src/assets/sy/fw_select.png';
    // const fwUnSelectImg = '/src/assets/sy/fw_unselect.png';
    // const trackSelectImg = '/src/assets/sy/track_select.png';
    // const trackUnSelectImg = '/src/assets/sy/track_unselect.png';
    // const centerImg = '/src/assets/sy/center.png';
    const newTrackSelect = '/src/assets/sy/newTrackSelect.png';
    const newTrackUnSelect = '/src/assets/sy/newTrackUnSelect.png';

    const wsURL = completeToken(SysWsURL.view3dws);
    const aisleURL = completeToken(SysWsURL.aisleURI);

    if (outMap) {
      mapConfig.layers = layers;
      twoDimensionalMapConfig.layers = layers;
    }

    return (
      <div className="content indexPage">
        <AmosWebSocket ref={node => (this.aws = node)} url={wsURL} onMessage={this.handleData} reconnect debug />
        <AmosWebSocket ref={node => (this.aws = node)} url={aisleURL} onMessage={this.aisleIndexHandleData} reconnect debug />
        <AlarmMarquee pmdList={pmdList} />
        <div className="body-left">
          {/**<div className='body-left' style={{ display: chartsViewFlag[0] === 'dangerMsg' ? 'block' : 'none' }}>**/}
          {/**<div><img src='/src/assets/sy/indexLeft.png' /></div>*/}
          <LeftCharts currentCode={orgCode} dotTipNumChange={this.dotTipNumChange} />
        </div>
        <div className="body-map">
          {/*<div className="top" >
            <Col span={12} className="small-card-wrapper">
              <div className={`${cardCss1}`} onClick={() => { this.showCityInfo('xian', 1) }} >
                <span >西安</span>
              </div>
            </Col>
            <Col span={12} className="small-card-wrapper">
              <div className={`${cardCss2}`} onClick={() => { this.showCityInfo('xianyang', 2) }} >
                <span>咸阳</span>
              </div>
            </Col>
          </div>*/}
          <div
            className="new_track"
            onClick={() => {
              currentCss === 1 ? this.show2dMap(2) : this.showIndexMap(1);
            }}
          >
            <img src={currentCss === 1 ? newTrackUnSelect : newTrackSelect} />
          </div>
          {/* <div className="middle">
                        <div className={`${fwCss}`} onClick={() => { this.showIndexMap(1) }}>
                            <img src={currentCss === 1 ? fwSelectImg : fwUnSelectImg} />
                        </div>
                        <div className={`${trackCss}`} onClick={() => { this.show2dMap(2) }}>
                            <img src={currentCss === 1 ? trackUnSelectImg : trackSelectImg} />
                        </div>
                    </div> */}
        </div>
        {currentCss === 1 && <LeftDown></LeftDown>}
        {isIndexMap ? (
          <div className="body-center">
            <BaseMap events={events} center={mapCenter} {...mapConfig}>
              {/* 三个可点击的中心点（西安|咸阳|西大街） */}
              {/* {(centerList || []).map((item, index) => (
                <Marker key={index} zIndex={22 - index} position={{ longitude: item.lng, latitude: item.lat }} events={this.markerEvents} extData={{ 'city': item.eName }}>
                  <div className={`after_circle_small center`}>
                    <img src="/src/assets/sy/center.png" onClick={() => { this.markerOnClick(item.eName) }}></img>
                  </div>
                </Marker>
              ))}*/}
              {/* 非中心点 */}
              {this.setBodyMarker(bankInfoList)}
              {/* 中心点 */}
              {this.setCenterMarker(centerList)}
              {/* 西安到各地通道 */}
              {(xaMapData || []).map((item, index) => (
                <Polyline
                  key={index}
                  zIndex={11}
                  path={this.calcCoorArr(item.path[0], item.path[1], 30, 3)}
                  events={this.lineEvents}
                  visible={this.state.visible}
                  style={city === 'xian' ? this.setSelectAisleStyle(item.alarmState) : this.setUnSelectAisleStyle(item.alarmState)}
                  extData={item}
                />
              ))}
              {/* 咸阳到各地通道 */}
              {(xyMapData || []).map((item, index) => (
                <Polyline
                  key={index}
                  zIndex={17}
                  path={this.calcCoorArr(item.path[0], item.path[1], 30, 4)}
                  events={this.lineEvents}
                  visible={this.state.visible}
                  style={city === 'xian' ? this.setUnSelectAisleStyle(item.alarmState) : this.setSelectAisleStyle(item.alarmState)}
                  extData={item}
                />
              ))}
              {/*{(centerList || []).map((item) => (
                <Marker key={item} zIndex={20} position={{ longitude: item.lng, latitude: item.lat }} events={this.markerEvents} extData={{ 'city': item.eName }}>
                  {isEncircleShow === false ?
                  <div className={`after_circle_small ${item.eName}`}>
                    <img src={`/src/assets/sy/${item.img}`} ></img>
                    <span onClick={() => { this.markerOnClick(item.eName) }}>{item.aName}</span>
                    {item.eName === 'xian' ? (xianVisible && <div className="pulse-spread-xian" />) : (xianyangVisible && <div className="pulse-spread-xianyang" />)}
                  </div> :
                  <div className={`after_circle_title_center`}>
                    <span onClick={() => { this.markerOnClick(item.eName) }}>{item.aName}</span>
                    {item.eName === 'xian' ? (xianVisible && <div className="pulse-spread-xian" />) : (xianyangVisible && <div className="pulse-spread-xianyang" />)}
                  </div>
                  }
                </Marker>
                ))}*/}
              {(bankInfoList || []).map(item => (
                <Marker
                  key={item.id}
                  zIndex={18}
                  position={{ longitude: item.lng, latitude: item.lat }}
                  events={this.markerEvents}
                  extData={{ city: item.eName }}
                >
                  {isEncircleShow === false && <TwinkleDiv info={item} markerOnClick={this.markerOnClick} styleCss={styleCss} />}
                </Marker>
              ))}
            </BaseMap>
          </div>
        ) : (
            <TwoDimensionalMap twoDimensionalMapConfig={twoDimensionalMapConfig}></TwoDimensionalMap>
          )}
        <div className="body-right">
          <RightCharts currentCode={orgCode} curCompanyId={sequenceNbr} patrolDetailView={this.patrolDetailView} chartsViewFlag={chartsViewFlag[0]} />
        </div>
        {/*{
          chartsViewFlag[0] === 'patrolMsg' || chartsViewFlag[0] === 'applyMsg' ? <div className='body-right' >
            <RightCharts currentCode={orgCode} curCompanyId={sequenceNbr} patrolDetailView={this.patrolDetailView} chartsViewFlag={chartsViewFlag[0]} />
          </div> : 'none'
        }*/}

        {patrolView ? <PatrolDetail closePatrol={this.closePatrol} dataList={patrolDescData} markerOnClick1={this.markerOnClick1} /> : ''}
        {/*{patrolView && chartsViewFlag.length > 0 ? <PatrolDetail closePatrol={this.closePatrol} dataList={patrolDescData} /> : ''}
        <IndexSidePane chartsView={this.chartsView} nowKey={chartsViewFlag} dotTipNum={dotTipNum} />*/}
      </div>
    );
  }
}

export default IndexMap;
