<template>
  <div>
    <!-- 地图通用组件：历史曲线 -->
    <el-dialog v-dialogDrag title="历史监测信息" :visible.sync="dialogVisible" :modal="false" :append-to-body="true" width="520px">
      <div class="top">
        <el-form ref="form" :model="form" label-width="auto" size="small">
          <el-row :gutter="24">
            <el-col :span="14">
              <el-form-item label="监测站点：" style="padding:0">
                <el-select v-model="form.siteId" filterable placeholder="选择站点">
                  <el-option v-for="(item,index) in siteOption" :key="index" :label="item.siteName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label-width="0">
                <el-button type="primary" size="small" style="width:85px">图上选点</el-button>
                <el-button type="primary" size="small" style="width:85px" @click="query()">查询</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="13" style="padding-right:0">
              <el-form-item label="日期范围：" style="padding:0">
                <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-col :span="11" style="padding-right:0">
              <el-form-item label-width="0">
                <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>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" type="card" style="height:500px">
        <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>
        </el-tab-pane>
        <el-tab-pane label="列表" name="second" style="height:100%">
          <el-table :data="tableData" stripe height="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="" />
              <p style="margin-top: -7px">暂无数据</p>
            </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 v-for="(item,index) in targetData" :key="index" :prop="item.targetCode+'s'" :label="item.targetName"
                             width="100" align="center">
            </el-table-column>
            <el-table-column prop="collectionDates" label="采集时间" width="200" align="center"></el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import { getHistoryCurve, getSites } from '@/views/spectrum/dynamicMonitor/api/api'

import * as echarts from 'echarts';
export default {
  name: "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]);
            }
          }]
      },
      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: [
          this.$moment().format('YYYY-MM-DD 00:00:00'),
          this.$moment().format('YYYY-MM-DD 23:59:59')
        ]
      },
      radio: 1,
      activeName: 'first',
      targetData: [], // 图表类型
      tableData: [], // 列表数据
    }
  },
  mounted() {

  },
  watch: {
    radio(val, oldVal) {
      if (val == 3) this.form['date'] = this.getSevenDate()
      else this.form['date'] = [
        this.$moment().format('YYYY-MM-DD 00:00:00'),
        this.$moment().format('YYYY-MM-DD 23:59:59')
      ]
    }
  },
  methods: {
    show(siteId) {
      this.getSites(siteId)
      this.dialogVisible = true
      this.getHistoryCurve({ siteId: siteId })
    },
    /**
     * 获取站点
     */
    getSites(siteId) {
      getSites({ projectId: this.$store.state.project.project.id, size: 1000 }).then(res => {
        if (res.code && res.code == 1) {
          this.siteOption = res.result.records
          this.$set(this.form, 'siteId', siteId)
        }
      })
    },
    /**
     * 获取监测曲线数据
     */
    getHistoryCurve(params) {
      // let params = {
      //   siteId: siteId,
      //   // beginTime: 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')
      // }
      // // if (this.form.date && this.form.date instanceof Array && this.form.date.length > 0) {
      // //   params['beginTime'] = this.$moment(this.form.date[0]).format('YYYY-MM-DD 00:00:00')
      // //   params['endTime'] = this.$moment(this.form.date[1]).format('YYYY-MM-DD 23:59:59')
      // // }
      getHistoryCurve(params).then(res => {
        if (res.code && res.code == 1) {
          if (!res.result || !res.result.list || res.result.list instanceof Array == false) return
          const result = res.result.list[0];
          let target = result.targetVos; // 要展示曲线的指标
          let collectionDates = result.collectionDates.map(item => {
            if (this.radio == 3) return this.$moment(item).format("MM-DD")
            else return this.$moment(item).format("DD HH")
          }); // 选择日期
          this.targetData = target;
          for (let index = 0; index < target.length; index++) {
            const item = target[index];
            const yData = result[item.targetCode + "s"]
            this.$nextTick(() => {
              this.loadChart(index, collectionDates, yData, this.areaColor[index])
            })
          }
          this.loadTable(result)
        }
      })
    },
    /**
     * 查询
     */
    query() {
      let params = {
        siteId: this.form.siteId,
        beginTime: 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')
      }
      this.getHistoryCurve(params)
    },
    /**
     * 加载图表
     */
    loadChart(domIndex, xData, yData, areaColor) {
      let chartDom = document.getElementById('curve-chart' + domIndex);
      let myChart = echarts.init(chartDom);
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        grid: {
          top: '6%',
          left: '3%',
          right: '4%',
          bottom: '2%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: xData
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            type: 'line',
            stack: 'Total',
            smooth: true,
            lineStyle: {
              width: 0
            },
            showSymbol: false,
            label: {
              show: true,
              position: 'top'
            },
            areaStyle: {
              opacity: 0.8,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: areaColor[0]
                },
                {
                  offset: 1,
                  color: areaColor[1]
                }
              ])
            },
            emphasis: {
              focus: 'series'
            },
            data: yData
          }
        ]
      };
      myChart.clear()
      option && myChart.setOption(option);
    },
    /**
     * 加载列表
     */
    loadTable(data) {
      let arr = [];
      data.collectionDates.forEach((item, index) => {
        arr.push({ serialnum: (index + 1) });
        data.targetVos.forEach((item1, index1) => {
          let columnName = item1.targetCode + "s";
          let columnVal = data[columnName];
          arr[index][columnName] = columnVal[index] ? columnVal[index] : '/'
        });
        arr[index]["collectionDates"] = item;
      });
      this.tableData = arr
    },
    /**
     * 获取近7天时间区间
     */
    getSevenDate() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [
        this.$moment(start).format('YYYY-MM-DD 00:00:00'),
        this.$moment(end).format('YYYY-MM-DD 23:59:59')
      ]
    },
  }
}
</script>

<style lang="scss" scoped>
// 覆盖层元素增加可穿透点击事件
.el-dialog__wrapper {
  pointer-events: none;
  overflow: hidden;
  >>> .el-dialog {
    // 弹窗层元素不可穿透点击事件（不影响弹窗层元素的点击事件）
    pointer-events: auto;
    .el-dialog__header {
      background-color: #13479e;
      .el-dialog__title {
        color: #ffffff;
      }
      .el-dialog__close {
        color: #ffffff !important;
      }
    }
  }
  .el-form {
    >>> .el-form-item {
      .el-form-item__label {
        padding: 0;
      }
    }
    >>> .el-date-editor {
      .el-input__icon {
        display: none;
      }
      .el-range-input {
        width: 50%;
      }
    }
  }
  .el-radio {
    margin-right: 4px;
    >>> .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: 180px;
          // background-color: #ccc;
        }
      }
    }
  }
  .el-table {
    >>> th > .cell {
      white-space: pre-line;
    }
    >>> .el-table__body {
      td.el-table__cell {
        height: 38px;
      }
    }
  }
}
</style>