<template>
  <div class="main">
    <el-card>
      <span class="show-text">设备:</span>
      <el-select v-model="clickOpName" filterable placeholder="请选择设备" style="width: 200px;margin-right: 10px">
        <el-option v-for="item in OpNameList" :key="item.value" :label="item.label" :value="item.value" size="mini" />
      </el-select>
      <el-tabs v-model="activeName" style="margin-top: 10px" type="card" @tab-click="handleClick">
        <el-tab-pane label="压力" name="active1">
          <div class="selectFilter">
            <div class="item">
              <el-select v-model="clickItemList" filterable multiple collapse-tags placeholder="查询类型"
                style="width: 400px;margin-right: 10px">
                <el-option v-for="item in selectItemList" :key="item" :label="item" :value="item" size="mini" />
              </el-select>

              <el-date-picker v-model="collectionTime" :clearable="false" :default-time="['00:00:00', '23:59:59']"
                end-placeholder="结束日期" format="yyyy-MM-dd HH:mm:ss" popper-class="virtual-cell-time-picker"
                range-separator="-" start-placeholder="开始日期" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" />
              <el-button icon="el-icon-search" plain type="primary" @click="searchTableData()">查询</el-button>
              <el-checkbox v-model="isAutoGetData">近期实时数据</el-checkbox>
            </div>
          </div>
          <div id="echarts1" style="width: 60vw;height: 35vh" />
          <div class="bottom">
            <el-table v-loading="loading" :data="pagedTableData" border element-loading-background="rgba(0, 0, 0, 0.2)"
              element-loading-spinner="el-icon-loading" element-loading-text="数据加载中" height="35vh" size="mini"
              tooltip-effect="dark">
              <el-table-column align="center" label="序号" :index="indexMethod" type="index" width="80" />
              <el-table-column align="center" label="变量名称">
                <template slot-scope="scope">
                  {{ scope.row.变量名称 }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="值">
                <template slot-scope="scope">
                  {{ scope.row.值 }}
                </template>
              </el-table-column>
              <el-table-column :width="setColumnWidth('datetime')" align="center" label="采集时间">
                <template slot-scope="scope">
                  {{ scope.row.创建时间 }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-pagination v-if="tableData.length > pageSize" style="margin-top: 10px;" background
            :current-page.sync="currentPage" :page-size="pageSize" :total="tableData.length"
            layout="total, prev, pager, next, jumper" @current-change="handlePageChange" />
        </el-tab-pane>
        <el-tab-pane label="流量" name="active2">
          <div class="selectFilter">
            <div class="item">
              <el-select v-model="clickItemList" filterable multiple collapse-tags placeholder="查询类型"
                style="width: 400px;margin-right: 10px">
                <el-option v-for="item in selectItemList" :key="item" :label="item" :value="item" size="mini" />
              </el-select>

              <el-date-picker v-model="collectionTime" :clearable="false" :default-time="['00:00:00', '23:59:59']"
                end-placeholder="结束日期" format="yyyy-MM-dd HH:mm:ss" popper-class="virtual-cell-time-picker"
                range-separator="-" start-placeholder="开始日期" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" />
              <el-button icon="el-icon-search" plain type="primary" @click="searchTableData()">查询</el-button>
              <el-checkbox v-model="isAutoGetData">近期实时数据</el-checkbox>

            </div>
          </div>
          <div id="echarts2" style="width: 60vw;height: 35vh" />
          <div class="bottom">
            <el-table v-loading="loading" :data="pagedTableData" border element-loading-background="rgba(0, 0, 0, 0.2)"
              element-loading-spinner="el-icon-loading" element-loading-text="数据加载中" height="35vh" size="mini"
              tooltip-effect="dark">
              <el-table-column align="center" label="序号" :index="indexMethod" type="index" width="80" />
              <el-table-column align="center" label="变量名称">
                <template slot-scope="scope">
                  {{ scope.row.变量名称 }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="值">
                <template slot-scope="scope">
                  {{ scope.row.值 }}
                </template>
              </el-table-column>
              <el-table-column :width="setColumnWidth('datetime')" align="center" label="采集时间">
                <template slot-scope="scope">
                  {{ scope.row.创建时间 }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-pagination v-if="tableData.length > pageSize" style="margin-top: 10px;" background
            :current-page.sync="currentPage" :page-size="pageSize" :total="tableData.length"
            layout="total, prev, pager, next, jumper" @current-change="handlePageChange" />
        </el-tab-pane>
        <el-tab-pane label="温度" name="active3">
          <div class="selectFilter">
            <div class="item">
              <el-select v-model="clickItemList" filterable multiple collapse-tags placeholder="查询类型"
                style="width: 400px;margin-right: 10px">
                <el-option v-for="item in selectItemList" :key="item" :label="item" :value="item" size="mini" />
              </el-select>

              <el-date-picker v-model="collectionTime" :clearable="false" :default-time="['00:00:00', '23:59:59']"
                end-placeholder="结束日期" format="yyyy-MM-dd HH:mm:ss" popper-class="virtual-cell-time-picker"
                range-separator="-" start-placeholder="开始日期" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" />
              <el-button icon="el-icon-search" plain type="primary" @click="searchTableData()">查询</el-button>
              <el-checkbox v-model="isAutoGetData">近期实时数据</el-checkbox>

            </div>
          </div>
          <div id="echarts3" style="width: 60vw;height: 35vh" />
          <div class="bottom">
            <el-table v-loading="loading" :data="pagedTableData" border element-loading-background="rgba(0, 0, 0, 0.2)"
              element-loading-spinner="el-icon-loading" element-loading-text="数据加载中" height="35vh" size="mini"
              tooltip-effect="dark">
              <el-table-column align="center" label="序号" :index="indexMethod" type="index" width="80" />
              <el-table-column align="center" label="变量名称">
                <template slot-scope="scope">
                  {{ scope.row.变量名称 }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="值">
                <template slot-scope="scope">
                  {{ scope.row.值 }}
                </template>
              </el-table-column>
              <el-table-column :width="setColumnWidth('datetime')" align="center" label="采集时间">
                <template slot-scope="scope">
                  {{ scope.row.创建时间 }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-pagination v-if="tableData.length > pageSize" style="margin-top: 10px;" background
            :current-page.sync="currentPage" :page-size="pageSize" :total="tableData.length"
            layout="total, prev, pager, next, jumper" @current-change="handlePageChange" />
        </el-tab-pane>
        <el-tab-pane label="浓度" name="active4">
          <div class="selectFilter">
            <div class="item">
              <el-select v-model="clickItemList" filterable multiple collapse-tags placeholder="查询类型"
                style="width: 400px;margin-right: 10px">
                <el-option v-for="item in selectItemList" :key="item" :label="item" :value="item" size="mini" />
              </el-select>

              <el-date-picker v-model="collectionTime" :clearable="false" :default-time="['00:00:00', '23:59:59']"
                end-placeholder="结束日期" format="yyyy-MM-dd HH:mm:ss" popper-class="virtual-cell-time-picker"
                range-separator="-" start-placeholder="开始日期" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" />
              <el-button icon="el-icon-search" plain type="primary" @click="searchTableData()">查询</el-button>
              <el-checkbox v-model="isAutoGetData">近期实时数据</el-checkbox>

            </div>
          </div>
          <div id="echarts4" style="width: 60vw;height: 35vh" />
          <div class="bottom">
            <el-table v-loading="loading" :data="pagedTableData" border element-loading-background="rgba(0, 0, 0, 0.2)"
              element-loading-spinner="el-icon-loading" element-loading-text="数据加载中" height="35vh" size="mini"
              tooltip-effect="dark">
              <el-table-column align="center" label="序号" :index="indexMethod" type="index" width="80" />
              <el-table-column align="center" label="变量名称">
                <template slot-scope="scope">
                  {{ scope.row.变量名称 }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="值">
                <template slot-scope="scope">
                  {{ scope.row.值 }}
                </template>
              </el-table-column>
              <el-table-column :width="setColumnWidth('datetime')" align="center" label="采集时间">
                <template slot-scope="scope">
                  {{ scope.row.创建时间 }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-pagination v-if="tableData.length > pageSize" style="margin-top: 10px;" background
            :current-page.sync="currentPage" :page-size="pageSize" :total="tableData.length"
            layout="total, prev, pager, next, jumper" @current-change="handlePageChange" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  data() {
    return {
      clickOpName: '',
      OpName: '',
      selectItem: '',

      clickItemList: [],
      selectItemList: [],
      collectionTime: [],
      tableData: [],
      OpNameList: [],
      opStatusList: ['关机', '待机', '运行', '报警', '暂停'],
      loading: false,
      activeName: 'active1',
      isAutoGetData: false,
      timer1: null,
      // 分页相关
      currentPage: 1,
      pageSize: 1000,
    }
  },
  computed: {
    // 计算当前页的表格数据
    pagedTableData() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.tableData.slice(start, end)
    }
  },
  created() {
    let that = this
    var now = new Date()
    var start = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes() - 1, now.getSeconds())).toISOString().replace('T', ' ').replace('.000Z', '')
    var end = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)).toISOString().replace('T', ' ').replace('.000Z', '')
    this.collectionTime = [start, end]
    this.getOpName()
    this.timer1 = setInterval(() => {
      if (that.isAutoGetData) {
        let now = new Date()
        let start2 = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes() - 1, now.getSeconds())).toISOString().replace('T', ' ').replace('.000Z', '')
        let end2 = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds())).toISOString().replace('T', ' ').replace('.000Z', '')
        console.log(start2, end2)
        that.collectionTime = [start2, end2]
        that.searchTableData()
      }
    }, 1000 * 3)
  },

  // 关闭页面 删除定时器
  beforeDestroy() {
    clearInterval(this.timer1)
  },

  methods: {
    // 查询工位号
    getOpName() {
      var param = []
      param.push(['Personnel_Number', this.$store.state.user.id])
      var Data = this.CreateData('11', '工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        this.OpNameList = []
        for (const item of response.data) {
          this.OpNameList.push({ label: item.公司 + item.工位号, value: item.工位号 })
        }
        if (this.OpNameList.length > 0) {
          this.clickOpName = this.OpNameList[0].value
        }
        this.handleClick()
      })
    },
    // 读取工位点位
    searchTableData() {
      var param = []
      param[0] = ['设备名称', this.clickOpName]
      param[1] = ['变量名称', JSON.stringify(this.clickItemList)]
      param.push(['开始时间', this.collectionTime[0]])
      param.push(['结束时间', this.collectionTime[1]])

      var Data = this.CreateData('11', 'WEB_实时分析曲线_变量_查询', param)
      this.ExecDatabase(Data).then(response => {
        this.tableData = []
        if (response.data.length !== 0) {
          this.tableData = JSON.parse(JSON.stringify(response.data))
        }
        this.currentPage = 1 // 查询后重置分页到第一页
        this.showEcharts(response.data)
      })
    },
    // 绘制图表
    showEcharts(tableData) {
      // 将时间字符串转换为时间戳，并按时间排序
      tableData.forEach(item => {
        item.time = new Date(item.创建时间).getTime()
      })
      tableData.sort((a, b) => a.time - b.time)

      const seriesList = []
      for (const item of this.clickItemList) {
        const seriesData = tableData.filter(item2 => item2.变量名称 === item).map(item => [item.创建时间, item.值])
        const isLargeData = seriesData.length > 10000
        seriesList.push({
          name: item,
          type: 'line',
          smooth: true,
          showSymbol: !isLargeData, // 大数据量时隐藏数据点符号
          large: isLargeData, // 大数据量优化模式
          largeThreshold: 10000, // 触发大数据量模式的阈值
          sampling: isLargeData ? 'lttb' : null, // 使用LTTB降采样算法保留趋势
          data: seriesData,
          lineStyle: {
            width: isLargeData ? 1 : 2 // 大数据量时使用更细的线条
          },
          itemStyle: {
            normal: {
              borderWidth: 2
            }
          }
        })
      }

      const config = {
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            let tooltipText = '';
            params.forEach(function (param) {
              if (param.value) {
                const createTime = new Date(param.value[0]).toLocaleString();
                const variableName = param.seriesName.replace('³', '3');
                const value = param.value[1];
                tooltipText += `${createTime}<br>${variableName}: ${value}<br>`;
              }
            });
            return tooltipText;
          }
        },
        legend: {
          data: this.clickItemList
        },
        xAxis: {
          type: 'time',
          splitLine: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          min: this.activeName === 'active4' ? 80 : null,
          max: this.activeName === 'active4' ? 100 : null
        },
        series: seriesList
      }

      if (this.activeName === 'active1') {
        const doc1 = echarts.init(document.getElementById('echarts1'))
        doc1.setOption(config)
      }
      if (this.activeName === 'active2') {
        const doc2 = echarts.init(document.getElementById('echarts2'))
        doc2.setOption(config)
      }
      if (this.activeName === 'active3') {
        const doc3 = echarts.init(document.getElementById('echarts3'))
        doc3.setOption(config)
      }
      if (this.activeName === 'active4') {
        const doc4 = echarts.init(document.getElementById('echarts4'))
        doc4.setOption(config)
      }
    },
    handleClick() {
      let keyName = ''
      if (this.activeName === 'active1') keyName = '压力'
      if (this.activeName === 'active2') keyName = '流量'
      if (this.activeName === 'active3') keyName = '温度'
      if (this.activeName === 'active4') keyName = '浓度'
      var param = []
      param[0] = ['设备名称', this.clickOpName]
      param[1] = ['keyName', keyName]
      var Data = this.CreateData('11', 'WEB_实时分析曲线_测量项目_查询', param)
      this.ExecDatabase(Data).then(response => {
        this.clickItemList = []
        this.selectItemList = []
        if (response.data.length !== 0) {
          for (const item of response.data) {
            this.selectItemList.push(item.变量名称)
          }
          if (this.selectItemList.length > 0) {
            this.clickItemList.push(this.selectItemList[0])
            this.searchTableData()
          }
        }
      })
    },
    // 分页切换
    handlePageChange(page) {
      this.currentPage = page
    },
    // 表格序号计算（跨页连续）
    indexMethod(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1
    }
  }
}
</script>

<style lang="scss" scoped>
.bottom {
  display: flex;
  width: 60%;
}

/* 整个滚动条 */
.opList::-webkit-scrollbar {
  width: 8px;
  height: 12px;
}

/* 滚动条里面滑块 */
.opList::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: skyblue;
}

/*滚动条里面轨道*/
.opList::-webkit-scrollbar-track {
  border-radius: 10px;
  box-shadow: inset 0 0 1px rgba(0, 0, 0, 0.2);
  background: #eee;
}

.opList {
  display: flex;
  overflow-y: hidden;
  overflow-x: auto;
  width: 100%;
  margin: 10px 0;

  .item {
    flex: 1;
    min-width: 200px;
    height: 90px;
    border: 1px solid #234f7c;
    margin: 10px 5px;
    background-color: #fff;
  }
}

.configTop {
  display: flex;

  .item {
    margin: 0 5px;
  }
}

.vdr-main {
  height: 750px;
  width: 1600px;
  border: 1px solid red;
  overflow: hidden;

  .vdr-Parent {
    position: relative;
    cursor: move;
    user-select: none;
  }
}
</style>
