<template>
  <div>
    <div class="params-panel">
      <div class="head-title">站点设置</div>
      <el-form ref="form" :model="form" label-width="auto" size="small">
        <el-form-item label="监测站点:">
          <el-select
            v-model="form.siteId"
            filterable
            placeholder="选择站点"
            style="width:100%"
            @change="selectSite"
          >
            <el-option
              v-for="(item,index) in siteOption"
              :key="index"
              :label="item.siteName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间设置:" style="line-height:78px;">
          <el-radio-group v-model="cycle">
            <el-radio :label="3">24小时水质变化规律</el-radio>
            <el-radio :label="2">7日水质变化规律</el-radio>
            <el-radio :label="1">30日水质变化规律</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="时段设置:" style="line-height:93px;">
          <div class="timeset-btns">
            <el-button type="text" icon="el-icon-plus" @click="dialogVisible=true"></el-button>
            <el-button type="text" icon="el-icon-minus" @click="removeTime()"></el-button>
            <span style="color:#606266">（说明:每个时段代表一条新线）</span>
          </div>
          <div class="time-container">
            <ul>
              <li v-for="(item,index) in timeItems" :key="index">
                <el-checkbox v-model="item.checked" v-cloak>时段：{{item.beginTime}}-{{item.endTime}}</el-checkbox>
              </li>
            </ul>
          </div>
        </el-form-item>
        <el-form-item label-width="0" style="text-align:right;">
          <el-button type="primary" @click="query()">查询</el-button>
          <el-button type="primary" @click="clear()">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 结果 -->
    <div class="result-panel">
      <div class="head-title" style="height:32px;line-height:32px;">
        <span>对比结果</span>
        <div style="float:right;font-weight:500">
          <span>统计方式:</span>
          <el-select v-model="granularity" size="small" style="width:120px">
            <el-option label="按小时统计" :value="2"></el-option>
            <el-option label="按日统计" :value="1"></el-option>
          </el-select>
        </div>
      </div>
      <!-- 结果 -->
      <div class="result-box">
        <div class="empty" v-if="targetVos.length==0"></div>
        <div v-for="(item,index) in targetVos" :key="index" :id="'chart'+index" class="chart-box"></div>
      </div>
    </div>

    <!-- 时间选择 -->
    <el-dialog title="选择统计时间区段" :visible.sync="dialogVisible" width="500px">
      <el-form :inline="true" label-width="80px" size="small">
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            value-format="yyyy/MM/dd"
            format="yyyy/MM/dd"
            :clearable="false"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" size="small" @click="selectTime()">确 定</el-button>
      </span>
    </el-dialog>
    <historyCurve ref="historyCurve"></historyCurve>
  </div>
</template>

<script>
import { getSites, getSiteNewData } from '@/views/spectrum/dynamicMonitor/api/api'
import { getSiteManyCurve } from '@/views/spectrum/statisticalAnalysis/api/api'
import { getSiteIcon } from '@/views/spectrum/common/siteIcon/siteIcon' // 站点图标

import { MapPopup } from '@/views/spectrum/common/mapPopup/mapPopup'
import historyCurve from '@/views/spectrum/common/historyCurve/index'
import { creatTipMonitor } from '@/views/spectrum/common/mapPopup/getPopupInfo'
export default {
  components: {
    historyCurve
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      form: {},
      cycle: 3,
      granularity: 2,
      timeItems: [],
      date: [],
      dialogVisible: false,
      siteOption: [],
      targetVos: [],
      popup: null, // 弹窗
      handler: null
    }
  },
  created() {},
  mounted() {
    this.getSites()
    this.initClick()
  },
  destroyed() {
    window.viewer.entities.removeAll()
    if (this.popup) this.popup.destroy()
    if (this.handler) this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
  },
  methods: {
    /**
     * 获取站点
     */
    getSites() {
      getSites({ projectId: this.$store.state.project.project.id, size: 1000 }).then((res) => {
        if (res.code && res.code == 1) {
          this.siteOption = res.result.records
          // if (this.siteOption.length > 0) {
          //   this.$set(this.form, 'siteId', this.siteOption[0].id)
          // }
        }
      })
    },
    /**
     * 选择站点
     */
    selectSite(val) {
      let site = this.siteOption.find((item) => {
        return item.id == val
      })
      this.showSite(site)
    },
    /**
     * 监听站点点击事件
     */
    initClick() {
      let viewer = window.viewer
      this.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
      this.handler.setInputAction((movement) => {
        var pick = viewer.scene.pick(movement.position)
        if (Cesium.defined(pick)) {
          // 本组件定义弹窗存在先移除
          if (this.popup) {
            this.popup.destroy()
          }
          let siteId = pick.id.id
          let siteData = this.siteOption.find((item) => {
            return item.id == siteId
          })
          if (siteData) {
            // 展示实时数据
            this.getSiteNewData([siteData])
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    },
    /**
     * 获取站点实时数据
     */
    getSiteNewData(sites) {
      let ids = sites.map((item) => {
        return item.id
      })
      getSiteNewData({ sites: ids.join(',') }).then((res) => {
        if (res.code && res.code == 1) {
          let result = res.result
          creatTipMonitor(sites, result, (data, tipHtml) => {
            let viewer = window.viewer
            this.popup = new MapPopup({
              lon: data.longitude,
              lat: data.latitude,
              viewer: viewer,
              title: data.siteName,
              html: tipHtml,
              cureBtnClick: () => {
                // 查看历史曲线
                this.$refs.historyCurve.show(data.id)
              }
            })
          })
        }
      })
    },
    /**
     * 选择时间区间
     */
    selectTime() {
      if (this.date.length == 2) {
        let timeItem = {
          checked: false,
          beginTime: this.date[0],
          endTime: this.date[1]
        }
        this.timeItems.push(timeItem)
        this.dialogVisible = false
        this.date = []
      }
    },
    /**
     * 移除时间段
     */
    removeTime() {
      let selection = this.timeItems.filter((item) => {
        return item.checked == true
      })
      if (selection.length == 0) {
        this.$message.info('请选择要移除的时间段！')
        return
      }
      this.timeItems = this.timeItems.filter((item) => {
        return item.checked == false
      })
    },
    /**
     * 查询
     */
    query() {
      if (!this.form.siteId) {
        this.$message.info('请选择检测站点！')
        return
      }
      if (this.timeItems.length == 0) {
        this.$message.info('请选择时间区段！')
        return
      }
      let data = {
        cycle: this.cycle,
        granularity: this.granularity,
        siteId: this.form.siteId,
        times: this.timeItems.map((item) => {
          return {
            beginTime: this.$moment(item.beginTime).format('YYYY-MM-DD'),
            endTime: this.$moment(item.endTime).format('YYYY-MM-DD')
          }
        })
      }
      getSiteManyCurve(data).then((res) => {
        if (res.code && res.code == 1) {
          let siteData = res.result
          if (siteData) {
            this.targetVos = siteData.targetVos // 名称
            let collectionDates = siteData.data_x //时间
            let datas = siteData.datas[0] //数据

            this.targetVos.forEach((item, index) => {
              let columnName = `${item.targetCode}s`
              let series = []
              datas.forEach((item2, index2) => {
                let _data = item2[columnName].map((item3) => {
                  return item3 || 0
                })
                let seriesdata = {
                  name: `${item.targetName}${index2 + 1}`,
                  type: 'line',
                  data: _data
                }
                series.push(seriesdata)
              })

              let chartData = {
                seriesdata: series,
                collectionDates: collectionDates
              }
              this.$nextTick(() => {
                this.loadChart(chartData, item, index)
              })
            })
          }
        }
      })
    },
    loadChart(chartData, target, domIndex) {
      let chartDom = document.getElementById('chart' + domIndex)
      let myChart = this.$echarts.init(chartDom)
      let colorAry = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
      let option = {
        title: {
          show: 'true', //是否显示标题，默认显示，可以不设置
          text: `${target.targetName}(${target.targetCode})`, //图表标题文本内容
          textStyle: {
            color: '#3E84D2',
            fontSize: '12px',
            fontWeight: 600
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        color: colorAry,
        grid: {
          top: 35,
          bottom: 30,
          left: 30,
          right: 30
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: chartData.collectionDates
        },
        yAxis: {
          type: 'value'
        },
        series: chartData.seriesdata
      }
      myChart.clear()
      option && myChart.setOption(option)
    },
    /**
     * 清除
     */
    clear() {
      this.timeItems = []
      this.targetVos = []
    },
    /**
     * 定位选择的站点
     */
    showSite(site) {
      let icon = getSiteIcon(site)
      let viewer = window.viewer
      let lon = site.longitude || null
      let lat = site.latitude || null
      if (!lon || !lat) {
        this.$message.warning('无坐标信息，无法定位！')
        return
      }
      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.removeAll()
        viewer.entities.add(entity)
      }
      // 本组件定义弹窗存在先移除
      if (this.popup) {
        this.popup.destroy()
      }
      viewer.flyTo(entity, {
        offset: {
          heading: Cesium.Math.toRadians(0.0),
          pitch: Cesium.Math.toRadians(-25),
          range: 3000
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import './css.scss';
</style>