<template>
  <div id="app">
    <el-row :gutter="10">
      <div class="app-container">
        <div class="filter-container" v-if="user.roleName!='企业用户'">
          <el-input
            v-model="queryParams.deviceId"
            :placeholder="$t('设备编号')"
            class="filter-item search-item"
          />
          <el-select v-model="ids" multiple placeholder="请选择企业" class="filter-item search-item">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <!--          <el-input-->
          <!--            v-model="queryParams.companyName"-->
          <!--            :placeholder="$t('企业名称')"-->
          <!--            class="filter-item search-item"-->
          <!--          />-->
          <el-button class="filter-item" type="primary" @click="search">{{
              $t('table.search')
            }}
          </el-button>
          <el-button class="filter-item" type="success" @click="reset">{{
              $t('table.reset')
            }}
          </el-button>
        </div>
        <el-table
          ref="table"
          :row-class-name="tableRowClassName"
          v-loading="loading"
          :data="monitordata"
          border
          fit
          style="width: 100%"
          @sort-change="sortChange"
        >
          <!--          <el-table-column type="expand">
                      <template>
                        <el-table :data="liveData" class="two-list">
                          &lt;!&ndash; <el-table-column type="selection" width="55"></el-table-column> &ndash;&gt;
                          <el-table-column
                            prop="sensorId"
                            label="传感器编号"
                          ></el-table-column>
                          <el-table-column
                            prop="sensorName"
                            label="传感器名称"
                          ></el-table-column>
                          <el-table-column
                            prop="dataValue"
                            label="数值"
                          >
                            <template slot-scope="scope">
                              {{ scope.row.dataValue  | rounding }}
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="reportTime"
                            label="上报时间"
                          ></el-table-column>
                          <el-table-column
                            prop="lowValue"
                            label="安全低值"
                          ></el-table-column>
                          <el-table-column
                            prop="highValue"
                            label="安全高值"
                          ></el-table-column>
                          &lt;!&ndash; <el-table-column></el-table-column>
                          <el-table-column></el-table-column> &ndash;&gt;
                          <el-table-column label="操作">
                            <template slot-scope="scope">
                              <el-button
                                @click="getHistoryData(scope.row)"
                                type="text"
                                size="small"
                              >历史数据
                              </el-button
                              >
                            </template>
                          </el-table-column>
                        </el-table>
                      </template>
                    </el-table-column>-->
          <el-table-column
            label="企业名称"
            prop="companyName"
            align="center"
            min-width="100px"
            v-if="user.roleName!='企业用户'"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.companyName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="设备编号"
            prop="deviceId"
            align="center"
            min-width="100px"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.deviceId }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="设备名称"
            prop="deviceName"
            align="center"
            min-width="100px"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.deviceName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="传感器编号"
            prop="sensorId"
            align="center"
            min-width="80px"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.sensorId }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="传感器名称"
            prop="sensorName"
            align="center"
            min-width="100px"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.sensorName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="数值"
            prop="dataValue"
            align="center"
            min-width="80px"
          >
            <template slot-scope="scope">
              <span> {{ scope.row.dataValue  | rounding }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="单位"
            prop="sensorUnit"
            align="center"
            min-width="60px"
          >
            <template slot-scope="scope">
              <span> {{ scope.row.sensorUnit }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="上报时间"
            prop="reportTime"
            align="center"
            min-width="130px"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.reportTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="安全低值"
            prop="lowValue"
            align="center"
            min-width="100px"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.lowValue }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="安全高值"
            prop="highValue"
            align="center"
            min-width="100px"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.highValue }}</span>
            </template>
          </el-table-column>
          <el-table-column label="最后一次报警时间" align="center" min-width="120px">
            <template slot-scope="scope">
              <span>{{ scope.row.alarmTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="告警级别"
            align="center"
            min-width="100px"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.alarmLevel }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="告警原因"
            align="center"
            min-width="80px"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.reason }}</span>
            </template>
          </el-table-column>
          <el-table-column label="历史数据">
            <template slot-scope="scope">
              <el-button
                @click="getHistoryData(scope.row)"
                type="text"
                size="small"
              >查看
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="pagination.num"
          :limit.sync="pagination.size"
          @pagination="search"
        />
      </div>
    </el-row>
    <el-dialog
      title="查看传感器历史数据"
      :visible.sync="historyDataVisible"
      width="90%"
      @open="drawHistoryChart"
      @close="closedFun"
    >
      <div class="filter-container">
        <el-date-picker
          v-model="dateValue"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          @change="dateChange"
        >
        </el-date-picker>
        <el-button
          class="filter-item"
          type="primary"
          @click="drawHistoryChart"
        >{{ $t('table.search') }}
        </el-button
        >
        <div style="width: 100%; display: flex; justify-content: flex-end">
          <el-switch
            v-model="switchValue"
            inactive-text="显示异常值"
            @change="handleSwitchChange"
          >
          </el-switch>
        </div>
      </div>
      <el-row>
        <el-col>
          <div class="app-container">
            <div id="sensorChart" style="width: 90%; height: 500px" />
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import echarts from 'echarts'

export default {
  components: { Pagination },
  data() {
    return {
      buttonLoading: false,
      monitordata: null,
      liveData: null,
      selectedSensorRow: null,
      historyData: null,
      dateValue: null,
      loading: false,
      deviceId_history: null,
      historyDataVisible: false,
      sensorChart: null,
      total: 0,
      switchValue: false,
      queryParams: {},
      sort: {},
      options: [],
      ids: [],
      intervalId: null,
      expandKeys: [],
      pagination: {
        size: 10,
        num: 1
      }
    }
  },
  computed: {
    user() {
      return this.$store.state.account.user
    }
  },
  created() {

  },
  mounted() {
    // this.initCharts()
    this.fetch1()
    this.dataRefreh()

  },
  destroyed() {
    // 在页面销毁后，清除计时器
    this.clear()
  },
  methods: {
    tableRowClassName(val) {
      console.log(val.row.dataValue)
      if (val.row.dataValue < val.row.lowValue || val.row.dataValue > val.row.highValue) {
        return 'warning-row'
      }
      return ''
    },
    dateChange(val) {
      this.dateValue = val
    },
    handleSwitchChange() {
      this.drawHistoryChart()
    },
    onSelectChange(selection) {
      this.selection = selection
    },
    clearSelections() {
      this.$refs.table.clearSelection()
    },
    sortChange(val) {
      this.sort.field = val.prop
      this.sort.order = val.order
      this.search()
    },
    reset() {
      this.queryParams = {}
      this.sort = {}
      this.search()
    },
    search() {
      // this.resetForm()
      this.queryParams.id = this.ids
      this.fetch1({
        ...this.queryParams,
        ...this.sort
      })
    },
    fetch1(params = {}) {
      this.loading = true
      params.pageSize = this.pagination.size
      params.pageNum = this.pagination.num
      this.$get('/demp/info/alarmEvent/getDeviceInfoAndAlarmEvent', { ...params }).then((r) => {
        this.monitordata = r.data.data.rows
        this.total = r.data.data.total
        this.loading = false
      })
      this.$get('/demp/info/deviceInfo/getCompanys').then((r) => {
        this.options = r.data.data
        // console.log(r.data.data)
      })
    },
    closedFun() {
      this.historyDataVisible = false
      this.sensorChart = null
    },
    // 定时刷新数据函数
    dataRefreh() {
      // 计时器正在进行中，退出函数
      if (this.intervalId != null) {
        return
      }
      // 计时器为空，操作 10秒刷新一次
      this.intervalId = setInterval(() => {
        this.search()
      }, 1000 * 20)
    },
    // 停止定时器
    clear() {
      clearInterval(this.intervalId) //清除计时器
      this.intervalId = null //设置为null
    },
    // expandChange(row, expandedRows) {
    //   if (this.expandKeys.indexOf(row.deviceId) >= 0) {
    //     this.expandKeys.shift()
    //     return
    //   }
    //   this.loading = true
    //   this.liveData = []
    //   const deviceId = row.deviceId
    //   this.deviceId_history = deviceId
    //   this.$get('/demp/data/exchange/liveData/getLiveData', { deviceId }).then(
    //     (r) => {
    //       this.liveData = r.data.data
    //       this.loading = false
    //       this.expandKeys.shift()
    //       this.expandKeys.push(deviceId)
    //     }
    //   )
    // },
    getHistoryData(row) {
      this.dateValue = null
      this.queryParams = {}
      this.selectedSensorRow = row
      this.historyDataVisible = true
    },
    drawHistoryChart() {
      this.$nextTick(() => {
        if (this.dateValue) {
          this.queryParams.startTimeFrom = this.dateValue[0]
          this.queryParams.startTimeTo = this.dateValue[1]
        }
        this.queryParams.deviceId = this.deviceId_history
        this.queryParams.sensorId = this.selectedSensorRow.sensorId
        this.queryParams.switchValue = this.switchValue
        this.$post('/demp/data/exchange/historyData/getHistoryData', {
          ...this.queryParams
        }).then((r) => {
          console.log(r.data.data)
          this.historyData = r.data.data
          this.initCharts()
        })
      })
    },
    initCharts() {
      this.sensorChart = echarts.init(document.getElementById('sensorChart'))

      const option1 = {
        backgroundColor: '#FFF',
        title: {
          text: this.selectedSensorRow.sensorName,
          textStyle: {
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        visualMap: {
          //区间内控制显示颜色
          top: 10,
          right: 10,
          show: true,
          dimension: 1,
          pieces: [
            {
              min: this.selectedSensorRow.lowValue,
              max: this.selectedSensorRow.highValue,
              color: 'rgba(0, 143, 251, 0.8)'
            }
          ],
          outOfRange: {
            symbol: 'rect',
            symbolSize: [10, 10],
            color: 'red'
          },
          precision: 2
        },
        legend: {
          data: [this.selectedSensorRow.sensorName],
          top: '25'
        },
        grid: {
          left: '5%',
          right: '3%',
          bottom: '0.5%',
          containLabel: true,
          show: false
        },
        toolbox: {
          feature: {
            dataView: { show: false, readOnly: false }
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: true,
          splitLine: {
            show: false
          },
          data: this.historyData.reportTime,
          axisLine: {
            lineStyle: {
              color: '#333'
            }
          },
          axisLabel: {
            interval: 0,
            rotate: 48
          }
        },
        yAxis: [
          {
            type: 'value',
            splitLine: {
              lineStyle: {
                type: 'dashed',
                color: '#DDD'
              }
            },
            axisLine: {
              show: false,
              lineStyle: {
                color: '#333'
              }
            },
            nameTextStyle: {
              color: '#999'
            },
            splitArea: {
              show: false
            }
          }
        ],
        series: [
          {
            name: this.selectedSensorRow.sensorName,
            smooth: true,
            type: 'line',
            color: 'rgb(0, 143, 251)',
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(0, 143, 251, 0.8)'
                  },
                  {
                    offset: 1,
                    color: '#fff'
                  }
                ],
                globalCoord: false
              }
            },
            lineStyle: {
              normal: {
                width: 3
              }
            },
            data: this.historyData.dataValue,
            markLine: {
              symbol: 'none',
              data: [
                {
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: 'solid',
                    color: '#2f73d8'
                  },
                  label: {
                    position: 'end',
                    formatter: this.historyData.thresholds[0].code + '低值',
                    fontSize: '10'
                  },
                  yAxis: this.historyData.thresholds[0].lowValue // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                },
                {
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: 'solid',
                    color: '#2f73d8'
                  },
                  label: {
                    position: 'end',
                    formatter: this.historyData.thresholds[0].code + '高值',
                    fontSize: '10'
                  },
                  yAxis: this.historyData.thresholds[0].highValue // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                },
                {
                  silent: false, // 鼠标悬停事件  true没有，false有
                  lineStyle: {
                    // 警戒线的样式  ，虚实  颜色
                    type: 'solid',
                    color: '#ffd200'
                  },
                  label: {
                    position: 'end',
                    formatter: this.historyData.thresholds[1].code + '低值',
                    fontSize: '10'
                  },
                  yAxis: this.historyData.thresholds[1].lowValue // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                },
                {
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: 'solid',
                    color: '#ffd200'
                  },
                  label: {
                    position: 'end',
                    formatter: this.historyData.thresholds[1].code + '高值',
                    fontSize: '10'
                  },
                  yAxis: this.historyData.thresholds[1].highValue // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                },
                {
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: 'solid',
                    color: '#ff6600'
                  },
                  label: {
                    position: 'end',
                    formatter: this.historyData.thresholds[2].code + '低值',
                    fontSize: '10'
                  },
                  yAxis: this.historyData.thresholds[2].lowValue // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                },
                {
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: 'solid',
                    color: '#ff6600'
                  },
                  label: {
                    position: 'end',
                    formatter: this.historyData.thresholds[2].code + '高值',
                    fontSize: '10'
                  },
                  yAxis: this.historyData.thresholds[2].highValue // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                },
                {
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: 'solid',
                    color: '#f00000'
                  },
                  label: {
                    position: 'end',
                    formatter: this.historyData.thresholds[3].code + '低值',
                    fontSize: '10'
                  },
                  yAxis: this.historyData.thresholds[3].lowValue // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                },
                {
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: 'solid',
                    color: '#f00000'
                  },
                  label: {
                    position: 'end',
                    formatter: this.historyData.thresholds[3].code + '高值',
                    fontSize: '10'
                  },
                  yAxis: this.historyData.thresholds[3].highValue // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                },
                {
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: 'solid',
                    color: '#f00000'
                  },
                  label: {
                    position: 'end',
                    formatter: this.historyData.thresholds[4].code + '低值',
                    fontSize: '10'
                  },
                  yAxis: this.historyData.thresholds[4].lowValue // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                },
                {
                  silent: false, //鼠标悬停事件  true没有，false有
                  lineStyle: {
                    //警戒线的样式  ，虚实  颜色
                    type: 'solid',
                    color: '#f00000'
                  },
                  label: {
                    position: 'end',
                    formatter: this.historyData.thresholds[4].code + '高值',
                    fontSize: '10'
                  },
                  yAxis: this.historyData.thresholds[4].highValue // 警戒线的标注值，可以有多个yAxis,多条警示线   或者采用   {type : 'average', name: '平均值'}，type值有  max  min  average，分为最大，最小，平均值
                }
              ]
            }
          }
        ]
      }
      this.sensorChart.setOption(option1)
    }
  },
  filters: {
    rounding(value) {
      return parseFloat(value).toFixed(2)
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  margin: 0 0 10px 0 !important;
}

.warning {
  background: #ecf5ff !important;
}

.double {
  background: #f6f6f6 !important;
}

.single {
  background: #ccc !important;
}

</style>
<style>
.el-table .warning-row {
  background: #FFA500;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
