<template>
  <div class="realtime-line-modal">
    <el-tabs class="tabs-wrapper" :value="activeName" :before-leave="beforeLeave">
      <el-tab-pane
        v-for="(item, index) in collectEntity.tagList"
        :key="index"
        :label="item.desc + '(' + item.unit + ')'"
        :data="item.tableColumn"
        :name="item.tag">
        <div :id="item.tag" style="height: 100%" />
      </el-tab-pane>
    </el-tabs>
    <div class="jg-btn-group" style="float: right">
      <div :class="activeButton === 0 ? 'btn-active' : ''" class="jg-btn" @click="onClick(0)">X轴长5分钟</div>
      <div :class="activeButton === 1 ? 'btn-active' : ''" class="jg-btn" @click="onClick(1)">X轴长1小时</div>
      <div :class="activeButton === 2 ? 'btn-active' : ''" class="jg-btn" @click="onClick(2)">X轴长2小时</div>
      <div :class="activeButton === 6 ? 'btn-active' : ''" class="jg-btn" @click="onClick(6)">X轴长6小时</div>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { historyChartData } from '@/api/HistoryData'
import { mapState } from 'vuex'

export default {
  name: 'RealtimeLineModal1',
  props: {
    collectEntity: {
      type: Object,
      default: () => {}
    },
  },
  data () {
    return {
      duration6: true,
      chartLoading: false,
      chartData: [],
      timeList: [],
      activeButton: 0,
      durTime: [
        moment().subtract(5, 'minutes').valueOf(),
        moment().valueOf()
      ],
      activeName: '',
      currentChart: null,
      opt: {
        color: ['#c71016', '#37A2FF', '#80FFA5', '#00DDFF', '#FFBF00', '#FF0087'],
        legend: {
          right: '4%',
          icon: 'roundRect',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        grid: {
          top: '8%',
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisTick: {
            show: false
          },
          axisLine: {
            show: true,
            lineStyle: {
              width: 2,
              color: {
                x: 1,
                y: 0,
                colorStops: [{
                  offset: 0,
                  color: '#AAA7A7' // 100% 处的颜色
                }, {
                  offset: 1,
                  color: '#FFFFFF' // 0% 处的颜色
                }]
              },
            }
          },
        },
        yAxis: {
          // name: this.collectEntity,
          type: 'value',
          axisLine: {
            show: true,
            lineStyle: {
              width: 2,
              color: {
                x: 0,
                y: 0,
                colorStops: [{
                  offset: 0,
                  color: '#AAA7A7' // 100% 处的颜色
                }, {
                  offset: 1,
                  color: '#FFFFFF' // 0% 处的颜色
                }]
              },
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              width: 2,
              color: {
                x: 1,
                y: 1,
                colorStops: [{
                  offset: 1,
                  color: '#AAA7A7' // 100% 处的颜色
                }, {
                  offset: 0,
                  color: '#FFFFFF' // 0% 处的颜色
                }]
              },
            },
          },
        },
        series: [{
          type: 'line',
          data: [],
          connectNulls: true,
        }]
      },
    }
  },
  computed: {
    ...mapState({
      realtimeData: (state, getter) => state.queue.realtimeData,
    }),
  },
  watch: {
    realtimeData(newVal) {
      for (const item of newVal) {
        if (item.tag === this.activeName) {
          if (this.chartData.length > 0) {
            this.chartData.push(item.value)
            this.chartData.shift()
          }
        }
      }
      if (this.chartData.length > 0) {
        this.timeList.push(moment(Number(newVal[0].timestamp)).format('YYYY-MM-DD HH:mm:ss'))
        this.timeList.shift()
        this.updateChart()
      }
    },
    collectEntity: {
      handler(newVal) {
        this.activeName = newVal.tagList[0].tag
      },
      immediate: true
    },
  },
  methods: {
    getTableColumn(activeName) {
      for (const item of this.collectEntity.tagList) {
        if (item.tag === activeName) {
          return item.tableColumn.toLowerCase()
        }
      }
    },
    beforeLeave(activeName, oldActiveName) {
      this.activeName = activeName
      this.initData()
    },
    fetchData() {
      this.chartLoading = true
      const params = {
        entityId: this.collectEntity.id,
        start: this.durTime[0],
        end: this.durTime[1],
        step: 2
      }
      historyChartData(params).then(res => {
        if (res && res.code === '200') {
          console.log('historyChartData =>', res, this.collectEntity)
          this.chartData = []
          for (const data of res.data) {
            this.chartData.push(Number(data[this.getTableColumn(this.activeName)]))
          }
          this.currentChart.setOption({
            xAxis: {
              data: res.data.map(e => e.dateTime)
            },
            series: [{
              data: this.chartData
            }]
          })
          this.timeList = res.data.map(e => e.dateTime)
        }
        // console.log('wwwwwwwwwwwww', this.chartList, this.chartData, this.timeList)
      }).finally(() => {
        this.chartLoading = false
      })
    },
    onClick(time) {
      this.activeButton = time
      if (time === 0) {
        this.durTime[0] = moment().subtract(5, 'minutes').valueOf()
      } else {
        this.durTime[0] = moment().subtract(time, 'hours').valueOf()
      }
      this.fetchData()
    },
    updateChart() {
      this.currentChart.setOption({
        xAxis: {
          data: this.timeList
        },
        series: [{
          data: this.chartData
        }]
      })
    },
    initData() {
      if (this.currentChart) {
        window.removeEventListener('resize', this.currentChart.resize)
        this.currentChart.dispose()
        this.currentChart = null
      }
      this.$nextTick(() => {
        this.currentChart = this.$echarts.init(document.getElementById(this.activeName))
        this.currentChart.setOption(this.opt)
        window.addEventListener('resize', this.currentChart.resize)
      })
      this.fetchData()
    },
  },
}
</script>

<style lang="less" scoped>
  .realtime-line-modal {
    height: calc(100% - 8px);
    display: flex;
    flex-direction: column;

    .left-desc {
      width: 140px;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      text-align: center;

      div {
        white-space: pre-line;
        height: 100%;
        line-height: 30px;
        margin: 16px;
        font-size: 20px;
        font-weight: 600;
        box-shadow: 0.1rem 0.1rem 0.1rem #aaa7a7, -0.1rem -0.1rem 0.1rem #FFFFFF;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .right-chart {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      /*justify-content: space-around;*/
    }

    .jg-btn-group {
      display: flex;
      padding: 1px;
      text-align: center;
      margin-top: 32px;
      justify-content: flex-end;

      .jg-btn {
        height: 40px;
        line-height: 40px;
        margin-left: 16px;
        padding: 0 24px;
        cursor: pointer;
        box-sizing: border-box;
        font-size: 16px;
        font-weight: 500;
        border-radius: 8px;
        box-shadow: 0.1rem 0.1rem 0.1rem #aaa7a7, -0.1rem -0.1rem 0.1rem #FFFFFF;
        user-select: none;
      }

      .jg-btn:active {
        color: #FFFFFF;
        background-color: #A20D13;
        box-shadow: inset 0.2rem 0.2rem 0.5rem #6e090c, inset -0.2rem -0.2rem 0.5rem #c71016;
      }

      .btn-active {
        color: #FFFFFF;
        background-color: #A20D13;
        box-shadow: inset 0.2rem 0.2rem 0.5rem #6e090c, inset -0.2rem -0.2rem 0.5rem #c71016;
        pointer-events: none;
        cursor: not-allowed;
      }
    }

    /deep/ .tabs-wrapper {
      height: 100%;
      display: flex;
      flex-direction: column;

      .el-tabs__content {
        height: calc(100% - 210px);
        display: flex;
        flex-direction: column;
        flex: 1;
      }

      .el-tab-pane {
        flex: 1;
        margin-bottom: 0;
      }

      .el-tabs__item {
        padding: 0 24px;
        height: 30px;
        line-height: 30px;
        border-radius: 4px;
      }
    }
  }
</style>
