<template>
  <div id="main" class="h-all">
    <el-container class="h-all">
      <el-header height="auto">
        <!-- 条件查询工具栏 -->
        <div class="header-search">
          <el-row>
            <div class="search-input-box">
              <label>{{ $t("AlarmStatistics.beginTimestamp") }}</label>
              <el-date-picker
                v-model="beginTimestamp"
                type="datetime"
                size="mini"
                format="yyyy-MM-dd HH:mm"
                :clearable="false"
                align="center"
                :picker-options="startDatePicker"
                @change="beginDateChange"
                :placeholder="$t('AlarmStatistics.chooseStartTime')">
              </el-date-picker>
            </div>
            <div class="search-input-box">
              <label>{{ $t("AlarmStatistics.endTimestamp") }}</label>
              <el-date-picker
                v-model="endTimestamp"
                type="datetime"
                size="mini"
                format="yyyy-MM-dd HH:mm"
                :clearable="false"
                align="center"
                :picker-options="endDatePicker"
                @change="endDateChange"
                :placeholder="$t('AlarmStatistics.chooseEndTime')">
              </el-date-picker>
            </div>
            <div class="search-input-box">
              <label>{{ $t("AlarmStatistics.staticInterval") }}</label>
              <el-select size='mini' v-model="staticInterval">
                <el-option
                  v-for="item in optionsPeriod"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled">
                </el-option>
              </el-select>
            </div>
            <div class="search-input-box">
              <label>{{ $t("AlarmStatistics.Y") }}</label>
              <el-select size='mini'
                         v-model="valueY">
                <el-option
                  v-for="item in valueList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div class="search-input-box">
              <label>{{$t("Performance.statisticsType") + '：'}}</label>
              <el-select size='mini' v-model="valueType">
                <el-option
                  v-for="item in optionsType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <el-button size='mini' icon="el-icon-plus" type="primary" @click="moreConditionOr">
              {{ $t("AlarmStatistics.moreCondition") }}
            </el-button>
            <el-button size='mini' icon="el-icon-upload2" type="warning" @click="importFile">
              {{$t("AlarmStatistics.importTemplate")}}
            </el-button>
            <el-button size='mini' icon="el-icon-s-data" type="success" @click="staticsData">
              {{$t("AlarmStatistics.statistic")}}
            </el-button>
            <el-button size='mini' icon="el-icon-download" type="danger" @click="exportFile">
              {{msg}}
            </el-button>
          </el-row>
          <el-row v-show="conditionShowFlag" style="margin-top: 5px">
            <div class="search-input-box">
              <label>{{ $t("Performance.deviceType") + '：'}}</label>
              <el-select size='mini' clearable
                         multiple
                         collapse-tags
                         v-model="deviceType"
                         @change="deviceTypeChange"
                         :placeholder="$t('common.selectOption')">
                <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-select size='mini' clearable
                         v-model="deviceModel"
                         multiple
                         collapse-tags
                         @change="deviceModelChange"
                         :placeholder="$t('common.selectOption')">
                <el-option v-for="item in deviceModelList"
                           :key="item.deviceModelKey"
                           :label="item.deviceModel"
                           :value="item.deviceModel">
                </el-option>
              </el-select>
            </div>
            <div class="search-input-box">
              <label>{{ $t("Performance.deviceName") + '：'}}</label>
              <el-select size='mini' v-model="deviceName"
                         placeholder="请选择"
                         clearable
                         multiple
                         collapse-tags
                         multiple-limit=5>
                <el-option
                  v-for="item in deviceList"
                  :key="item.deviceKey"
                  :label="item.displayName"
                  :value="item.deviceKey">
                </el-option>
              </el-select>
            </div>
<!--            <div class="search-input-box">-->
<!--              <label>{{ $t("Performance.deviceBrand") + '：' }}</label>-->
<!--              <el-select size='mini' clearable-->
<!--                         v-model="deviceBrand"-->
<!--                         multiple-->
<!--                         collapse-tags-->
<!--                         :placeholder="$t('common.selectOption')">-->
<!--                <el-option v-for="item in deviceModelList"-->
<!--                           :key="item.deviceModelKey"-->
<!--                           :label="item.deviceModel"-->
<!--                           :value="item.deviceModel">-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </div>-->
            <div class="search-input-box">
              <label>{{ $t("Performance.performParam") + '：'}}</label>
              <el-select size='mini' clearable
                         v-model="deviceParam"
                         multiple
                         collapse-tags
                         :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>
          </el-row>
        </div>
      </el-header>
      <!-- table数据表格 -->
      <el-main class="adapt-height-box">
        <el-tabs v-model="activeName" type="card" class="statistic-tab-box h-all adapt-height adapt-height-box"
                 :before-leave="handleClick" @tab-click="handleClick1">
          <el-tab-pane :label="$t('AlarmStatistics.statisticResult')" name="first" class="h-all adapt-height adapt-height-box">
            <el-table
              id="myTable"
              :empty-text="$t('common.noData')"
              header-row-class-name="table-header"
              cell-class-name="table-cell"
              class="adapt-height"
              ref="multipleTable"
              :data="dataList1"
              stripe
              tooltip-effect="dark"
              height="auto"
              border
              :highlight-current-row="true">
              <el-table-column
                type="index"
                v-if="this.showFlag"
                :label="$t('AlarmStatistics.No')"
                width="50">
              </el-table-column>
              <el-table-column
                v-if="this.showFlag"
                prop="time"
                :label="$t('Performance.acquisitionTime')">
              </el-table-column>
              <el-table-column
                v-for="(item, index) in tableLabel"
                :key="index"
                :prop="item.prop"
                :width="item.width"
                :label="item.label"
              >
              </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           background
                           :current-page="currentPage"
                           :page-sizes="[10, 20, 50, 100]"
                           :page-size="pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="total">
            </el-pagination>
          </el-tab-pane>
          <el-tab-pane :label="$t('AlarmStatistics.statisticGraph')" name="second" :lazy='true' class="h-all adapt-height adapt-height-box">
            <el-row style="margin-left: -1000px" v-show="showFlag">
              <el-col>
                <label>{{ $t("AlarmStatistics.typeChange") }}</label>
                <el-select size='mini'
                           style="width: 100px"
                           @change="chartTypeChange"
                           v-model="chartType">
                  <el-option v-for="item in chartTypeList"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
            <div id="staticId" class="h-all adapt-height adapt-height-box">
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
    <ImportReportTemplate :innerVisible.sync="innerVisible"
                          :templateType.sync=templateType
                          :title="title"
                          :detailType="4">
    </ImportReportTemplate>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import DeviceService from '@/domain/services/DeviceService.js'
import AlarmManagerService from '@/domain/services/AlarmManagerService.js'
import HelperUtil from '../../utils/HelperUtil'
import legitimacyCheck from '../../utils/legitimacyCheck'
import Echart from 'echarts'
import PerformanceStatisticService from '../../domain/services/PerformanceStatisticService'
import ImportReportTemplate from "./ImportReportTemplate";

export default {
  name: 'PerformTrendStatisticReport',
  data: function () {
    return {
      conditionShowFlag: false,
      msg: this.$t('AlarmStatistics.exportStatisticResult'),
      staticInterval: 1,
      valueY: 'displayName',
      // Tab页
      activeName: 'first',
      // Y值
      valueList: [
        {
          value: 'displayName',
          label: this.$t('Performance.deviceName')
        },
        {
          value: 'deviceTypeKey',
          label: this.$t('Performance.deviceType')
        },
        {
          value: 'deviceModel',
          label: this.$t('Performance.deviceModel')
        },
        {
          value: 'brand',
          label: this.$t('Performance.deviceBrand')
        },
        {
          value: 'deviceParam',
          label: this.$t('Performance.performParam')
        }
      ],

      // 统计周期
      optionsPeriod: [
        {
          value: 1,
          label: this.$t('AlarmStatistics.hour'),
          disabled: false
        },
        {
          value: 2,
          label: this.$t('AlarmStatistics.day'),
          disabled: false
        },
        {
          value: 3,
          label: this.$t('AlarmStatistics.week'),
          disabled: false
        },
        {
          value: 4,
          label: this.$t('AlarmStatistics.month'),
          disabled: false
        }
      ],
      performTypeList: [],
      // 统计类型
      chartType: 'bar',
      chartTypeList: [
        {
          value: 'line',
          label: this.$t('AlarmStatistics.line')
        },
        {
          value: 'bar',
          label: this.$t('AlarmStatistics.bar')
        }
      ],
      valueType: 0,
      optionsType: [
        {
          value: 0,
          label: this.$t('Performance.maximumValue')
        },
        {
          value: 1,
          label: this.$t('Performance.minimumValue')
        },
        {
          value: 2,
          label: this.$t('Performance.meanValue')
        },
        {
          value: 3,
          label: this.$t('Performance.sum')
        }
      ],
      valueAspect: 'alarmLevel', // 统计维度
      // 设备类型选择域
      deviceList: [],
      deviceTypeList: [],
      deviceModelList: [],
      deviceModelList1: [],
      deviceList0: [],
      deviceModelList0: [],
      alarmListStatistics: [],
      performListStatistics: [],

      // 日期控件
      beginTimestamp: '', // 开始时间
      endTimestamp: '', // 结束时间
      addTimestamp: '00.000', // 查询开始时间默认添加
      addTimestamp1: '59.999', // 查询结束时间默认添加
      startDatePicker: this.beginDate(),
      endDatePicker: this.endDate(),

      // 双向绑定数据
      deviceBrand: [], // 设备类型
      deviceModel: [], // 设备类型
      deviceType: [], // 设备类型
      deviceName: [], // 设备名称
      deviceParam: [], // 性能指标
      // 统计条件
      t1: [],
      se: [],
      yAxis: [],
      showData: [],
      showDataY: [],
      dataList: [],
      dataList1: [],
      selectList: [],
      statisticsList: [],
      conditions: {},
      chartData: [],
      echartLine: null,
      echartPie: null,
      tableLabel: [],
      pageSize: 20,
      currentPage: 1,
      total: 0,
      colors: ['#7cb5ec', '#f7a35c', '#434348', '#90ed7d', '#8085e9',
        '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1'],
      check: null,
      innerVisible: false,
      templateType: {},
      title: this.$t('ReportTemplateManagement.performanceTrend')
    }
  },
  created: function () {
    this.check = legitimacyCheck()
    this.setDefaultDateTime()
    this.getAlarmTypeList()
    this.getAllDevice()
    this.getAllDeviceModel()
    this.getAllDeviceType()
    this.getPerformType()
  },
  methods: {
    /**
     * @Description  : handelSizeCha
     * @author       : ls
     * @date         : 2020/5/9 17:03
     * @param        :
     * @return       :
     */
    handleSizeChange: function (pageSize) {
      this.pageSize = pageSize
      this.handleCurrentChange(this.currentPage)
    },
    /**
     * @Description  : handleCurrentChange
     * @author       : ls
     * @date         : 2020/5/9 17:04
     * @param        :
     * @return       :
     */
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
      this.currentChangePage(this.dataList, currentPage)
    },
    /**
     * @Description  : currentChangePage
     * @author       : ls
     * @date         : 2020/5/9 17:06
     * @param        :
     * @return       :
     */
    currentChangePage (list, currentPage) {
      let from = (currentPage - 1) * this.pageSize
      let to = currentPage * this.pageSize
      this.dataList1 = []
      for (; from < to; from++) {
        if (list[from]) {
          this.dataList1.push(list[from])
        }
      }
    },
    /**
     * @Description  : handleTotal
     * @author       : ls
     * @date         : 2020/5/9 18:00
     * @param        :
     * @return       :
     */
    handleTotal: function () {
      this.dataList1 = []
      this.total = this.dataList.length
      if (this.total > this.pageSize) {
        for (let index = 0; index < this.pageSize; index++) {
          this.dataList1.push(this.dataList[index])
        }
      } else {
        this.dataList1 = this.dataList
      }
    },
    /**
     * @Description  : chartTypeChange
     * @author       : ls
     * @date         : 2020/5/14 14:57
     * @param        :
     * @return       :
     */
    chartTypeChange: function () {
      switch (this.chartType) {
        case 'pie':
          this.closeAll()
          this.echartPieInit()
          break
        default:
          this.closeAll()
          this.chartInit()
          this.genChart()
      }
    },
    /**
     * @Description  : 关闭
     * @author       : ls
     * @date         : 2020/5/14 15:57
     * @param        :
     * @return       :
     */
    closeAll: function () {
      if (this.echartLine) {
        this.echartLine.clear()
      }
      if (this.echartPie) {
        this.echartPie.clear()
      }
    },
    /**
     * @Description  : 初始化
     * @author       : ls
     * @date         : 2020/5/7 16:08
     * @param        :
     * @return       :
     */
    chartInit: function () {
      var div_e = document.getElementById('staticId')
      this.echartLine = Echart.init(div_e)
      this.echartLine.setOption(
        {
          animation: true,
          tooltip: {
            trigger: 'axis'
          },
          color: ['#7cb5ec', '#f7a35c', '#175BE3', '#008000',
            '#0366CB', '#e4d354', '#8085e8', '#8d4653', '#91e8e1'],
          toolbox: {
            show: true,
            orient: 'horizontal',
            itemSize: 15,
            itemGap: 5,
            showTitle: true,
            right: '10%',
            top: '20',
            emphasis: {
              iconStyle: {
                textPosition: 'top'
              }
            },
            feature: {
              saveAsImage: {
                show: true,
                type: 'png',
                backgroundColor: '#fff',
                title: '保存图片',
                pixelRatio: 1,
                excludeComponents: ['toolbox']
              }
            }
          }
        }
      )
    },
    /**
     * @Description  : getData1
     * @author       : ls
     * @date         : 2020/5/13 10:24
     * @param        :
     * @return       :
     */
    getData1: function () {
      var tt = []
      for (var i = 0; i < this.dataList.length; i++) {
        tt.push(this.dataList[i].time)
      }
      return tt
    },
    /**
     * @Description  : 获取数据
     * @author       : ls
     * @date         : 2020/5/7 16:02
     * @param        :
     * @return       :
     */
    getData: function (item) {
      this.chartData.length = 0
      var ret = []
      for (var i = 0; i < this.dataList.length; i++) {
        // if (this.valueY === 'deviceModel') {
        //   var val = ''
        //   val = item.split('.').join('')
        //   ret.push(this.dataList[i][val])
        // } else {
        //   ret.push(this.dataList[i][item])
        // }
        ret.push(this.dataList[i][item])
      }
      return ret
    },
    /**
     * @Description  : 绘图
     * @author       : ls
     * @date         : 2020/5/7 16:13
     * @param        :
     * @return       :
     */
    genChart: function () {
      this.se = []
      this.yAxis = []
      for (var t = 0; t < this.showData.length; t++) {
        if (this.valueY === 'deviceParam') {
          this.se.push(
            {
              type: this.chartType,
              name: this.showData[t],
              yAxisIndex: t,
              data: this.getData(this.showData[t])
            }
          )
          if (t === 0) {
            this.yAxis.push(
              {
                position: 'left',
                type: 'value',
                axisLine: {
                  lineStyle: {
                    color: this.colors[t]
                  }
                }
              }
            )
          } else {
            this.yAxis.push(
              {
                position: 'right',
                type: 'value',
                offset: 40 * (t - 1),
                axisLine: {
                  lineStyle: {
                    color: this.colors[t]
                  }
                }
              }
            )
          }
        } else {
          this.se.push({
            type: this.chartType,
            name: this.showData[t],
            data: this.getData(this.showDataY[t])
          })
        }
      }
      if (this.valueY === 'deviceParam') {
        this.yAxis = this.yAxis
      } else {
        this.yAxis = {
          name: '次数',
          type: 'value',
          max: function (value) {
            if (value.max < 1) {
              return 1
            } else {
              return value.max
            }
          },
          minInterval: 1
        }
      }
      this.echartLine.setOption({
        series: this.se,
        legend: {
          left: 'center',
          top: 30
        },
        title: {
          text: '性能趋势统计',
          x: 'center'
        },
        yAxis: this.yAxis,
        xAxis:
          {
            type: 'category',
            data: this.getData1(),
            splitLine: {
              show: false
            },
            boundaryGap: ['10%', '10%'],
            axisLabel: {
              showMinLabel: true,
              showMaxLabel: true
            }
          }
      })
    },
    /**
     * @Description  : 校验
     * @author       : ls
     * @date         : 2020/5/13 10:56
     * @param        :
     * @return       :
     */
    submitCheck: function () {
      if (this.valueY !== 'deviceParam') {
        if (this.deviceParam.length !== 1) {
          this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.PARAM_NOT_NULL), 'Y')
          return false
        }
      }
      return true
    },
    /**
     * @Description  : 统计数据
     * @author       : ls
     * @date         : 2020/5/7 15:44
     * @param        :
     * @return       :
     */
    staticsData: function () {
      if (!this.submitCheck()) {
        return
      }
      // this.getData()
      this.setStatisticsList()
      this.obtainData()
    },
    /**
     * @Description  : y校验
     * @author       : ls
     * @date         : 2020/5/7 12:48
     * @param        :
     * @return       :
     */
    // valueYChange: function () {
    //   if (!this.check.textNullCheck(this.valueY)) {
    //     this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.TEXT_NULL_CODE), this.$t('ReportTemplateManagement.Y'))
    //     return false
    //   }
    //   if (this.valueY === this.valueX) {
    //     this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.NOT_EQUAL))
    //     this.valueY = ''
    //     return false
    //   }
    //   return true
    // },
    /**
     * @Description  : x校验
     * @author       : ls
     * @date         : 2020/5/7 12:50
     * @param        :
     * @return       :
     */
    valueXChange: function () {
      if (!this.check.textNullCheck(this.valueX)) {
        this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.TEXT_NULL_CODE), this.$t('ReportTemplateManagement.Y'))
        return false
      }
      if (this.valueY === this.valueX) {
        this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.NOT_EQUAL))
        this.valueX = ''
        return false
      }
      return true
    },
    /**
     * @Description  : obtainData
     * @author       : ls
     * @date         : 2020/5/8 19:07
     * @param        :
     * @return       :
     */
    obtainData: function () {
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      AlarmManagerService.queryReportService(this.conditions).then(result => {
        // _this.performListStatistics = Object.values(result)
        _this.performListStatistics = result
        _this.Loading.closeLoading(loadingInstance)
        if (_this.performListStatistics.length > 0) {
          this.showFlag = true
          _this.performListStatisticsInit()
        } else {
          this.showFlag = false
          this.dataList = []
          this.dataList1 = []
          this.tableLabel = []
          this.handleTotal()
          this.closeAll()
          _this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.QUERY_NULL_CODE))
        }
      }).catch(err => {
        _this.Loading.closeLoading(loadingInstance)
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 初始化
     * @author       : ls
     * @date         : 2020/5/8 19:15
     * @param        :
     * @return       :
     */
    performListStatisticsInit: function () {
      this.t1 = []
      var time = new Date(this.beginTimestamp)
      switch (this.staticInterval) {
        case 1:
          while (time.getTime() <= this.endTimestamp) {
            this.t1.push(HelperUtil.timePass(time, this.staticInterval, this.beginTimestamp, this.endTimestamp))
            time = new Date(time.getTime() + (1000 * 60 * 60))
          }
          break
        case 2:
          while (time.getTime() <= this.endTimestamp) {
            this.t1.push(HelperUtil.timePass(time, this.staticInterval, this.beginTimestamp, this.endTimestamp))
            time = new Date(time.getTime() + (1000 * 60 * 60 * 24))
          }
          break
        case 3:
          while (time.getTime() <= this.endTimestamp) {
            this.t1.push(HelperUtil.timePass(time, this.staticInterval, this.beginTimestamp, this.endTimestamp))
            time = new Date(time.getTime() + (1000 * 60 * 60 * 24 * 7))
          }
          break
        case 4:
          this.t1 = HelperUtil.timePass(time, this.staticInterval, this.beginTimestamp, this.endTimestamp)
          break
      }
      this.unique(this.performListStatistics.map(function (val) {
        return val[1]
      }))
      this.showDataY = []
      for (var k = 0; k < this.showData.length; k++) {
        if (this.showData[k].indexOf('.') !== -1) {
          this.showDataY.push(this.showData[k].split('.').join(''))
        } else {
          this.showDataY.push(this.showData[k])
        }
      }
      this.genData()
      this.handleTableLabel()
      this.handleTotal()
      if (this.activeName === 'second') {
        this.chartTypeChange()
      }
    },
    /**
     * @Description  : genData
     * @author       : ls
     * @date         : 2020/5/9 11:47
     * @param        :
     * @return       :
     */
    genData: function () {
      this.dataList = []
      for (var i = 0; i < this.t1.length; i++) {
        var datas = {}
        datas['time'] = this.t1[i]
        for (var j = 0; j < this.showData.length; j++) {
          // if (this.valueY === 'deviceModel') {
          //   var val = ''
          //   val = this.showData[j].split('.').join('')
          //   datas[val] = '0'
          // } else {
          //   datas[this.showData[j]] = '0'
          // }
          datas[this.showDataY[j]] = '0'
        }
        this.dataList.push(datas)
      }
      for (let m in this.dataList) {
        for (let n in this.performListStatistics) {
          if (this.dataList[m].time === this.performListStatistics[n][0]) {
            for (let q = 0; q < this.showData.length; q++) {
              if (this.showData[q] === this.performListStatistics[n][1]) {
                // if (this.valueY === 'deviceModel') {
                //   var val1 = ''
                //   val1 = this.showData[q].split('.').join('')
                //   this.dataList[m][val1] = this.performListStatistics[n][2]
                // } else {
                //   this.dataList[m][this.showData[q]] = this.performListStatistics[n][2]
                // }
                this.dataList[m][this.showDataY[q]] = this.performListStatistics[n][2]
              }
            }
          }
        }
      }
    },
    /**
     * @Description  : unique
     * @author       : ls
     * @date         : 2020/5/9 9:34
     * @param        :
     * @return       :
     */
    unique: function (arr) {
      this.showData = Array.from(new Set(arr))
    },
    /**
     * @Description  : 更多条件
     * @author       : ls
     * @date         : 2020/5/7 12:45
     * @param        :
     * @return       :
     */
    moreConditionOr: function () {
      this.conditionShowFlag = !this.conditionShowFlag
    },
    // 导出按钮显示
    handleClick (activeName, oldActiveName) {
      if (activeName === 'first') {
        this.msg = this.$t('AlarmStatistics.exportStatisticResult')
      } else {
        this.msg = this.$t('AlarmStatistics.exportStatisticGraph1')
      }
      return true
    },
    handleClick1 () {
      if (this.activeName === 'second' && this.dataList.length !== 0) {
        if (this.echartLine === null) {
          this.$nextTick(function () {
            this.chartInit()
            this.genChart()
          })
        }
      }
    },

    /**
       * ----------时间处理函数------------------------------------------------------------
       * */
    /**
     * @Description  : 开始时间设置
     * @author       : ls
     * @date         : 2020/5/7 13:00
     * @param        :
     * @return       :
     */
    beginDate: function () {
      let self = this
      return {
        disabledDate (time) {
          return time.getTime() > self.endTimestamp.getTime() || time.getTime() > Date.now()
        }
      }
    },
    /**
     * @Description  : 结束时间设置
     * @author       : ls
     * @date         : 2020/5/7 13:00
     * @param        :
     * @return       :
     */
    endDate: function () {
      let self = this
      return {
        disabledDate (time) {
          return time.getTime() < self.beginTimestamp.getTime() || time.getTime() > Date.now()
        }
      }
    },
    /**
     * @Description  : 起始时间赋值
     * @author       : ls
     * @date         : 2020/5/7 15:40
     * @param        :
     * @return       :
     */
    beginDateChange: function () {
      const setTimes = new Date()
      if (this.beginTimestamp === null) {
        setTimes.setTime(this.endTimestamp.getTime() - (60 * 60 * 1000))
        this.beginTimestamp = setTimes
        this.InfoTip.warningTip_alarm(this, {message: this.$t('AlarmStatistics.startTimeEmpty')})
      }
      if (this.beginTimestamp > this.endTimestamp) {
        setTimes.setTime(this.endTimestamp.getTime() - (60 * 60 * 1000))
        this.beginTimestamp = setTimes
        this.InfoTip.warningTip_alarm(this, {message: this.$t('AlarmStatistics.startGreaterEnd')})
      }
      this.changeValuePeriod()
    },
    /**
     * @Description  : 结束时间赋值
     * @author       : ls
     * @date         : 2020/5/7 15:40
     * @param        :
     * @return       :
     */
    endDateChange: function () {
      const setTimes = new Date()
      const curTimes = new Date()
      if (this.endTimestamp === null) {
        if ((this.beginTimestamp.getTime() + (60 * 60 * 1000)) > curTimes.getTime()) {
          this.endTimestamp = curTimes
        } else {
          setTimes.setTime(this.beginTimestamp.getTime() + (60 * 60 * 1000))
          this.endTimestamp = setTimes
        }
        this.InfoTip.warningTip_alarm(this, {message: this.$t('AlarmStatistics.endTimeEmpty')})
      }
      if (this.endTimestamp < this.beginTimestamp) {
        if ((this.beginTimestamp.getTime() + (60 * 60 * 1000)) > curTimes.getTime()) {
          this.endTimestamp = curTimes
        } else {
          setTimes.setTime(this.beginTimestamp.getTime() + (60 * 60 * 1000))
          this.endTimestamp = setTimes
        }
        this.InfoTip.warningTip_alarm(this, {message: this.$t('AlarmStatistics.endSmallerStart')})
      }
      if (this.endTimestamp > curTimes) {
        if ((this.beginTimestamp.getTime() + (60 * 60 * 1000)) > curTimes.getTime()) {
          this.endTimestamp = curTimes
        } else {
          setTimes.setTime(this.beginTimestamp.getTime() + (60 * 60 * 1000))
          this.endTimestamp = setTimes
        }
        this.InfoTip.warningTip_alarm(this, {message: this.$t('AlarmStatistics.endGreaterNow')})
      }
      this.changeValuePeriod()
    },
    /**
     * @Description  : 修改事件间隔
     * @author       : ls
     * @date         : 2020/5/8 16:27
     * @param        :
     * @return       :
     */
    changeValuePeriod: function () {
      var judgeTime = this.endTimestamp - this.beginTimestamp
      if (judgeTime > (7 * 24 * 60 * 60 * 1000) && judgeTime <= (30 * 24 * 60 * 60 * 1000)) {
        this.optionsPeriod[0].disabled = true
        this.optionsPeriod[1].disabled = false
        this.optionsPeriod[2].disabled = false
        this.optionsPeriod[3].disabled = false
        this.staticInterval = 2
      } else if (judgeTime > (30 * 24 * 60 * 60 * 1000) && judgeTime <= (180 * 24 * 60 * 60 * 1000)) {
        this.optionsPeriod[0].disabled = true
        this.optionsPeriod[1].disabled = true
        this.optionsPeriod[2].disabled = false
        this.optionsPeriod[3].disabled = false
        this.staticInterval = 3
      } else if (judgeTime > (180 * 24 * 60 * 60 * 1000)) {
        this.optionsPeriod[0].disabled = true
        this.optionsPeriod[1].disabled = true
        this.optionsPeriod[2].disabled = true
        this.optionsPeriod[3].disabled = false
        this.staticInterval = 4
      } else {
        this.optionsPeriod[0].disabled = false
        this.optionsPeriod[1].disabled = false
        this.optionsPeriod[2].disabled = false
        this.optionsPeriod[3].disabled = false
        this.staticInterval = 1
      }
    },
    /**
     * @Description  : 默认时间
     * @author       : ls
     * @date         : 2020/5/7 15:14
     * @param        :
     * @return       :
     */
    setDefaultDateTime: function () {
      const start = new Date()
      const end = new Date()
      start.setTime(start.getTime() - 3600 * 1000)
      this.beginTimestamp = start
      this.endTimestamp = end
    },
    /**
     * @Description  : 获取告警原因
     * @author       : ls
     * @date         : 2020/5/7 15:12
     * @param        :
     * @return       :
     */
    getAlarmTypeList: function () {
      let _this = this
      AlarmManagerService.getAlarmTypeList().then(result => {
        _this.optionsAlarmCause = Object.values(result)
        // _this.handleAlarmCause();
      }).catch(err => {
        _this.InfoTip.errorTip(_this, err)
      })
    },

    /**
     * @Description  : 获取网元
     * @author       : ls
     * @date         : 2020/5/7 15:07
     * @param        :
     * @return       :
     */
    getAllDevice: function () {
      let _this = this
      DeviceService.getAllDeviceCollection().then(result => {
        _this.deviceList = Object.values(result)
        _this.deviceList0 = Object.values(result)
        // _this.getAllDeviceModelListSelf()
      }).catch(err => {
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 网元类型变化
     * @author       : ls
     * @date         : 2020/5/8 9:50
     * @param        :
     * @return       :
     */
    deviceTypeChange: function () {
      var a = HelperUtil.deviceTypeChangeCURD(this.deviceModelList1, this.deviceType, this.deviceModel, this.deviceList0)
      this.deviceModelList = a[0]
      this.deviceModel = ''
      this.deviceName = ''
      this.deviceList = []
      this.deviceList = a[1]

      // this.deviceModel = ''
      // this.deviceName = ''
      // this.deviceModelList = []
      // this.deviceList = []
      // for (let j in this.deviceModelList0) {
      //   if (this.deviceType.length === 0) {
      //     this.deviceModelList.push(this.deviceModelList0[j])
      //   }
      //   for (let key1 in this.deviceType) {
      //     if (this.deviceType[key1] === this.deviceModelList0[j]['key']) {
      //       this.deviceModelList.push(this.deviceModelList0[j])
      //     }
      //   }
      // }
      // for (let i in this.deviceList0) {
      //   if (this.deviceType.length === 0) {
      //     this.deviceList.push(this.deviceList0[i])
      //   }
      //   for (let key in this.deviceType) {
      //     if (this.deviceType[key] === this.deviceList0[i]['deviceTypeKey']) {
      //       this.deviceList.push(this.deviceList0[i])
      //     }
      //   }
      // }
    },
    /**
     * @Description  : 网元型号变化
     * @author       : ls
     * @date         : 2020/5/8 11:49
     * @param        :
     * @return       :
     */
    deviceModelChange: function () {
      this.deviceName = ''
      this.deviceList = []
      this.deviceList = HelperUtil.deviceModelChangeCURD(this.deviceType, this.deviceModel, this.deviceList0)


      // this.deviceName = ''
      // this.deviceList = []
      // for (let k in this.deviceList0) {
      //   if (this.deviceModel.length === 0) {
      //     if (this.deviceType.length === 0) {
      //       this.deviceList.push(this.deviceList0[k])
      //     } else {
      //       for (let t in this.deviceType) {
      //         if (this.deviceList0[k].deviceTypeKey === this.deviceType[t]) {
      //           this.deviceList.push(this.deviceList0[k])
      //         }
      //       }
      //     }
      //   }
      //   for (let key in this.deviceModel) {
      //     if (this.deviceModel[key] === this.deviceList0[k]['deviceModel']) {
      //       if (this.deviceType.length === 0) {
      //         this.deviceList.push(this.deviceList0[k])
      //       } else {
      //         for (let key1 in this.deviceType) {
      //           if (this.deviceType[key1] === this.deviceList0[k]['deviceTypeKey']) {
      //             this.deviceList.push(this.deviceList0[k])
      //           }
      //         }
      //       }
      //     }
      //   }
      // }
    },
    /**
     * @Description  : 获取设备的网元型号
     * @author       : ls
     * @date         : 2020/5/8 10:23
     * @param        :
     * @return       :
     */
    getAllDeviceModelListSelf: function () {
      for (let key in this.deviceList) {
        let containIs = false
        for (let i in this.deviceModelList) {
          if (this.deviceList[key].deviceModel === this.deviceModelList[i].value) {
            containIs = true
            break
          }
        }
        if (containIs === false && this.deviceList[key].deviceModel !== '') {
          let device = {}
          device.key = this.deviceList[key].deviceTypeKey
          device.label = this.deviceList[key].deviceModel
          device.value = this.deviceList[key].deviceModel
          this.deviceModelList.push(device)
          this.deviceModelList0.push(device)
        }
      }
    },
    /**
     * @Description  : 获取网元类型
     * @author       : ls
     * @date         : 2020/5/7 15: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  : 获取性能指标
     * @author       : ls
     * @date         : 2020/5/13 10:08
     * @param        :
     * @return       :
     */
    getPerformType: function () {
      let _this = this
      PerformanceStatisticService.getPerformTypeService().then(result => {
        _this.performTypeList = Object.values(result)
      }).catch(err => {
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
     * @Description  : 获取网元型号
     * @author       : ls
     * @date         : 2020/5/7 15:05
     * @param        :
     * @return       :
     */
    getAllDeviceModel: function () {
      let _this = this
      DeviceService.getAllDeviceModelCollection().then(result => {
        _this.deviceModelList = Object.values(result)
        _this.deviceModelList1 = Object.values(result)
      }).catch(err => {
        _this.InfoTip.errorTip(_this, err)
      })
    },
    /**
    * @Description  : 设置条件
    * @author       : ls
    * @date         : 2020/5/7 15:16
    * @param        :
    * @return       :
    */
    setStatisticsList: function () {
      this.conditions = {}
      this.statisticsList = []
      if (this.deviceType.length !== 0) {
        this.statisticsList.push({
          quaryAttribute: 'deviceTypeKey',
          compareSymbol: 'in',
          compareValue: this.deviceType.join(',')
        })
      }
      if (this.deviceName.length !== 0) {
        this.statisticsList.push({
          quaryAttribute: 'deviceKey',
          compareSymbol: 'in',
          compareValue: this.deviceName.join(',')
        })
      }
      if (this.deviceModel.length !== 0) {
        this.statisticsList.push({
          quaryAttribute: 'deviceModel',
          compareSymbol: 'in',
          compareValue: this.deviceModel.join(',')
        })
      }
      if (this.deviceBrand.length !== 0) {
        this.statisticsList.push({
          quaryAttribute: 'brand',
          compareSymbol: 'in',
          compareValue: this.deviceBrand.join(',')
        })
      }
      if (this.deviceParam.length !== 0) {
        this.statisticsList.push({
          quaryAttribute: 'deviceParam',
          compareSymbol: 'in',
          compareValue: this.deviceParam.join(',')
        })
      }

      this.conditions.queryTerms = this.statisticsList
      this.conditions.reportType = 4
      this.conditions.startTime = HelperUtil.getTimeInit(this.beginTimestamp) + this.addTimestamp
      this.conditions.endTime = HelperUtil.getTimeInit(this.endTimestamp) + this.addTimestamp1
      this.conditions.xAxis = ''
      this.conditions.yAxis = this.valueY
      this.conditions.aggregateFunc = this.valueType
      this.conditions.interval = this.staticInterval
      this.conditions.topN = -999
      this.conditions.bottomN = -999
    },
    /**
     * @Description  : handleTableLabel
     * @author       : ls
     * @date         : 2020/5/9 16:47
     * @param        :
     * @return       :
     */
    handleTableLabel: function () {
      this.tableLabel = []
      // for (let i = 0; i < this.performListStatistics.length; i++) {
      //   let flag1 = 0 // 标记该维度是否已经存在在表头列表中了，0是不存在
      //   for (let j = 0; j < this.tableLabel.length; j++) {
      //     if (this.tableLabel[j].label === this.performListStatistics[i][1]) {
      //       flag1 = 1
      //     }
      //   }
      //   // 判断，如果不存在就把该维度添加到表头列表当中
      //   if (flag1 === 0) {
      //     let map = {}
      //     map['label'] = this.performListStatistics[i][1]
      //     map['width'] = ''
      //     map['prop'] = this.performListStatistics[i][1]
      //     // TODO：设备类型时应剔除 "."
      //     if (this.valueY === 'deviceModel') {
      //       let propList = this.performListStatistics[i][1].split('.')
      //       map['prop'] = propList.join('')
      //     }
      //     this.tableLabel.push(map)
      //   }
      // }
      for (var k = 0; k < this.showData.length; k++) {
        this.tableLabel.push(
          {
            label: this.showData[k],
            width: '',
            prop: this.showDataY[k]
          }
        )
      }
    },
    /**
     * @Description  : 导入模板
     * @author       : ls
     * @date         : 2020/6/8 11:30
     * @param        :
     * @return       :
     */
    importFile: function () {
      this.innerVisible = true
    },
    /**
       * ---------------------------导出功能实现---------------------------
       * */
    exportFile () {
      if (this.performListStatistics.length === 0) {
        this.InfoTip.warningTip_alarm(this, {message: '暂无统计结果!'})
      } else {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
          target: document.querySelector('.el-row')
        })
        if (this.activeName === 'first') {
          HelperUtil.downloadExcel('性能趋势统计报表.xlsx')
        } else {
          HelperUtil.downloadImage()
        }
        loading.close()
      }
    },
    // table download
    exportExcel () {
      this.exportName1()
      /* generate workbook object from table */
      var wb = XLSX.utils.table_to_book(document.querySelector('#myTable'))
      /* get binary string as output */
      var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'})
      try {
        FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), this.exportName)
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },

    // 导出名称
    exportName1: function () {
      let aspect = ''
      for (let i = 0; i < this.optionsAspect.length; i++) {
        if (this.optionsAspect[i].value === this.valueAspect) {
          aspect = this.optionsAspect[i].label
        }
      }
      this.exportName = this.exportName + '-统计维度-' + aspect + '.xlsx'
    }
  },
  components: {
    ImportReportTemplate
  },
  watch: {
    templateType: {
      handler () {
        this.valueX = ''
        this.valueY = ''
        this.valueType = ''
        this.deviceModel = []
        this.deviceName = []
        this.deviceBrand = []
        this.deviceType = []
        this.deviceParam = []
        this.valueX = this.templateType.statDimensionX
        this.valueY = this.templateType.statDimensionY
        this.valueType = this.templateType.statType
        this.conditionShowFlag = true
        var arr = (this.templateType.filterValue.indexOf(';') !== -1) ? this.templateType.filterValue.split(';') : this.templateType.filterValue.split()
        var obj = {}
        for (var t = 0; t < arr.length; t++) {
          var arr1 = []
          arr1 = arr[t].split('@#')
          obj[arr1[0]] = arr1[2]
        }
        if (obj.hasOwnProperty('deviceTypeKey')) {
          this.deviceType = obj['deviceTypeKey'].split(',')
        }
        if (obj.hasOwnProperty('deviceModel')) {
          this.deviceModel = obj['deviceModel'].split(',')
        }
        if (obj.hasOwnProperty('displayName')) {
          this.deviceName = obj['displayName'].split(',')
        }
        if (obj.hasOwnProperty('brand')) {
          this.deviceBrand = obj['brand'].split(',')
        }
        if (obj.hasOwnProperty('deviceParam')) {
          this.deviceParam = obj['deviceParam'].split(',')
        }
      }
    },
    dataList: {
      handler () {
        if (this.activeName === 'first' && this.echartLine !== null) {
          this.chartTypeChange()
        }
      }
    }
  }
}
</script>

<style>
</style>
