<template>
  <div style="width: auto; height: 100%;">
    <vue-scroll>
      <div ref="all">
        <el-header class="header-button-box">
          <div class="search-input-box">
            <label>{{$t("Performance.deviceType") + '：'}}</label>
            <el-select size='mini'
                       disabled
                       v-model="deviceTypeKey">
              <el-option
                v-for="item in deviceTypeList"
                :key="item.deviceTypeKey"
                :label="item.deviceTypeName"
                :value="item.deviceTypeKey">
              </el-option>
            </el-select>
          </div>
          <div class="search-input-box">
            <label>{{$t("Performance.deviceModel") + '：'}}</label>
            <el-input size='mini' :placeholder="$t('common.placeholder')"
                      v-model="deviceModel"
                      disabled
                      style="width: 173px">
            </el-input>
          </div>
          <div class="search-input-box">
            <label>{{$t("Performance.deviceName") + '：'}}</label>
            <el-input size='mini' :placeholder="$t('common.placeholder')"
                      v-model="deviceName"
                      disabled
                      style="width: 173px">
            </el-input>
          </div>
          <div class="search-input-box">
            <label>{{$t("Performance.performanceEvent") + '：'}}</label>
            <el-select v-model="performType"
                       size="mini"
                       multiple
                       collapse-tags
                       :multiple-limit=6
                       :disabled="F"
                       @change="queryRtEventChange"
                       :placeholder="$t('common.selectOption')">
              <el-option
                v-for="item in performTypeList"
                :key="item.deviceParam"
                :label="item.peformTypeName"
                :value="item.deviceParam">
              </el-option>
            </el-select>
          </div>
          <div class="search-input-box">
            <label>{{ $t("RtPerformance.devicePort") }}：</label>
            <el-select
              size='mini'
              v-model="queryRtPort"
              :placeholder="$t('common.placeholder')"
              multiple
              :disabled="F"
              collapse-tags
              :multiple-limit=4
            >
              <el-option
                v-for="item in queryRtPortList"
                :key="item.label"
                :label="item.portName"
                :value="item.portName">
              </el-option>
            </el-select>
          </div>
          <div class="search-input-box">
            <label>{{ $t("RtPerformance.refreshRate") }}：</label>
            <el-select
              size='mini'
              v-model="refreshRate"
              :placeholder="$t('common.placeholder')"
              :disabled="F"
            >
              <el-option
                v-for="item in refreshRateList"
                :key="item.label"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="search-input-box">
            <el-button v-if = 'flag' size='mini' icon="el-icon-search" type="primary" @click="getRt()">
              {{ $t("common.look")}}
            </el-button>
            <el-button v-if = '!flag' size='mini' icon="el-icon-search" type="primary" @click="clearRt()">
              {{ $t("common.clear")}}
            </el-button>
          </div>
        </el-header>
        <div ref="containersAll" id="containersAll"></div>
      </div>
    </vue-scroll>
    <RtTable :visibleFlag.sync="visibleFlag"
             :rate="rate"
             :dataList='dataList'>
    </RtTable>
  </div>
</template>
<script>
import RtPerformanceService from '@/domain/services/RtPerformanceService'
import HelperUtil from '@/utils/HelperUtil'
import Echart from 'echarts'
import legitimacyCheck from '../../utils/legitimacyCheck'
import RtTable from '../PerformanceManagement/RtTable'
import DeviceService from '../../domain/services/DeviceService'
export default {
  name: 'RtPerformance',
  data: function () {
    return {
      dataList: [],
      deviceTypeKey: '',
      deviceModel: '',
      deviceName: '',
      performType: [],
      performTypeList: [],
      performTypeList1: {},
      performTypeList2: [],
      queryRtEvent: [],
      queryRtEventList: [],
      queryRtPort: [],
      flag: true,
      F: false,
      visibleFlag: false,
      queryRtPortList: [],
      fullWidth: 300,
      fullHeight: document.body.clientHeight,
      div_id: [],
      echart: [],
      timeEchart: null,
      deviceKey: '',
      returnresult: [],
      refreshRate: 3,
      rate: '',
      deviceTypeList: [],
      refreshRateList: [
        {
          label: '3s',
          value: 3
        },
        {
          label: '5s',
          value: 5
        },
        {
          label: '7s',
          value: 7
        }
      ]
    }
  },
  created () {
    this.getAllDeviceType()
    this.deviceKey = JSON.parse(window.sessionStorage.getItem('dev'))
    this.initFirst()
    // this.getPerformType()
    this.getPerformTypeList()
    this.genArr()
    // this.returnresult = this.getEvent()
    // this.queryRtEventList = this.getEvent()
    // this.queryRtEvent[0] = this.queryRtEventList[0]
  },
  methods: {
    /**
     * @Description  : getAllDeviceType
     * @author       : ls
     * @date         : 2020/11/16 17:03
     * @param        :
     * @return       :
     */
    getAllDeviceType: function () {
      let _this = this
      DeviceService.getAllDeviceTypeCollection().then(result => {
        _this.deviceTypeList = Object.values(result)
      }).catch(err => {
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : getRt
     * @author       : ls
     * @date         : 2020/11/16 17:03
     * @param        :
     * @return       :
     */
    getRt: function () {
      if (this.check()) {
        this.F = true
        this.initDivFirst()
        this.initDiv()
        this.initEchart()
        this.addSeries()
        this.resizeResolve()
        this.loadEchartData1(this.deviceKey, this.performType, this.queryRtPort, this.echart, this)
      }
    },
    getPerformType: function () {
      let _this = this
      RtPerformanceService.getRtEventType().then(result => {
        _this.performTypeList = Object.values(result)
        _this.performTypeList1 = result
      }).catch(err => {
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : getPerformTypeList
     * @author       : ls
     * @date         : 2020/11/23 16:50
     * @param        :
     * @return       :
     */
    getPerformTypeList: function () {
      let _this = this
      RtPerformanceService.getRtPerformType(this.deviceKey).then(result => {
        _this.performTypeList = Object.values(result)
        _this.performTypeList1 = result
      }).catch(err => {
        _this.InfoTip.errorTip(_this, err)
      })
    },
    initFirst: function () {
      this.deviceTypeKey = this.deviceKey.deviceTypeKey
      this.deviceModel = this.deviceKey.deviceModel
      this.deviceName = this.deviceKey.displayName
    },
    genArr: function () {
      let _this = this
      let selectList = []
      selectList.push(
        {
          quaryAttribute: 'deviceKey',
          compareSymbol: '=',
          compareValue: this.deviceKey.deviceKey
        },
        {
          quaryAttribute: 'deviceParam',
          compareSymbol: '=',
          compareValue: 'PORT_NAME'
        }
      )
      DeviceService.getDevicePortStatus(selectList).then(result => {
        _this.queryRtPortList = result
      }).catch(err => {
        _this.InfoTip.errorTip(_this, err)
      })
    },
    clearRt: function () {
      this.flag = true
      this.F = false
      this.clearAll()
    },
    loadEchartData1: function (valDevice, rtData, rtPort, chart, _this) {
      this.rate = parseInt(this.refreshRate) * 1000
      this.flag = false
      var op = []
      var eventPort = new Array(rtData.length)
      for (var k = 0; k < rtData.length; k++) {
        eventPort[k] = new Array(rtPort.length)
      }
      for (var i = 0; i < this.performType.length; i++) {
        op[i] = this.echart[i].getOption()
        // if (this.contains(this.performType[i])) {
        if (this.performTypeList1[this.performType[i]].resourceType === 1) {
          for (var m = 0; m < this.queryRtPort.length; m++) {
            eventPort[i][m] = op[i].series[m].data
          }
        } else {
          eventPort[i] = op[i].series[0].data
        }
      }
      this.timeEchart = setInterval(function () {
        RtPerformanceService.rtPerformDatas(valDevice, rtPort, rtData).then(result => {
          for (var j = 0; j < rtData.length; j++) {
            // if (_this.contains(rtData[j])) {
            if (_this.performTypeList1[_this.performType[j]].resourceType === 1) {
              var portData = []
              for (var n = 0; n < rtPort.length; n++) {
                if (result[j][n][1].indexOf('ERROR') !== -1) {
                  portData.push(
                    {
                      data: []
                    }
                  )
                } else {
                  eventPort[j][n].shift()
                  eventPort[j][n].push(result[j][n])
                  portData.push(
                    {
                      data: eventPort[j][n]
                    }
                  )
                }
              }
              chart[j].setOption({
                series: portData
              })
            } else {
              eventPort[j].shift()
              eventPort[j].push(result[j])
              chart[j].setOption({
                series: {
                  data: eventPort[j]
                }
              })
            }
          }
        }).catch(err => {
          if (_this.timeEchart) {
            clearInterval(_this.timeEchart)
          }
          _this.InfoTip.errorTip(_this, err)
        })
      }, _this.rate)
    },
    addSeries1: function () {
      for (var i = 0; i < this.queryRtEvent.length; i++) {
        var seriesList = []
        if (this.contains(this.queryRtEvent[i])) {
          for (var j = 0; j < this.queryRtPort.length; j++) {
            seriesList.push({
              name: '端口' + this.queryRtPort[j],
              data: this.getData1(),
              type: 'line',
              smooth: true
            })
          }
        } else {
          seriesList.push({
            name: this.queryRtEvent[i],
            type: 'line',
            smooth: 'true',
            data: this.getData1(),
            markLine: {
              silent: true,
              data: [{
                yAxis: 0.3
              }, {
                yAxis: 0.7
              }]
            }
          })
        }
        this.echart[i].setOption({
          series: seriesList,
          legend: {
            left: 'center',
            top: 30
          },
          title: {
            text: this.queryRtEvent[i] + '设备' + this.deviceKey.displayName,
            x: 'center'
          },
          yAxis: {
            name: this.queryRtEvent[i]
          },
          color: ['#7cb5ec', '#434348', '#90ed7d']
        })
      }
    },
    addSeries: function () {
      for (var i = 0; i < this.performType.length; i++) {
        var seriesList = []
        if (this.performTypeList1[this.performType[i]].resourceType === 1) {
          for (var j = 0; j < this.queryRtPort.length; j++) {
            seriesList.push({
              name: this.queryRtPort[j],
              data: this.getData1(),
              type: 'line',
              smooth: true
            })
          }
        } else {
          seriesList.push({
            name: this.performTypeList1[this.performType[i]].peformTypeName,
            type: 'line',
            smooth: 'true',
            data: this.getData1()
            // markLine: {
            //   silent: true,
            //   data: [{
            //     yAxis: 0.3
            //   }, {
            //     yAxis: 0.7
            //   }]
            // }
          })
        }
        this.echart[i].setOption({
          series: seriesList,
          legend: {
            left: 'center',
            top: 30
          },
          title: {
            text: '设备' + this.deviceKey.displayName + this.performTypeList1[this.performType[i]].peformTypeName,
            x: 'center'
          },
          yAxis: {
            name: this.performTypeList1[this.performType[i]].peformTypeName
          }
          // color: ['#7cb5ec', '#434348', '#90ed7d']
        })
      }
    },
    initEchart: function () {
      let _this = this
      for (var j = 0; j < this.performType.length; j++) {
        var div_e = document.getElementById(this.div_id[j])
        // this.echart[j] = Echart.init(div_e, null, {width: '100%', height: '500px'})
        this.echart[j] = Echart.init(div_e)
        this.echart[j].setOption(
          {
            animation: false,
            tooltip: {
              trigger: 'axis'
            },
            color: ['#7cb5ec', '#f7a35c', '#434348', '#90ed7d', '#8085e9',
              '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1'],
            // color: ['#7cb5ec'],
            // visualMap: {
            //   show: false,
            //   top: 10,
            //   right: 10,
            //   pieces: [{
            //     gt: 0,
            //     lte: 0.3,
            //     color: '#ffde33'
            //   }, {
            //     gt: 0.3,
            //     lte: 0.7,
            //     color: '#660099'
            //   }, {
            //     gt: 0.7,
            //     color: '#7e0023'
            //   }],
            //   outOfRange: {
            //     color: '#999'
            //   }
            // },
            toolbox: {
              show: true,
              orient: 'horizontal',
              itemSize: 15,
              itemGap: 5,
              showTitle: true,
              right: '30',
              top: '20',
              feature: {
                saveAsImage: {
                  show: true,
                  type: 'png',
                  title: '下载图片',
                  pixelRatio: 1,
                  excludeComponents: ['toolbox']
                },
                myView: {
                  title: '查看数据',
                  icon: 'path d="M911.266055 63.120445c106.980288 0 219.468995 25.353819 334.183707 75.005048 93.75631 40.803802 189.700895 99.264729 283.457205 172.062636a1892.104197 1892.104197 0 0 1 220.600862 201.8496 1837.397296 1837.397296 0 0 1-217.280719 198.529457c-94.850448 73.892045-190.851627 131.239969-284.570207 173.062452-114.695848 50.726502-228.259828 76.099186-336.390848 76.099186-106.980288 0-219.48786-25.372683-334.202572-74.986184-93.737445-40.728345-189.700895-99.208135-283.43834-171.987178a1890.689363 1890.689363 0 0 1-220.600862-201.8496A1836.586124 1836.586124 0 0 1 290.305 312.395269c93.75631-72.797907 189.700895-131.239969 284.551343-173.156774 114.695848-50.745367 228.259828-76.099186 336.409712-76.099185z m0-63.120445C407.698464 0 0 512 0 512s407.698464 512 911.266055 512 911.266055-512 911.266055-512S1414.833647 0 911.266055 0m-2.112818 291.587782a209.866991 209.866991 0 1 1-209.866991 209.866991 210.187687 210.187687 0 0 1 209.866991-209.866991z m0-59.819166a269.761615 269.761615 0 1 0 269.761615 269.761615 269.535242 269.535242 0 0 0-269.761615-269.761615',
                  onclick: function () {
                    _this.clickInit(this)
                  }
                }
              }
            },
            xAxis: [
              {
                type: 'time',
                splitLine: {
                  show: false
                },
                splitNumber: 8,
                boundaryGap: ['10%', '10%'],
                // maxInterval: 3600 * 24 * 1000,
                maxInterval: 40 * 1000,
                minInterval: 30 * 1000,
                axisLabel: {
                  showMinLabel: true,
                  showMaxLabel: true
                }
              }
            ],
            yAxis: [
              {
                splitLine: {
                  lineStyle: {
                    type: 'dotted'
                  }
                },
                // max: '1',
                type: 'value'
                // axisLabel: {
                //   formatter: '{value} °C'
                // }
              }
            ]
          }
        )
      }
    },
    clickInit: function (val) {
      this.dataList = val.ecModel.option.series
      this.visibleFlag = true
    },
    getData1: function () {
      var data = [],
        time = (new Date().getTime()),
        i
      for (i = -100; i < 0; i += 1) {
        data.push([
          time + i * 1000, 0
        ])
      }
      return data
    },
    initDivFirst: function () {
      var nd = this.$refs.containersAll
      if (nd.children.length > 0) {
        this.closeAll()
      }
      var par = this.$refs.containersAll
      var chids = par.childNodes
      for (var i = chids.length - 1; i >= 0; i--) {
        par.removeChild(chids[i])
      }
    },
    initDiv: function () {
      var div_parent = this.$refs.containersAll
      this.fullWidth = div_parent.clientWidth
      // this.fullHeight = div_parent.clientHeight
      this.fullHeight1 = document.documentElement.clientHeight - 200
      this.fullHeight = document.documentElement.clientHeight
      for (var m = 0; m < this.performType.length; m++) {
        var div = document.createElement('div')
        this.div_id[m] = 'chartDiv_' + m
        div.setAttribute('id', this.div_id[m])
        // div.setAttribute('style', 'width: 500px;height: 500px;')
        if (this.performType.length === 1) {
          // div.setAttribute('style', 'width: 100%;height: 500px')
          div.setAttribute('style', 'width:' + this.fullWidth + 'px;height:' + this.fullHeight1 + 'px;')
        } else {
          if (m === this.performType.length - 1) {
            div.setAttribute('style', 'width:' + this.fullWidth / 2 + 'px;height: 500px;float: left')
            // div.setAttribute('style', 'width:' + this.fullWidth / 2 + 'px;height:' + this.fullHeight / 2 + 'px')
            // div.setAttribute('style', 'width:' + this.fullWidth / 2 + 'px;height:500%;float: left')
          } else {
            div.setAttribute('style', 'width:' + this.fullWidth / 2 + 'px;height:500px;float: left')
            // div.setAttribute('style', 'width:' + this.fullWidth / 2 + 'px;height:' + this.fullHeight / 2 + 'px')
            // div.setAttribute('style', 'width:' + this.fullWidth / 2 + 'px;height:' + this.fullHeight / 2 + 'px;float: left')
          }
        }
        div.setAttribute('class', 'box')
        div_parent.appendChild(div)
      }
    },
    contains: function (value) {
      var flag = false
      switch (value) {
        case 'shangxing':
          flag = true
          break
        case 'cpu':
          flag = false
          break
        case 'temperature':
          flag = false
          break
        case 'error':
          flag = true
          break
      }
      return flag
    },
    portOr: function (type) {
      for (var j = 0; j < this.performTypeList.length; j++) {
        if (this.performTypeList1[type].resourceType === 0) {
          return true
        }
      }
    },
    queryRtEventChange: function () {
      let deviceCheck = legitimacyCheck()
      var result = deviceCheck.textNullCheck(this.performType)
      if (!result) {
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.TEXT_NULL_CODE), this.$t('RtPerformance.performanceEvents'))
        return false
      }
      return true
    },
    check: function () {
      let rtCheck = legitimacyCheck()
      var _this = this
      if (this.performType.length === 0) {
        this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.TEXT_NULL_CODE), this.$t('RtPerformance.performanceEvents'))
        return false
      } else {
        var result = rtCheck.textNullCheck(this.queryRtPort)
        var flag = _this.performType.some(function (val) {
          return _this.performTypeList1[val].resourceType === 1
        })
        if (result && !flag) {
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.TEXT_NULL_CODE), this.$t('RtPerformance.performancePortEvents'))
          return false
        }
        if (flag && !result) {
          this.InfoTip.warningTip(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.TEXT_NULL_CODE), this.$t('RtPerformance.devicePort'))
          return false
        } else {
          return true
        }
      }
    },
    clearAll: function () {
      if (this.timeEchart) {
        if (this.timeEchart) {
          clearInterval(this.timeEchart)
        }
      }
    },
    closeAll: function () {
      if (this.echart) {
        for (var i = 0; i < this.echart.length; i++) {
          this.echart[i].clear()
        }
      }
      if (this.timeEchart) {
        clearInterval(this.timeEchart)
      }
    },
    closeAll1: function () {
      if (this.echart) {
        for (var i = 0; i < this.echart.length; i++) {
          this.echart[i].dispose()
        }
      }
      if (this.timeEchart) {
        clearInterval(this.timeEchart)
      }
    },
    resizeResolve: function () {
      if (this.echart) {
        for (var i = 0; i < this.echart.length; i++) {
          this.echart[i].resize()
          // setTimeout(this.echart[i].resize(), 100)
        }
      }
    }
  },
  mounted: function () {
    window.addEventListener('resize', this.resizeResolve())
  },
  destroyed: function () {
    this.closeAll1()
  },
  beforeDestroy: function () {
    window.removeEventListener('resize', this.resizeResolve())
  },
  components: {
    RtTable
  },
  computed: {
    deviceKeyList () {
      return this.$store.state.passDev
    }
  },
  watch: {
    deviceKeyList (newVal) {
      this.flag = true
      this.F = false
      this.deviceKey = newVal
      this.performTypeList = []
      this.performTypeList1 = {}
      this.getPerformTypeList()
      this.initFirst()
      this.initDivFirst()
    },
    fullWidth: {
      immediate: true,
      deep: true,
      handler: function () {
        if (this.echart) {
          this.resizeResolve()
        }
      }
    }
  }
}
</script>
<style lang="scss">
  .box {
    /*width: 800px;*/
    /*height: 600px;*/
    display: inline-block;
    border: 1px solid #ccc;
    overflow: hidden;
    /*position: relative;*/
  }
</style>
