/**
 * 一张图图层的数据展示
 */
import React, { Component } from "react";
import { Checkbox, Row, Col, Icon, Slider } from 'antd';
import ReactEcharts from 'echarts-for-react';
import { recentAbnormalData, getTodayAbnormalData, getAbnormaCount, getTimeAbnormalCount, getDomainInfo, getRootDep, getSubdepartmentList } from '@services/api';
import moment from "moment";
import styles from "./index.less";
import { connect } from "dva";
import { getHostByPath } from '../../../../utils/config';
import APictureData from './APictureData';
import AttendInfo from './AttendInfo';
import Search from './Search';
import InfoSearch from './InfoSearch';
import Componey from './Componey';
import ComprehensiveSearch from "./ComprehensiveSearch";
import MapEventModule from "./MapEventModule";
import ComponyList from "./ComponyList";
@connect((state) => {
  return {
    //所有下左右按钮状态
    switchOpenStatus: state.command.switchOpenStatus,
    mapStyle: state.command.mapStyle,
    gITFPoint: state.command.gITFPoint,
    selectAttendInfo: state.command.selectAttendInfo,
    selectComponeyInfo: state.command.selectComponeyInfo,
    selectComponyList: state.command.selectComponyList,
    mapLayerSwitchState: state.command.mapLayerSwitchState,
  }
})
export default class APicture extends Component {
  constructor(props) {
    super(props);
    this.state = {
      nowErrorList: [],
      errTimeOption: {},
      errorReportOption: {},
      errorTimeReport: {},
      todayCount: 0,
      yesterdayCount: 0,
      beforeYesterdayCount: 0,
      errorTimeHeight: null,
      // gITFPoint: [
      //   {
      //     name: "rjyA",
      //     lng: 118.051053,
      //     lat: 24.607252,
      //     gIFTurl: "https://bcxin-vedio-prod.obs.myhuaweicloud.com/glTF/0914san-fbx2/0914san-fbx.gltf",
      //     isShow: false,
      //   },
      //   {
      //     name: "rjyB",
      //     lng: 118.048937,
      //     lat: 24.611863,
      //     gIFTurl: "https://bcxin-vedio-prod.obs.myhuaweicloud.com/glTF/B-1/B-1.gltf",
      //     isShow: false,
      //   },
      // ],
    };
  }
  componentDidMount() {
    this.getThreeDaysAbnormalCount();
    this.recentAbnormalData()
    this.getErrorTime()
    this.getErrorReport()
    const errorTimeHeight = document.documentElement.clientHeight - 148 - 340 - 46 - 16;
    this.setState({ errorTimeHeight });
    this.setGITFMark();
  }
  // 获取这三天异常
  getThreeDaysAbnormalCount() {
    let today = moment().format("YYYY-MM-DD");
    let yesterday = moment().subtract(1, 'days').format('YYYY-MM-DD');
    let beforeYesterday = moment().subtract(2, 'days').format('YYYY-MM-DD');
    //获取今天异常
    this.getAbnormaCount(today).then(res => {
      this.setState({
        todayCount: res.data.data[0].total
      })
    })
    //获取昨天异常
    this.getAbnormaCount(yesterday).then(res => {
      this.setState({
        yesterdayCount: res.data.data[0].total
      })
    })
    //获取前天异常
    this.getAbnormaCount(beforeYesterday).then(res => {
      this.setState({
        beforeYesterdayCount: res.data.data[0].total
      })
    })
  }
  //按时间获取异常数
  getAbnormaCount(day) {
    return getAbnormaCount({
      _currpage: 1,
      lines: 10
    }, {
      appId: "__N04pcqn4nJYvdkjohbK",
      containTitle: "根据时间查询",
      dateTime: day,
      field: "",
      opentarget: "detail",
      viewId: "__kZW6NG4GdBBRHfcSzlx",
    })
  }
  //近期实时上报异常数据
  recentAbnormalData() {
    recentAbnormalData({
      _currpage: 1,
      lines: 10
    }, {
      appId: "__N04pcqn4nJYvdkjohbK",
      viewId: "__0iiRNXOJBGOiwTDPSr3",
      opentarget: "detail",
      containTitle: "近期实时上报异常展示接口",
      categoryParentName: "现场态势",
    }).then(res => {
      this.setState({
        nowErrorList: res.data.data
      })
      console.log(res.data.data)
    })

  }
  //展示当前异常的详细信息
  getEventAddress(item) {
    this.props.addNowErrorEvent(item)
  }
  // 获取异常事件
  getErrorTime() {
    getTodayAbnormalData({
      _currpage: 1,
      lines: 20
    }, {
      appId: "__N04pcqn4nJYvdkjohbK",
      containTitle: "今日异常上报各分类数量接口",
      opentarget: "detail",
      viewId: "__K3a3SsbfKNZis2xBMjQ",
    }).then(res => {
      let data = res.data.data;
      let yAxis = data.map(item => item.alarmeventtypename);
      let seriesData = data.map(item => item.sum)
      let errorTimeReportData = data.map(item => {
        return {
          value: item.sum,
          name: item.alarmeventtypename
        }
      })
      const errTimeOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: "errorTime",
          show: false
        },
        grid: {
          left: 0,
          // right: '4%',
          bottom: '3%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          show: false,
          splitLine: {
            show: false
          }
        },
        yAxis: {
          type: 'category',
          data: yAxis
        },
        series: {
          name: '异常事件',
          type: 'bar',
          data: seriesData,
          itemStyle: {
            normal: {
              color: '#FF9846'
            }
          },
          label: {
            show: true,
            position: 'right'
          },
        }
      };
      const errorTimeReport = {
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            name: '异常事件',
            type: 'pie',
            radius: '50%',

            data: errorTimeReportData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              }
            }
          }
        ]
      };

      this.setState({
        errTimeOption,
        errorTimeReport
      })
    })
  }
  // 获取分时异常报告
  async getErrorReport() {
    let today = moment().format("YYYY-MM-DD");
    let yesterday = moment().subtract(1, 'days').format('YYYY-MM-DD');
    let beforeYesterday = moment().subtract(2, 'days').format('YYYY-MM-DD');

    let todayCount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,];
    let yesterdayyCount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,];
    let beforeYesterdayCount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,];

    let todayList = await getTimeAbnormalCount({
      _currpage: 1,
      lines: 99999
    }, {
      appId: "__N04pcqn4nJYvdkjohbK",
      containTitle: "根据时间返回所有事件详情",
      dateTime: today,
      field: "",
      opentarget: "detail",
      viewId: "__CZBJre6k8BYpk881gTV",
    })
    let yesterdayList = await getTimeAbnormalCount({
      _currpage: 1,
      lines: 99999
    }, {
      appId: "__N04pcqn4nJYvdkjohbK",
      containTitle: "根据时间返回所有事件详情",
      dateTime: yesterday,
      field: "",
      opentarget: "detail",
      viewId: "__CZBJre6k8BYpk881gTV",
    })
    let beforeYesterdayList = await getTimeAbnormalCount({
      _currpage: 1,
      lines: 99999
    }, {
      appId: "__N04pcqn4nJYvdkjohbK",
      containTitle: "根据时间返回所有事件详情",
      dateTime: beforeYesterday,
      field: "",
      opentarget: "detail",
      viewId: "__CZBJre6k8BYpk881gTV",
    })

    todayList = todayList.data.data;
    yesterdayList = yesterdayList.data.data;
    beforeYesterdayList = beforeYesterdayList.data.data;

    todayList.forEach(item => {
      let time = item.alarmTime
      let hour = moment(time).hour()
      todayCount[hour] = todayCount[hour] + 1;
    })
    yesterdayList.forEach(item => {
      let time = item.alarmTime
      let hour = moment(time).hour()
      yesterdayyCount[hour] = yesterdayyCount[hour] + 1;
    })
    beforeYesterdayList.forEach(item => {
      let time = item.alarmTime
      let hour = moment(time).hour()
      beforeYesterdayCount[hour] = beforeYesterdayCount[hour] + 1;
    })
    let errorReportOption = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['前天', '昨天', '今天']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: "3%",
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['1时', '2时', '3时', '4时', '5时', '6时', '7时', '8时', '9时', '10时', '11时', '12时', '13时', '14时', '15时', '16时', '17时', '18时', '19时', '20时', '21时', '22时', '23时']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '前天',
          type: 'line',
          smooth: true,
          stack: '总量',
          data: todayCount
        },
        {
          name: '昨天',
          type: 'line',
          smooth: true,
          stack: '总量',
          data: yesterdayyCount
        },
        {
          name: '今天',
          type: 'line',
          smooth: true,
          stack: '总量',
          data: beforeYesterdayCount
        },
      ]
    };
    this.setState({
      errorReportOption,
    })
  }
  // 调整3d地图仰视角
  changePitch(e) {
    this.props.locaMap.setPitch(e);
  }
  // gIFT建模
  setGITFMark() {
    const { AMap } = window
    // let { gITFPoint } = this.state;
    const { locaMap, gITFPoint } = this.props

    // 地图图块加载完成后触发
    locaMap.on('complete', () => {
      // 加载3d模型组件
      let gITFMarks = []
      var object3Dlayer = new AMap.Object3DLayer();
      this.props.dispatch({
        type: "command/changeObject3Dlayer",
        payload: object3Dlayer,
      });
      locaMap.add(object3Dlayer);
      var gltfObj = new AMap.GltfLoader();
      gITFPoint.forEach(item => {
        let marker = new AMap.Marker({
          icon: "https://bcxin-saas-test.obs.cn-north-1.myhuaweicloud.com:443/upload%2F2021-09-18%2F1631951346190020782.png",
          // icon: "../../../../../src/assets/images/prevention/gIFT.png",
          position: [item.lng, item.lat],
        });
        var paramCity = {
          position: new AMap.LngLat(item.lng, item.lat), // 必须
          scale: 10,// 非必须，默认1
          height: 0,  // 非必须，默认0
          scene: 0, // 非必须，默认0
        };
        let cityMeshes = null
        AMap.event.addListener(marker, "click", () => {
          if (!item.isShow) {
            this.props.dispatch({
              type: "command/setSwitchOpenStatus",
              payload: {
                type: 'is3D',
                value: true
              },
            });
            gltfObj.load(item.gIFTurl, (gltfCity) => {
              cityMeshes = gltfCity;
              item.cityMeshes = gltfCity
              gltfCity.setOption(paramCity);
              switch (item.name) {
                case "rjyA":
                  gltfCity.rotateX(90);
                  break;
                case "rjyB":
                  gltfCity.rotateX(90);
              }
              item.isShow = true;
              this.props.dispatch({
                type: "command/changeGITFPoint",
                payload: gITFPoint,
              });
              object3Dlayer.add(gltfCity);
            });
            locaMap.setZoomAndCenter(17, [item.lng, item.lat])
            locaMap.setPitch(50)
            // locaMap.setPitch(0)
            this.props.setSatellite(true)

          } else {
            object3Dlayer.remove(cityMeshes);
            item.isShow = false;
            this.props.dispatch({
              type: "command/changeGITFPoint",
              payload: gITFPoint,
            });
          }
        });
        gITFMarks.push(marker)
      })
      locaMap.add(gITFMarks);
    });
  }
  render() {
    const { all, down, left, right, is3D, search } = this.props.switchOpenStatus
    const { searchViews, resourceViews, eventViews } = this.props.mapLayerSwitchState
    const { mapStyle, searchAround, selectAttendInfo,selectComponeyInfo, selectComponyList } = this.props
    console.log('APicture-state', this.state);
    return (
      <div style={{ display: '' }} className={styles[mapStyle]}>
        <div className={styles.slider} style={{ display: is3D ? '' : 'none' }}>
          <Slider onChange={this.changePitch.bind(this)} vertical defaultValue={0} />
        </div>
        {/* <div style={{ display: left ? 'none' : '' }}>
          <div className={styles.todayError}>
            <div className={styles.title}>
              <img src={require('../../../../assets/images/prevention/aPicture/todayError.png')} />
              <div>今日异常</div>
            </div>
            <div className={styles.todayErrorContent}>
              <div className={styles.todayCount}>{this.state.todayCount}</div>
              <div className={styles.otherDay}>
                <div style={{ color: '#00B40C' }} className={styles.otherDayCount}>
                  <span>昨日异常</span>
                  <div style={{ border: '1px solid #00B40C' }}>{this.state.yesterdayCount}</div>
                </div>
                <div style={{ color: '#0E70FF' }} className={styles.otherDayCount}>
                  <span>前日异常</span>
                  <div style={{ border: '1px solid #0E70FF' }}>{this.state.beforeYesterdayCount}</div>
                </div>
              </div>
            </div>
          </div>
          <div className={styles.errorTime} style={{ height: this.state.errorTimeHeight }}>
            <div className={styles.title}>
              <img src={require('../../../../assets/images/prevention/aPicture/errorTime.png')} />
              <div>异常事件</div>
            </div>
            <ReactEcharts option={this.state.errTimeOption} style={{ height: '400px', width: '100%' }} />
          </div>
          <div className={styles.nowError}>
            <div className={styles.title}>
              <img src={require('../../../../assets/images/prevention/aPicture/nowError.png')} />
              <div >实时异常</div>
            </div>
            <div className={styles.norErrorContent}>
              {
                this.state.nowErrorList.map(item => {
                  return (
                    <div onClick={this.getEventAddress.bind(this, item)} className={styles.nowErrorItem} key={item.id}>
                      <div className={styles.itemTitle}>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                          <Icon type="clock-circle" className={styles.icon} />
                          <div>{item.alarmTime}</div>
                        </div>
                        <div>{item.eventType}</div>
                      </div>
                      <div className={styles.itemInfo}>
                        <div title={item.eventType} style={{ border: '1px solid #FF6416', color: '#FF6416' }}>{item.eventType}</div>
                        <span>{item.eventName}</span>
                      </div>
                      <div className={styles.itemInfo}>
                        <div style={{ border: '1px solid #0E70FF', color: '#0E70FF' }}>编号</div>
                        <span>{item.eventNO}</span>
                      </div>
                      <div className={styles.itemInfo}>
                        <div style={{ border: '1px solid #0E70FF', color: '#0E70FF' }}>地址</div>
                        <span>{item.eventPlace}</span>
                      </div>
                    </div>
                  )
                })
              }
            </div>
          </div>
        </div> */}

        {/* <div style={{ display: down ? 'none' : '' }}>
          <div className={styles.errorReport}>
            <div className={styles.title}>
              <img src={require('../../../../assets/images/prevention/aPicture/errorReport.png')} />
              <div>分时异常报告</div>
            </div>
            <ReactEcharts option={this.state.errorReportOption} style={{ height: '230px', width: '100%' }} />
          </div>
        </div> */}
        {
          eventViews ? <MapEventModule /> : null
        }
        {
          selectAttendInfo.selectAttendId ? <AttendInfo
            // addPictueMarks={(data, type) => {
            //   this.props.addPictueMarks(data, type);
            // }}
            // reducePictueMarks={(data, type) => {
            //   this.props.reducePictueMarks(data, type);
            // }}
          /> : ""
        }
        {
          selectComponeyInfo.selectComponeyId ? < Componey
          // addPictueMarks={(data, type) => {
          //   this.props.addPictueMarks(data, type);
          // }}
          // reducePictueMarks={(data, type) => {
          //   this.props.reducePictueMarks(data, type);
          // }}
        /> : selectComponyList && selectComponyList.length > 0 ? <ComponyList /> : null
        }
        { searchViews && <ComprehensiveSearch _thisGIS={this.props._thisGIS} /> }
        {
          /* 周边搜索组件 */
          searchAround.show && searchAround.type == 'aPicture' &&
          <Search
            _thisGIS={this.props._thisGIS}
            onClose={(value) => this.props.changeShowSearchView(value)}
            lnglat={searchAround.lnglat}
            // addPictueMarks={(data, type, where) => {
            //   this.props.addPictueMarks(data, type, where);
            // }}
            // reducePictueMarks={(data, type, where) => {
            //   this.props.reducePictueMarks(data, type, where);
            // }}
          />
        }
        <div style={{ display: resourceViews ? '' : 'none' }}>
          {/* <div className={styles.errorTimeReport}>
            <div className={styles.title}>
              <img src={require('../../../../assets/images/prevention/aPicture/errorTimeReport.png')} />
              <div>异常事件报告</div>
            </div>
            <ReactEcharts option={this.state.errorTimeReport} style={{ height: '230px', width: '100%' }} />
          </div> */}
          {/* 一张图数据展示 */}
          <APictureData
            _thisGIS={this.props._thisGIS}
          />
          {
            search &&
            <InfoSearch
              _thisGIS={this.props._thisGIS}
            />
          }
        </div>
      </div>
    );
  }
}
