<template>
  <div class="realtime-line">
    <div style="width: 100%;height: 100%;">
      <el-carousel indicator-position="outside" :interval="30000" height="95%" arrow="never">
        <el-carousel-item v-for="(item, index) in Math.ceil(Object.keys(workshopList).length / (x * y))" :key="index">
          <div style="display: flex;flex-wrap: wrap;height: 100%">
            <div
              v-loading="chartLoading"
              class="chart-box"
              :class="indexkey % x === 0 ? 'row-first-chart' : ''"
              v-for="(key, indexkey) in Object.keys(workshopList).slice(index * x * y , (index + 1) * x * y)"
              :key="key"
              :style="chartBoxStyle"
            >
              <div class="chart-box-title"> {{ (workshopList[key].remark || '') + workshopList[key].workshopName }}</div>
<!--              <div class="chart-box-title">{{ workshopList[key].workshopName }}</div>-->
              <div class="chart-box-content">
                <div :id="key" style="height: 100%;"/>
              </div>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>
    <!--<div
      v-loading="chartLoading"
      class="chart-box"
      :class="index % x === 0 ? 'row-first-chart' : ''"
      v-for="(key, index) in Object.keys(workshopList)"
      :key="key"
      :style="chartBoxStyle"
    >
      <div class="chart-box-title">{{ workshopList[key].workshopName }}</div>
      <div class="chart-box-content">
        <div :id="key" style="height: 100%"/>
      </div>
    </div>-->
  </div>
</template>

<script>
import { historyChartAllData } from '@/api/HistoryData'
import { findByAcquisitionStationId } from '@/api/Workshop'
import { findYMax } from '@/api/DashboardLayout'
import moment from 'moment'
import { mapState } from 'vuex'

export default {
  name: 'RealtimeLine',
  data() {
    return {
      chartLoading: true,
      workshopList: {},
      timeList: [],
      chartData: {},
      chartList: {},
      initCompleted: false,
      canUpdate: true,
      yMaxMap: {},
    }
  },
  computed: {
    ...mapState({
      realtimeDataMap: (state, getter) => state.queue.realtimeDataMap,
      lastTime: (state, getter) => state.queue.lastTime,
      acquisitionStation: state => state.company.acquisitionStation,
      x: state => state.company.acquisitionStation.xQuantity,
      y: state => state.company.acquisitionStation.yQuantity,
    }),
    chartBoxStyle() {
      const baseX = this.x === 1 ? 99 : 90
      const baseY = this.y === 1 ? 99 : 90
      const baseMargin = this.x === 1 ? 10000 : 3

      return {
        width: baseX / this.x + '%',
        height: baseY / this.y + '%',
        marginLeft: baseMargin / (this.x - 1) + '%',
      }
    },
  },
  watch: {
    lastTime() {
      if (this.initCompleted && this.canUpdate) {
        this.updateChart()
      }
    },
    async workshopList(newVal) {
      // console.log('newVal', newVal)
      if (newVal) {
        this.$nextTick(() => {
          this.chartLoading = false
          for (const key in this.chartList) {
            window.removeEventListener('resize', this.chartList[key].resize)
            this.chartList[key].dispose()
            this.chartList[key] = null
          }
          this.chartList = {}
          for (const key in this.workshopList) {
            this.chartList[key] = this.$echarts.init(document.getElementById(key))

            const tagList = this.workshopList[key].tagList
            const legendData = tagList.map(e => this.getLegendName(this.workshopList[key].workshopName, e.name))
            let startType = 'UNKNOWN'
            tagList.forEach(e => {
              if (e.tableColumn === this.workshopList[key].collectEntityList[0].startType) {
                startType = e.desc
              }
            })
            const collectEntityId = this.workshopList[key].collectEntityList[0].id
            const legendSelected = {}
            legendData.forEach(e => {
              legendSelected[e] = e === startType
            })
            const options = {
              legend: {
                right: '4%',
                left: '20%',
                icon: 'roundRect',
                textStyle: {
                  fontSize: 12,
                  color: '#FFFFFF',
                },
                data: legendData,
                selected: legendSelected,
              },
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'cross',
                  label: {
                    backgroundColor: '#6a7985'
                  }
                }
              },
              grid: {
                top: '15%',
                left: '5%',
                right: '10%',
                bottom: '3%',
                containLabel: true
              },
              xAxis: {
                type: 'category',
                boundaryGap: false,
                data: [],
                axisTick: {
                  show: false
                },
                axisLine: {
                  show: true,
                  lineStyle: {
                    width: 2,
                    color: '#FFF',
                  }
                },
                axisLabel: { //y轴文字的配置
                  color: '#FFF', //Y轴内容文字颜色
                },
              },
              yAxis: {
                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: false,
                  lineStyle: {
                    width: 2,
                    color: {
                      x: 1,
                      y: 1,
                      colorStops: [{
                        offset: 1,
                        color: '#AAA7A7' // 100% 处的颜色
                      }, {
                        offset: 0,
                        color: '#FFFFFF' // 0% 处的颜色
                      }]
                    },
                  },
                },
                axisLabel: { //y轴文字的配置
                  color: '#FFF', //Y轴内容文字颜色
                },
                max: this.yMaxMap[collectEntityId]
              },
              series: []
            }
            for (const e of tagList) {
              const name = this.getLegendName(this.workshopList[key].workshopName, e.name)
              options.series.push(
                {
                  name,
                  color: this.getLineColor(name),
                  type: 'line',
                  smooth: true,
                  symbol: 'none',
                  connectNulls: true,
                  data: [],
                  markLine: {
                    symbol: ['none', 'none'],
                    data: [
                      {
                        name: '告警线',
                        yAxis: e.warnMaxValue
                      },
                    ],
                    lineStyle: {
                      type: 'solid',
                      color: '#ef0505',
                    },
                    animation: false,
                  }
                }
              )
            }
            this.chartList[key].setOption(options)
            window.addEventListener('resize', this.chartList[key].resize)
          }
          this.fetchData()
        })
      }
    },
  },
  /*mounted () {
    console.log('======================' + Object.keys(this.workshopList).length)
  },*/
  methods: {
    async initData() {
      this.initCompleted = false
      await findYMax().then(res => {
        if (res && res.code === '200') {
          const yMaxMap = {}
          res.data.forEach(e => {
            yMaxMap[e.collectEntityId] = e.yMax
          })
          this.yMaxMap = yMaxMap
        }
      })
      await findByAcquisitionStationId({ acquisitionStationId: this.acquisitionStation.id }).then(res => {
        if (res && res.code === '200') {
          const obj = {}
          const arrNotTags = []
          res.data.forEach((val, index) => {
            if (val.tagList && val.tagList.length > 0) {
              // 过滤运行反馈
              val.tagList = val.tagList.filter(e => !e.code.endsWith('FEEDBACK'))
              obj[val.workshopCode] = val
            } else {
              arrNotTags.push(val)
            }
          })
          this.workshopList = obj
          for (const item of arrNotTags) {
            this.$message.warning(item.workshopName + '未配置标签或者标签未启用!!!')
          }
        }
      })
    },
    async fetchData() {
      const params = {
        start: moment().subtract(5, 'minutes').valueOf(),
        end: moment().valueOf(),
        step: 2,
        acquisitionStationId: this.acquisitionStation.id
      }
      await historyChartAllData(params).then(res => {
        if (res && res.code === '200') {
          this.timeList = res.data.timeList
          for (const key in res.data.dataMap) {
            this.chartData[key] = res.data.dataMap[key]
          }
          for (const k in this.workshopList) {
            const options = {
              xAxis: {
                data: this.timeList
              },
              series: []
            }
            for (const a of this.workshopList[k].tagList) {
              options.series.push({ data: this.chartData[a.code] })
            }
            this.chartList[k].setOption(options)
          }
          this.initCompleted = true
        }
      })
    },
    getLineColor(name) {
      const colors = ['#17f107', '#ec0ad5', '#00DDFF', '#f1ca05']
      switch (name) {
        case '电流':
          return colors[0]
        case '振动':
          return colors[1]
        case '噪声':
          return colors[2]
        case '反馈':
          return colors[3]
        default:
          return colors[4]
      }
    },
    getLegendName(prefix, name) {
      if (name.lastIndexOf(prefix) !== -1) {
        return name.split(prefix)[1]
      } else {
        return name
      }
    },
    updateChart() {
      this.canUpdate = false

      this.timeList.push(this.lastTime)
      this.timeList.shift()
      for (const key in this.chartList) {
        const opt = {
          xAxis: {
            data: this.timeList
          },
          series: []
        }
        for (const e of this.workshopList[key].tagList) {
          this.chartData[e.code].shift()
          this.chartData[e.code].push(this.realtimeDataMap[e.code])
          const data = this.chartData[e.code]
          opt.series.push({ data })
        }
        this.chartList[key].setOption(opt)
      }

      try {
      } catch (e) {
        console.error(e)
      } finally {
        this.canUpdate = true
      }
    },
  },
}
</script>

<style lang="less" scoped>
  .realtime-line {
    height: 100%;
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    /*justify-content: flex-start;*/
    align-items: center;

    .chart-row {
      display: flex; /* 使用 flex 布局 */
      height: 100%;
    }
    .chart-box {
      display: flex;
      flex-direction: column;

      .chart-box-title {
        background-color: #0c3048;
        padding: 5px 16px;
      }
      .chart-box-content {
        flex: 1;
        padding-top: 8px;
      }
    }

    .row-first-chart {
      /*margin-left: 0 !important;*/
    }
  }
  .el-carousel {
    height: 100%;
  }
</style>
