<template>
  <div class="page-panel">
    <div class="head-title">{{title}}</div>
    <div>
      <span style="margin-left:10px;color:#606266">时间轴：</span>
      <el-slider v-model="value1" class="time-slider" :show-tooltip="false" :step="1" :min="0" :max="sliderMax" :disabled="sliderMax==0||!checked" @change="sliderChange"></el-slider>
      <el-checkbox v-model="checked" style="margin-left:20px">实时监测信息地图标注</el-checkbox>
      <div class="an-type">
        <span style="margin-left:100px;color:#606266">统计方式：</span>
        <el-radio-group v-model="radio" @change="radioChange">
          <el-radio label="1">每日平均</el-radio>
          <el-radio label="2">每小时平均</el-radio>
        </el-radio-group>
      </div>
    </div>
    <div class="chart-box">
      <div class="chart-item" ref="chart1">
        <div class="empty"></div>
      </div>
      <div class="chart-item" ref="chart2">
        <div class="empty"></div>
      </div>
    </div>
    <el-table :data="tableData" stripe style="width: 100%" :header-cell-style="{backgroundColor:'#eaf1fd',height:'39px',textAlign:'center',fontWeight:600}" max-height="350px">
      <template slot="empty">
        <img src="@/assets/icon/null.png" alt />
      </template>
      <el-table-column prop="collectionDate" label="采集时间" align="center"></el-table-column>
      <el-table-column prop="siteName" label="监测站点名称" align="center"></el-table-column>
      <el-table-column prop="deviceTypeName" label="设备类型" align="center"></el-table-column>
      <el-table-column prop="targetValue" label="监测值" align="center">
        <template slot-scope="{row}">{{row.targetValue?row.targetValue:'/'}}</template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getManySiteCurv } from '@/views/spectrum/statisticalAnalysis/api/api'
import { getSiteIcon } from '@/views/spectrum/common/siteIcon/siteIcon' // 站点图标
import { MapPopup } from '@/views/spectrum/common/mapPopup/mapPopup'
import * as echarts from 'echarts'
export default {
  name: 'sitesanalysisResult',
  data() {
    return {
      value1: 0,
      checked: false,
      tableData: [],
      radio: '2',
      title: '',
      sliderMax: 0,
      dateCollection: [], // 日期
      targetVos: [] // 数据
    }
  },
  computed: {
    halfPanels() {
      return this.$store.state.map.halfPanels
    },
    param() {
      let panel = this.halfPanels.find((item) => {
        let coms = item.com.split('/')
        let panelName = coms[coms.length - 1]
        return (panelName = 'sitesanalysisResult')
      })
      console.log('panel.param', panel.param)
      return panel.param
    }
  },
  watch: {
    checked(val, oldVal) {
      if (val) this.showSites()
      else this.clearSites()
    }
  },
  mounted() {
    this.getManySiteCurv()
  },
  destroyed() {
    this.clearSites()
  },
  methods: {
    getManySiteCurv() {
      this.title = this.param.titleName
      let params = this.param.params
      params['granularity'] = this.radio
      getManySiteCurv(params).then((res) => {
        let siteData = res.result
        let vosData = res.result.vos
        let _targetListVos = siteData.targetListVos //数据
        let _collectionDates = siteData.collectionDates //时间

        this.dateCollection = JSON.parse(JSON.stringify(siteData.collectionDates))
        this.sliderMax = this.dateCollection.length > 0 ? this.dateCollection.length - 1 : 0
        this.targetVos = JSON.parse(JSON.stringify(siteData.targetListVos))

        let _dataX = []

        let _formatterVal = 'YYYY-MM-DD'
        if (this.radio == '2') {
          _formatterVal = 'MM-DD HH'
        }
        _collectionDates.forEach((item) => {
          _dataX.push(this.$moment(item).format(_formatterVal))
        })

        let _seriesdataLine = []
        let _seriesdataBar = []
        _targetListVos.forEach((item) => {
          let _data = item.values.map((item2) => {
            return item2 || 0
          })
          let seriesdataLine = {
            name: item.siteName,
            type: 'line',
            data: _data
          }
          _seriesdataLine.push(seriesdataLine)

          let seriesdataBar = {
            name: item.siteName,
            type: 'bar',
            data: _data
          }
          _seriesdataBar.push(seriesdataBar)
        })
        let chartDataLine = {
          id: 'linedata',
          seriesdata: _seriesdataLine,
          collectionDates: _dataX
        }

        let chartDataBar = {
          id: 'bardata',
          seriesdata: _seriesdataBar,
          collectionDates: _dataX
        }
        this.$nextTick(() => {
          this.loadChart(chartDataLine, 'chart1')
        })
        this.$nextTick(() => {
          this.loadChart(chartDataBar, 'chart2')
        })
        this.tableData = JSON.parse(JSON.stringify(vosData))
      })
    },
    /**
     *改变统计类型
     */
    radioChange(val) {
      this.getManySiteCurv()
    },
    /**
     * 加载图表
     */
    loadChart(chartData, domId) {
      let chartDom = this.$refs[domId]
      let myChart = echarts.init(chartDom)
      let colorAry = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
      let option = {
        tooltip: {
          trigger: 'axis'
        },
        color: colorAry,
        grid: {
          top: 30,
          bottom: 30,
          left: 35,
          right: 25,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: domId == 'chart1' ? false : true,
          data: chartData.collectionDates
        },
        yAxis: {
          type: 'value'
        },
        series: chartData.seriesdata
      }
      myChart.clear()
      option && myChart.setOption(option)
      window.addEventListener('resize', function () {
        myChart.resize()
      })
    },
    /**
     * 站点信息框
     */
    createTipBox(site, index = 0) {
      let viewer = window.viewer
      let _site = this.targetVos.find((item) => {
        return item.siteId == site.id
      })

      new MapPopup({
        lon: site.longitude,
        lat: site.latitude,
        viewer: viewer,
        title: site.siteName,
        cureBtn: false,
        html: _site
          ? `
          <span>${this.dateCollection[index] ? this.dateCollection[index] : '/'}</span>
          <span>${this.param.targetName}：${_site.values[index] ? _site.values[index] : '/'}</span>`
          : `<span>暂无数据</span>`
      })
    },
    /**
     * 实时监测信息标注
     */
    showSites() {
      let sites = this.param.sites
      let targetSite = this.param.targetSite

      let viewer = window.viewer
      window.viewer.entities.removeAll()
      sites.forEach((site) => {
        let icon = getSiteIcon(site, false)
        let lon = site.longitude || null
        let lat = site.latitude || null
        if (!lon || !lat) {
          this.$message.warning('无坐标信息，无法显示！')
          return
        }

        this.createTipBox(site)

        let entity = viewer.entities.getById(site.id)
        if (!entity) {
          const position = Cesium.Cartesian3.fromDegrees(lon, lat, 0)
          entity = new Cesium.Entity({
            id: site.id,
            position: position,
            billboard: {
              image: icon,
              width: 40,
              height: 70,
              heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
              eyeOffset: Cesium.Cartesian3.ZERO
            }
          })
          viewer.entities.add(entity)
        }
        // viewer.flyTo(entity, {
        //   offset: {
        //     heading: Cesium.Math.toRadians(0.0),
        //     pitch: Cesium.Math.toRadians(-25),
        //     range: 3000
        //   }
        // })
      })
      console.log('站点：', sites)
    },
    /**
     * 滑块移动
     */
    sliderChange(val) {
      let sites = this.param.sites
      MapPopup.clearAll()
      sites.forEach((site) => {
        let lon = site.longitude || null
        let lat = site.latitude || null
        if (!lon || !lat) {
          this.$message.warning('无坐标信息，无法显示！')
          return
        }
        this.createTipBox(site, val)
      })
    },
    /**
     * 清除站点标注
     */
    clearSites() {
      window.viewer.entities.removeAll()
      MapPopup.clearAll()
    }
  }
}
</script>

<style lang="scss" scoped>
.head-title {
  font-size: 15px;
  font-family: '宋体';
  color: #333333;
  line-height: 18px;
  margin: 10px 0;
  font-weight: 600;

  &::before {
    content: '';
    display: inline-block;
    width: 3px;
    height: 16px;
    background: #2a77f7;
    vertical-align: text-bottom;
    margin-right: 5px;
  }
}
.page-panel {
  overflow-y: auto;
  .an-type {
    float: right;
    margin-right: 10px;
  }
  .time-slider {
    width: 350px;
    display: inline-block;
    vertical-align: middle;
  }
}
.el-table {
  >>> .el-table__cell {
    padding: 6px 0 !important;
  }
}
.chart-box {
  height: 260px;
  .chart-item {
    width: 50%;
    height: 100%;
    float: left;
    > div.empty {
      width: 100%;
      height: 100%;
      background: url('../../../../../assets/icon/null.png') no-repeat;
      background-position-x: 50%;
      background-position-y: 30%;
    }
  }
}
</style>