<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-col :span="2">
              <el-form-item label-width="0">
                <el-button type="primary" size="small" style="width:85px">导出</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">
          <!-- <div class="chart-div" v-for="(item,index) in targetData" :key="index">
            <div class="chart-title" v-cloak>{{item.targetName}}({{item.targetCode}})</div>
            <div :id="'curve-chart'+index" class="chartBox"></div>
          </div> -->
          <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 class="chart-title" v-cloak>{{key}}</div> -->
            <div :ref="targetObj[key].target.targetCode" class="chartBox"></div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="列表" name="second" style="height:100%">
          <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: 1,
      activeName: 'first',
      targetObj: {},
      targetOptions1: [],
      targetOptions2: [],
      targetData: [], // 图表类型
      tableData: [], // 列表数据
      pageTableData: [], // 列表分页数据
      dialogDragWidth: '520px',
      timeType: 1,
      customProps: {
        value: 'id',
        label: 'name',
        children: 'data'
      },
      totleTargets: [],
      pagination: { current: 1, size: 50, total: 0 }
    }
  },
  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])
      }
    }
  },
  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) {
      console.log('typeId', 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) {
      Object.assign(this.$data, this.$options.data.call(this))
      await this.getSites(siteId)
      this.dialogVisible = true
      if (siteId != null) {
        this.getHistoryCurve({ siteId: siteId, checkCodes: this.targets.join(',') })
      }
    },
    /**
     * 获取站点
     */
    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
    },
    /**
     * 处理返回的曲线数据
     */
    dealCurveData(params, res) {
      if (res.code && res.code == 1) {
        if (!res.result || !res.result.list || res.result.list instanceof Array == false) {
          this.targetObj = {}
          this.targetData = []
          this.tableData = []
          return
        }
        // const tableData = res.result.list[0]
        // 显示最新时间
        if (!params.hasOwnProperty('beginTime') && !params.hasOwnProperty('endTime')) {
          this.timeType = 7
          this.form.date = [res.result.map.X1[0], res.result.map.X1[res.result.map.X1.length - 1]]
        }
        // 主站点
        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)
        // console.log('图表668', targetObj)
        this.targetObj = targetObj
        for (const key in targetObj) {
          const item = targetObj[key]
          // 加载图表
          this.$nextTick(() => {
            let { series, legends } = this.getChartData(item.data)
            this.loadChart(item.target.targetCode, legends, res.result.map, series)
          })
        }
      }
    },
    /**
     * 组织返回的数据
     */
    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))
        console.log('指标ss', totleTargets)
        // 组合数据
        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) {
      if (this.radio == 1) {
        getCurve(params).then((res) => {
          this.dealCurveData(params, res)
        })
      } else if (this.radio == 2) {
        getHourCurve(params).then((res) => {
          this.dealCurveData(params, res)
        })
      } else if (this.radio == 3) {
        getDayCurve(params).then((res) => {
          this.dealCurveData(params, res)
        })
      }
    },
    /**
     * 获取查询时间
     */
    // getQueryTime() {
    //   // 当前时间
    //   const CURRENT_TIME = this.$moment().format('YYYY-MM-DD HH:mm:ss')
    //   let endTime = ''
    //   let startTime = ''
    //   // 获取时间
    //   switch (this.timeType) {
    //     case 1: // 近24小时
    //       endTime = CURRENT_TIME // 当前时间
    //       startTime = this.$moment(CURRENT_TIME).subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss')
    //       break
    //     case 2: // 今天
    //       endTime = this.$moment(CURRENT_TIME).format('YYYY-MM-DD HH:mm:ss')
    //       startTime = this.$moment(CURRENT_TIME).format('YYYY-MM-DD 00:00:00')
    //       break
    //     case 3: // 昨天
    //       endTime = this.$moment(CURRENT_TIME).subtract(1, 'day').format('YYYY-MM-DD 23:59:59')
    //       startTime = this.$moment(CURRENT_TIME).subtract(1, 'day').format('YYYY-MM-DD 00:00:00')
    //       break
    //     case 4: // 近7天
    //       endTime = this.$moment(CURRENT_TIME).subtract(1, 'day').format('YYYY-MM-DD 23:59:59')
    //       startTime = this.$moment(endTime).subtract(7, 'day').format('YYYY-MM-DD 00:00:00')
    //       break
    //     case 5: // 近15天
    //       endTime = this.$moment(CURRENT_TIME).subtract(1, 'day').format('YYYY-MM-DD 23:59:59')
    //       startTime = this.$moment(endTime).subtract(15, 'day').format('YYYY-MM-DD 00:00:00')
    //       break
    //     case 6:
    //       endTime = this.$moment(CURRENT_TIME).subtract(1, 'day').format('YYYY-MM-DD 23:59:59')
    //       startTime = this.$moment(endTime).subtract(30, 'day').format('YYYY-MM-DD 00:00:00')
    //       break
    //     case 7:
    //       endTime = this.$moment(this.form.date[1]).format('YYYY-MM-DD 23:59:59')
    //       startTime = this.$moment(this.form.date[0]).format('YYYY-MM-DD 00:00:00')
    //       break
    //   }
    //   return {
    //     startTime: startTime,
    //     endTime: endTime
    //   }
    // },
    /**
     * 查询
     */
    query() {
      let params = this.readyParams()
      this.getHistoryCurve(params)
    },
    /**
     * 图表数据
     */
    getChartData(seriesList) {
      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
        })
      })
      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'
          }
        ],
        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()
    }
  }
}
</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);
      overflow-y: auto;
      .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>