<template>
  <div>
    <!-- 地图通用组件：历史曲线 -->
    <el-dialog v-dialogDrag title="历史监测信息" :visible.sync="dialogVisible" :modal="false" :append-to-body="true" width="1200px">
      <div class="top">
        <el-form ref="form" :model="form" label-width="auto" size="small">
          <el-row :gutter="24">
            <el-col :span="7">
              <el-form-item label="监测站点">
                <el-cascader v-model="form.siteId" :props="customProps" :options="siteOption" :show-all-levels="false" clearable @change="value=>{siteChange(1,value)}" placeholder="选择站点" style="width:100%"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="监测指标">
                <el-select v-model="targets" filterable multiple collapse-tags placeholder="选择站点" style="width:100%">
                  <el-option v-for="(item,index) in targetOptions1" :key="index" :label="item.targetName" :value="item.targetCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="时间范围">
                <el-date-picker v-model="form.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" style="width:100%" :clearable="false">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="7">
              <el-form-item label="对比监测站点">
                <el-cascader v-model="form.siteId2" :props="customProps" :options="siteOption" :show-all-levels="false" clearable @change="value=>{siteChange(2,value)}" placeholder="选择站点" style="width:100%"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="对比监测指标">
                <el-select v-model="targets2" filterable multiple collapse-tags placeholder="选择站点" style="width:100%">
                  <el-option v-for="(item,index) in targetOptions2" :key="index" :label="item.targetName" :value="item.targetCode">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="同比开始时间">
                <!-- <el-date-picker v-model="form.date2" type="date" placeholder="选择日期" style="width: 100%;"></el-date-picker> -->
                <el-date-picker v-model="form.date2" type="datetime" placeholder="选择日期时间" style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item label-width="0">
                <el-button type="primary" size="small" style="width:85px" @click="query()">查询</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="time-select">
        <el-radio-group v-model="radio">
          <el-radio :label="1">实时数据</el-radio>
          <el-radio :label="2">每小时均值</el-radio>
          <el-radio :label="3">每日均值</el-radio>
        </el-radio-group>
      </div>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" style="height:550px">
        <el-tab-pane label="图表" name="first" :disabled="tabPaneDisabled">
          <div class="chartsdiv" ref="chartsdiv">
            <div class="chart-div" v-for="(value,key) in targetObj">
              <div class="chart-title" v-cloak>{{targetObj[key].target.targetName}}({{targetObj[key].target.targetCode}})</div>
              <div :ref="targetObj[key].target.targetCode" class="chartBox"></div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="列表" name="second" style="height:100%" :disabled="tabPaneDisabled">
          <el-table :data="pageTableData" stripe height="calc(100% - 45px)" style="width:100%" :header-cell-style="{background:'#e0eafb',color:'rgb(50,59,65)',height:'39px',textAlign:'center',fontWeight:'600'}">
            <template slot="empty">
              <img src="@/assets/icon/null.png" alt="" />
            </template>
            <el-table-column prop="date" label="序号" width="50" align="center">
              <template slot-scope="scope">{{scope.$index+1}}</template>
            </el-table-column>
            <el-table-column prop="collectionDates" label="采集时间" align="center"></el-table-column>
            <el-table-column v-for="(item,index) in targetData" :key="index" :prop="item.targetCode+'s'" :label="item.targetName" align="center">
            </el-table-column>
          </el-table>
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagination.current" small :page-sizes="[20, 50, 100, 150]" :page-size="pagination.size" layout="total, sizes, prev, pager, next"
            :total="pagination.total">
          </el-pagination>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCurve,
  getHourCurve,
  getDayCurve,
  getSites,
  getGroupSite,
  getTargetByType,
  getRainfallHour
} from '@/views/spectrum/dynamicMonitor/api/api'

import elementResizeDetectorMaker from 'element-resize-detector'

import * as echarts from 'echarts'
export default {
  name: 'historyCurve',
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '昨天',
            onClick(picker) {
              const start = new Date()
              const end = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              end.setTime(end.getTime() - 3600 * 1000 * 24)
              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 * 15)
              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 * 90)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近半年',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
              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])
            }
          }
        ]
      },
      areaColor: [
        ['rgba(126, 215, 243)', 'rgba(250, 253, 254)'],
        ['rgba(128, 255, 165)', 'rgba(1, 191, 236)'],
        ['rgba(0, 221, 255)', 'rgba(77, 119, 255)'],
        ['rgba(55, 162, 255)', 'rgba(116, 21, 219)'],
        ['rgba(255, 0, 135)', 'rgba(135, 0, 157)'],
        ['rgba(255, 191, 0)', 'rgba(224, 62, 76)'],
        ['rgba(0, 221, 255)', 'rgba(77, 119, 255)'],
        ['rgba(0, 221, 255)', 'rgba(77, 119, 255)']
      ], // 曲线图表颜色
      dialogVisible: false,
      siteOption: [],
      form: {
        date: []
      },
      targets: [],
      targets2: [],
      radio: 2,
      activeName: 'first',
      targetObj: {},
      targetOptions1: [],
      targetOptions2: [],
      targetData: [], // 图表类型
      tableData: [], // 列表数据
      pageTableData: [], // 列表分页数据
      dialogDragWidth: '520px',
      customProps: {
        value: 'id',
        label: 'name',
        children: 'data'
      },
      totleTargets: [],
      pagination: { current: 1, size: 50, total: 0 },
      loadingState: null,
      tabPaneDisabled: false
    }
  },
  mounted() { },
  watch: {
    radio(val, oldVal) {
      this.query()
    },

    targets2(val, oldVal) {
      if (oldVal.length == 0 && val.length > 0 && this.form.date && this.form.date.length > 0) {
        this.$set(this.form, 'date2', this.form.date[0])
      }
    },
    dialogVisible(val, oldVal) {
      if (!val) {
        this.loadingClose()
      }
    }
  },
  methods: {
    /**
     * 选择主站点
     */
    siteChange(type, value) {
      if (type == 1) {
        this.targetOptions1 = []
        this.targets = []
      } else {
        this.targetOptions2 = []
        this.targets2 = []
      }
      if (!value || value.length == 0) {
        return
      }
      const divice = this.getDivice(value[1])
      const typeId = divice.site.deviceType || null
      if (typeId) this.getTargetByType(type, typeId)
    },
    /**
     * 根据设备类型id获取指标
     */
    async getTargetByType(type, typeId) {
      await getTargetByType({ current: 1, size: 10000, typeId: typeId }).then((res) => {
        if (res.code == 1) {
          if (type == 1) {
            this.targetOptions1 = res.result.records
            let targets = this.targetOptions1.length > 0 ? [this.targetOptions1[0].targetCode] : []
            this.targets = targets
          } else {
            this.targetOptions2 = res.result.records
            let targets2 = this.targetOptions2.length > 0 ? [this.targetOptions2[0].targetCode] : []
            this.targets2 = targets2
          }
        }
      })
    },
    /**
     * 根据设站点id获取站点信息
     */
    getDivice(value) {
      let _group = null
      let _site = null
      for (let i = 0; i < this.siteOption.length; i++) {
        const group = this.siteOption[i]
        for (let j = 0; j < group.data.length; j++) {
          const site = group.data[j]
          if (site.id == value) {
            _group = group
            _site = site
            break
          }
        }
      }
      return {
        group: _group,
        site: _site
      }
    },
    /**
     * 展示曲线
     */
    async show(siteId = null, obj = {}) {
      Object.assign(this.$data, this.$options.data.call(this))
      await this.getSites(siteId)
      this.dialogVisible = true

      if (!siteId) return

      let params = { siteId: siteId }
      if (obj.beginDate && obj.endDate) {
        params['beginTime'] = this.$moment(obj.beginDate).format('YYYY-MM-DD 00:00:00')
        params['endTime'] = this.$moment(obj.endDate).format('YYYY-MM-DD 23:59:59')
        this.$set(this.form, 'date', [
          this.$moment(obj.beginDate).format('YYYY-MM-DD'),
          this.$moment(obj.endDate).format('YYYY-MM-DD')
        ])
      }
      if (obj.targets) {
        params['checkCodes'] = obj.targets.join(',')
        this.targets = obj.targets
      }
      // 获取曲线数据
      this.getHistoryCurve(params)
    },
    /**
     * 获取站点
     */
    async getSites(siteId) {
      await getGroupSite({ projectId: this.$store.state.project.project.id }).then(async (res) => {
        if (res.code && res.code == 1) {
          this.siteOption = res.result.records
          this.siteOption = res.result.map((item) => {
            item['name'] = `${item.groupName}(${item.size})`
            item['id'] = item.groupName
            item.data = item.data.map((item2) => {
              item2['name'] = item2.siteName
              return item2
            })
            return item
          })
          if (!siteId) return
          let { group, site } = this.getDivice(siteId)
          // 初始化选中站点
          if (group && site) this.$set(this.form, 'siteId', [group.id, siteId])
          if (site.deviceType) await this.getTargetByType(1, site.deviceType)
        }
      })
    },
    /**
     * 请求参数
     */
    readyParams() {
      // let timeInterval = this.getQueryTime() // 查询时间段一
      let timeInterval = {
        startTime: this.$moment(this.form.date[0]).format('YYYY-MM-DD 00:00:00'),
        endTime: this.$moment(this.form.date[1]).format('YYYY-MM-DD 23:59:59')
      }
      let params = {
        siteId: this.form.siteId[1],
        beginTime: timeInterval.startTime,
        endTime: timeInterval.endTime,
        checkCodes: this.targets.join(','),
        comprasionCheckCodes: this.targets2.join(',')
      }
      if (this.form.siteId2) params['comprasionSiteIds'] = this.form.siteId2[1]
      // 同比开始时间
      if (this.form.date2) params['comprasionBeginTime'] = this.$moment(this.form.date2).format('YYYY-MM-DD HH:mm:ss')
      // 时间差
      let seconds = this.$moment(timeInterval.endTime).diff(this.$moment(timeInterval.startTime), 'seconds')
      // 同比结束时间
      if (this.form.date2)
        params['comprasionEndTime'] = this.$moment(params.comprasionBeginTime)
          .add(seconds, 'second')
          .format('YYYY-MM-DD HH:mm:ss')
      return params
    },
    /**
     * 处理返回的曲线数据
     */
    async dealCurveData(params, res) {
      if (res.code && res.code == 1) {
        if (!res.result || !res.result.list || res.result.list instanceof Array == false) {
          this.tableData = []
          this.filedError()
          return
        }
        // 显示最新时间
        if (!params.hasOwnProperty('beginTime') && !params.hasOwnProperty('endTime')) {
          this.$set(this.form, 'date', [res.result.map.X1[0], res.result.map.X1[res.result.map.X1.length - 1]])
        }
        let rainData = null;
        if (this.radio != 3) {
          const startDate = this.$moment(this.form.date[0]).format("YYYY-MM-DD")
          const endDate = this.$moment(this.$moment(this.form.date[1]).add(1, 'd')).format("YYYY-MM-DD")
          // 雨量
          const getRainfallParams = {
            beginDate: startDate,
            endDate: endDate
          }
          let { result: rainFall } = await getRainfallHour(getRainfallParams);
          rainData = this.groupRainfallData(res.result.map.X1, rainFall)
        }
        // 主站点
        let mainData = res.result.list.find((item) => {
          return item.type == 'X1'
        })
        // 表格字段
        this.targetData = mainData.targetVos.filter((item) => {
          return this.targets.indexOf(item.targetCode) >= 0
        })
        this.loadTable(mainData)
        // 图表
        let targetObj = this.groupResponseData(res)

        this.targetObj = targetObj
        for (const key in targetObj) {
          const item = targetObj[key]
          // 加载图表
          this.$nextTick(() => {
            let { series, legends } = this.getChartData(item.data, rainData)
            this.loadChart(item.target.targetCode, legends, res.result.map, series)
          })
        }
        this.$nextTick(() => {
          this.loadingClose()
        })
      }
    },
    /**
     * 获取图表雨量数据
     */
    groupRainfallData(x1Data, rainFallData) {
      // 将雨量列表转对象
      let rainObj = {}
      for (let index = 0; index < rainFallData.length; index++) {
        const item = rainFallData[index];
        rainObj[this.$moment(item.xposition).format("_YYYY_MM_DD_HH")] = item.maxFall
      }
      let myRainFallData = []
      for (let index = 0; index < x1Data.length; index++) {
        const x1Item = this.$moment(x1Data[index]).format("_YYYY_MM_DD_HH");
        // const rain = rainFallData.find(item => { return this.$moment(item.xposition).format("YYYY-MM-DD HH") == x1Item })
        // myRainFallData.push(rain ? rain.maxFall : null)
        myRainFallData.push(rainObj[x1Item] ? rainObj[x1Item] : null)
      }
      return myRainFallData
    },
    /**
     * 组织返回的数据
     */
    groupResponseData(response) {
      let obj = {}
      const array = response.result.list
      for (let index = 0; index < array.length; index++) {
        const listItem = array[index]
        let targetVos = listItem.targetVos
        // 所有指标
        let targets = this.targets.concat(this.targets2)
        const totleTargets = Array.from(new Set(targets))
        // 组合数据
        for (let index2 = 0; index2 < targetVos.length; index2++) {
          const targetItem = targetVos[index2]
          if (totleTargets.indexOf(targetItem.targetCode) < 0) continue
          let targetData = {
            list: listItem[targetItem.targetCode + 's'],
            type: listItem.type
          }
          if (!obj.hasOwnProperty(targetItem.targetCode)) {
            obj[targetItem.targetCode] = {
              target: targetItem,
              data: [targetData]
            }
          } else {
            obj[targetItem.targetCode].data.push(targetData)
          }
        }
      }
      return obj
    },
    /**
     * 获取监测曲线数据
     */
    getHistoryCurve(params) {
      this.loading()
      if (this.radio == 1) {
        // 移除时间区间，查询最新数据
        const { beginTime, endTime, ...newParams } = params;
        getCurve(newParams).then((res) => {
          if (!res) {
            this.filedError()
            return
          }
          this.dealCurveData(newParams, res)
        })
      } else if (this.radio == 2) {
        getHourCurve(params).then((res) => {
          if (!res) {
            this.filedError()
            return
          }
          this.dealCurveData(params, res)
        })
      } else if (this.radio == 3) {
        getDayCurve(params).then((res) => {
          if (!res) {
            this.filedError()
            return
          }
          this.dealCurveData(params, res)
        })
      }
    },
    /**
     * 请求失败处理
     */
    filedError() {
      this.targetObj = {}
      this.targetData = []
      this.pageTableData = []
      this.pagination = { current: 1, size: 50, total: 0 }
      this.loadingClose()
    },
    /**
     * 查询
     */
    query() {
      let params = this.readyParams()
      this.getHistoryCurve(params)
    },
    /**
     * 图表数据
     */
    getChartData(seriesList, rainFallData = null) {
      let series = []
      let legends = []
      seriesList.forEach((item) => {
        const siteInfo = item.type == 'X1' ? this.getDivice(this.form.siteId[1]) : this.getDivice(this.form.siteId2[1])
        const siteName = siteInfo.site.siteName || '未知站点'
        legends.push(siteName)
        series.push({
          name: siteName,
          xAxisIndex: item.type == 'X1' ? 0 : 1,
          sampling: 'average', //降采样策略
          type: 'line',
          smooth: true,
          lineStyle: {
            width: 2
          },
          showSymbol: false,
          label: {
            show: true,
            position: 'top'
          },
          emphasis: {
            focus: 'series'
          },
          data: item.list
        })
      })
      if (rainFallData) {
        series.unshift({
          name: '雨量',
          xAxisIndex: 0,
          sampling: 'average', //降采样策略
          type: 'bar',
          yAxisIndex: 1,
          emphasis: {
            focus: 'series'
          },
          data: rainFallData
        })
        legends.unshift('雨量')
      }
      return {
        series: series,
        legends: legends
      }
    },
    /**
     * 加载图表
     */
    loadChart(domIndex, legends, xAxisList, seriesList) {
      const chartDom = this.$refs[domIndex][0]
      const myChart = echarts.init(chartDom)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: legends
        },
        grid: {
          top: '10%',
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0
            // end: 20
          },
          {
            start: 0
            // end: 20
          }
        ],
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: xAxisList.X1,
            axisLabel: {
              formatter: (dateTime) => {
                return this.formatAxisLabel(dateTime)
              }
            }
          },
          {
            type: 'category',
            boundaryGap: false,
            data: xAxisList.X2,
            axisLabel: {
              formatter: (dateTime) => {
                return this.formatAxisLabel(dateTime)
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          },
          {
            nameLocation: 'start',
            alignTicks: true,
            type: 'value'
          }
        ],
        series: seriesList
      }
      myChart.clear()
      option && myChart.setOption(option)

      elementResizeDetectorMaker().listenTo(chartDom, () => {
        this.$nextTick(() => {
          myChart.resize()
        })
      })
    },
    /**
     * 格式化 X 轴指标标签
     */
    formatAxisLabel(axisLabel) {
      if (this.radio == 3) return this.$moment(axisLabel).format('MM月DD日')
      else if (this.radio == 2) return this.$moment(axisLabel).format('MM月DD日HH时')
      else if (this.radio == 1) return this.$moment(axisLabel).format('MM月DD日HH时')
    },
    /**
     * 加载列表
     */
    loadTable(data) {
      let arr = []
      data.collectionDates.forEach((item, index) => {
        arr.push({ serialnum: index + 1 })
        const targetVos = data.targetVos
        for (let index1 = 0; index1 < targetVos.length; index1++) {
          const item1 = targetVos[index1]
          if (this.targets.indexOf(item1.targetCode) < 0) continue
          let columnName = item1.targetCode + 's'
          let columnVal = data[columnName]
          arr[index][columnName] = columnVal[index] ? columnVal[index] : '/'
        }
        arr[index]['collectionDates'] = item
      })
      this.tableData = arr
      this.getPageList()
    },
    /**
     * 分页操作
     */
    getPageList() {
      const { current, size } = this.pagination
      this.pageTableData = this.tableData.filter(
        (item, index) => index < current * size && index >= size * (current - 1)
      )
      this.pagination.total = this.tableData.length
    },
    //处理切换页码
    handleSizeChange(val) {
      this.pagination.size = val
      this.getPageList()
    },
    handleCurrentChange(val) {
      this.pagination.current = val
      this.getPageList()
    },
    /**
     * 加载状态
     */
    loading() {
      this.$nextTick(() => {
        this.tabPaneDisabled = true
        this.loadingState = this.$loading({
          target: this.$refs.chartsdiv,
          lock: false,
          text: '正在加载……',
          spinner: 'el-icon-loading',
          background: 'rgb(255, 255, 255)'
        });
      })
    },
    /**
     * 关闭加载状态
     */
    loadingClose() {
      this.tabPaneDisabled = false
      if (this.loadingState) this.loadingState.close()
    }
  }
}
</script>

<style lang="scss" scoped>
// 覆盖层元素增加可穿透点击事件
.el-dialog__wrapper {
  pointer-events: none;
  overflow: hidden;
  >>> .el-dialog {
    // 弹窗层元素不可穿透点击事件（不影响弹窗层元素的点击事件）
    pointer-events: auto;
    .el-dialog__header {
      background-color: #2d74e7;
      padding: 10px 20px 10px;
      .el-dialog__title {
        color: #ffffff;
        font-size: 16px;
      }
      .el-dialog__headerbtn {
        top: 15px;
      }
      .el-dialog__close {
        color: #ffffff !important;
      }
    }
    .el-dialog__full {
      position: absolute;
      top: 15px;
      right: 45px;
      i {
        color: #fff !important;
      }
    }
  }
  .el-form {
    >>> .el-form-item {
      .el-form-item__content {
        .el-radio-group {
          .el-radio {
            margin-right: 15px !important;
          }
        }
      }
    }
  }
  .time-select {
    position: absolute;
    right: 15px;
    top: 20p;
    margin-top: 15px;
    z-index: 99;
    .el-radio {
      >>> .el-radio__label {
        padding-left: 2px !important;
      }
    }
  }

  .el-tabs {
    >>> .el-tabs__content {
      height: calc(100% - 55px);
      .el-tab-pane {
        width: 100%;
        height: 100%;
      }
      .chartsdiv {
        width: 100%;
        height: 100%;
        overflow-y: auto;
        .el-loading-spinner {
          font-size: 30px;
        }
        .chart-div {
          margin-bottom: 20px;
          .chart-title {
            font-size: 16px;
            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: top;
              margin-right: 5px;
            }
          }
          .chartBox {
            width: 100%;
            height: 430px;
          }
        }
      }
    }
  }
  .el-table {
    >>> th > .cell {
      white-space: pre-line;
    }
    >>> .el-table__body {
      td.el-table__cell {
        height: 35px;
        padding: 0 !important;
      }
    }
    ::v-deep .el-table__body,
    ::v-deep .el-table__header,
    ::v-deep .el-table__empty-block {
      width: 100% !important;
    }
  }
  .el-pagination {
    margin-top: 10px;
  }
}
</style>