<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.staticDimension") }}</label>
              <el-select size='mini' v-model="staticDimension"
                         placeholder="请选择">
                <el-option
                  v-for="item in chooseAlarmItem"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled">
                </el-option>
              </el-select>
            </div>
            <div class="search-input-box">
              <el-radio-group v-model='topBottom'>
                <el-radio label=0>{{$t("AlarmStatistics.top")}}</el-radio>
                <el-radio label=1 style="margin-left: -20px">{{$t("AlarmStatistics.bottom")}}</el-radio>
              </el-radio-group>
            </div>
            <div style="display: inline-block">
              <el-input-number v-model="num" size="small" style="width: 100px" :min='1' :step=10 controls-position="right"></el-input-number>
            </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("AlarmStatistics.AlarmCause") }}</label>
              <el-select size='mini' v-model="alarmCause"
                         multiple
                         collapse-tags>
                <el-option
                  v-for="item in optionsAlarmCause"
                  :key="item.alarmCode"
                  :label="item.alarmName"
                  :value="item.alarmCode">
                </el-option>
              </el-select>
            </div>
            <div class="search-input-box">
              <label>{{ $t("AlarmStatistics.AlarmLevel") }}</label>
              <el-select size='mini' v-model="alarmLevel"
                         multiple
                         collapse-tags
                         placeholder="请选择">
                <el-option
                  v-for="item in optionsAlarmLevel"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div class="search-input-box">
              <label>{{ $t("AlarmStatistics.AlarmStatus") }}</label>
              <el-select size='mini' v-model="alarmStatus"
                         multiple
                         collapse-tags
                         placeholder="请选择">
                <el-option
                  v-for="item in optionsAlarmStauts"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div class="search-input-box">
              <label>{{ $t("AlarmStatistics.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("AlarmStatistics.DeviceType1") }}</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("AlarmStatistics.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.displayName">
                </el-option>
              </el-select>
            </div>
<!--            <div class="search-input-box">-->
<!--              <label>{{ $t("AlarmStatistics.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.deviceModelKey">-->
<!--                </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-for="(item, index) in tableLabel"
                :key="index"
                :prop="item.prop"
                :width="item.width"
                :label="item.label"
              >
              </el-table-column>
              <el-table-column
                v-if="this.showFlag"
                :prop="$t('AlarmStatistics.alarmCount')"
                :label="$t('AlarmStatistics.alarmCount')">
              </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="2">
    </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 elementResizeDetectorMaker from 'element-resize-detector'
import Echart from 'echarts'
import ImportReportTemplate from "./ImportReportTemplate";

export default {
  name: 'AlarmTopBottomStatisticReport',
  data: function () {
    return {
      conditionShowFlag: false,
      msg: this.$t('AlarmStatistics.exportStatisticResult'),
      staticDimension: 'displayName',
      topBottom: '0',
      num: 20,
      showFlag: false,
      optionsAlarmCause: [],
      chartType: 'pie',
      chartTypeList: [
        {
          value: 'pie',
          label: this.$t('AlarmStatistics.pie')
        },
        {
          value: 'line',
          label: this.$t('AlarmStatistics.line')
        },
        {
          value: 'bar',
          label: this.$t('AlarmStatistics.bar')
        }
      ],
      // 导出文件名称
      exportName: '告警统计结果',

      // Tab页
      activeName: 'first',
      chooseAlarmItem: [
        {
          value: 'displayName',
          label: this.$t('AlarmStatistics.deviceName')
        },
        {
          value: 'deviceTypeKey',
          label: this.$t('AlarmStatistics.deviceType')
        },
        {
          value: 'deviceModel',
          label: this.$t('AlarmStatistics.deviceModel')
        },
        {
          value: 'brand',
          label: this.$t('AlarmStatistics.deviceBrand')
        },
        {
          value: 'alarmCode',
          label: this.$t('AlarmStatistics.cause')
        },
      ],
      valueAspect: 'alarmLevel', // 统计维度
      // 告警等级选择域
      optionsAlarmLevel: [{
        value: 0,
        label: this.$t('ReportTemplateManagement.warn')
      }, {
        value: 1,
        label: this.$t('ReportTemplateManagement.serve')
      }, {
        value: 2,
        label: this.$t('ReportTemplateManagement.urgency')
      }
      ],
      // 告警状态选择域
      optionsAlarmStauts: [{
        value: 0,
        label: this.$t('AlarmStatistics.Notconfirmed')
      }, {
        value: 1,
        label: this.$t('AlarmStatistics.Confirmed')
      }, {
        value: 2,
        label: this.$t('AlarmStatistics.Cleared')
      }, {
        value: 3,
        label: this.$t('AlarmStatistics.Restored')
      }, {
        value: 4,
        label: this.$t('AlarmStatistics.Delete')
      }
      ],
      // 设备类型选择域
      deviceList: [],
      deviceTypeList: [],
      deviceModelList: [],
      deviceList0: [],
      deviceModelList0: [],
      deviceModelList1: [],
      alarmListStatistics: [],
      labelList: '',

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

      // 双向绑定数据
      deviceBrand: [], // 设备类型
      deviceModel: [], // 设备类型
      deviceType: [], // 设备类型
      deviceName: [], // 设备名称
      alarmCause: [], // 告警原因
      alarmStatus: [], // 状态：0未确认；1已确认；2已清除；3已恢复
      alarmLevel: [], // 告警等级
      // 统计条件
      t1: [],
      se: [],
      showData: [],
      dataList: [],
      dataList1: [],
      statisticsList: [],
      conditions: {},
      echartLine: null,
      echartPie: null,
      tableLabel: [],
      pageSize: 20,
      currentPage: 1,
      total: 0,

      check: null,
      innerVisible: false,
      templateType: {},
      title: this.$t('ReportTemplateManagement.alarmTopBottom')
    }
  },
  created: function () {
    this.check = legitimacyCheck()
    this.setDefaultDateTime()
    this.getAlarmTypeList()
    this.getAllDevice()
    this.getAllDeviceModel()
    this.getAllDeviceType()
  },
  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  : 初始化
     * @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',
            formatter: function (params) {
              var res = ''
              for (var i = 0, l = params.length; i < l; i++) {
                res += params[i].seriesName + '<br/>' + params[i].data[0] + ':' + params[i].data[1]
              }
              return res
            }
          },
          color: ['#7cb5ec', '#f7a35c', '#175BE3', '#008000',
            '#0366CB', '#e4d354', '#8085e8', '#8d4653', '#91e8e1'],
          grid: {
            bottom: '80'
          },
          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/11 18:23
     * @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/11 18:32
     * @param        :
     * @return       :
     */
    chartTypeChange: function () {
      switch (this.chartType) {
        case 'pie':
          this.closeAll()
          this.echartPieInit()
          break
        default:
          this.closeAll()
          this.chartInit()
          this.genChart()
      }
    },
    /**
     * @Description  : echartPieInit
     * @author       : ls
     * @date         : 2020/5/11 18:40
     * @param        :
     * @return       :
     */
    echartPieInit: function () {
      this.chartPieInit()
      this.genChartPie()
    },
    /**
     * @Description  : chartPieInit
     * @author       : ls
     * @date         : 2020/5/11 18:56
     * @param        :
     * @return       :
     */
    chartPieInit: function () {
      var div_e = document.getElementById('staticId')
      this.echartPie = Echart.init(div_e)
      this.echartPie.setOption(
        {
          animation: true,
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          color: ['#7cb5ec', '#f7a35c', '#175BE3', '#008000',
            '#0366CB', '#e4d354', '#8085e8', '#8d4653', '#91e8e1'],
          legendHoverLink: false,
          top: '40%',
          bottom: '5%',
          toolbox: {
            show: true,
            orient: 'horizontal',
            // orient: 'vertical',
            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  : genChartPie
     * @author       : ls
     * @date         : 2020/5/11 18:57
     * @param        :
     * @return       :
     */
    genChartPie: function () {
      this.se = []
      var pieData = []
      this.alarmListStatistics.map(function (val) {
        pieData.push({
          value: val[1],
          name: val[0]
        })
      })
      this.se.push({
        type: this.chartType,
        name: this.labelList,
        radius: '67%',
        data: pieData
      })
      this.echartPie.setOption({
        series: this.se,
        legend: {
          left: 'center',
          top: '30'
        },
        title: {
          text: 'TopBottom告警统计',
          x: 'center'
        }
      })
    },
    /**
     * @Description  : 获取数据
     * @author       : ls
     * @date         : 2020/5/7 16:02
     * @param        :
     * @return       :
     */
    getData: function (item) {
      this.chartData.length = 0
      var ret = []
      // this.dataList.map(function (val) {
      //   ret.push([val.time, val.item])
      // })

      for (var i = 0; i < this.dataList.length; i++) {
        ret.push(this.dataList[i][item])
        // ret.push([this.dataList[i].time, this.dataList[i][item]])
      }
      return ret
    },
    /**
     * @Description  : 绘图
     * @author       : ls
     * @date         : 2020/5/7 16:13
     * @param        :
     * @return       :
     */
    genChart: function () {
      this.se = []
      if (this.chartType === 'pie') {
        var pieData = []
        this.alarmListStatistics.map(function (val) {
          pieData.push({
            value: val[1],
            name: val[0]
          })
        })
        this.se.push({
          type: this.chartType,
          name: this.labelList,
          data: pieData
        })
      } else {
        this.se.push({
          type: this.chartType,
          name: this.labelList,
          data: this.alarmListStatistics
        })
      }
      this.echartLine.setOption({
        series: this.se,
        legend: {
          left: 'center',
          top: 30
        },
        title: {
          text: 'TopBottom告警统计',
          x: 'center'
        },
        yAxis: {
          name: '告警次数',
          type: 'value',
          max: function (value) {
            return value.max
          },
          minInterval: 1
        },
        xAxis:
          {
            type: 'category',
            // data: this.getData1(),
            splitLine: {
              show: false
            },
            boundaryGap: ['10%', '10%'],
          }
      })
    },
    /**
     * @Description  : 统计数据
     * @author       : ls
     * @date         : 2020/5/7 15:44
     * @param        :
     * @return       :
     */
    staticsData: function () {
      this.setStatisticsList()
      this.switchLabel()
      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.alarmListStatistics = Object.values(result)
        _this.Loading.closeLoading(loadingInstance)
        if (_this.alarmListStatistics.length > 0) {
          this.showFlag = true
          _this.alarmListStatisticsInit()
        } 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  : closeAll
     * @author       : ls
     * @date         : 2020/5/11 18:10
     * @param        :
     * @return       :
     */
    closeAll: function () {
      if (this.echartLine) {
        this.echartLine.clear()
      }
      if (this.echartPie) {
        this.echartPie.clear()
      }
    },
    /**
     * @Description  : 初始化
     * @author       : ls
     * @date         : 2020/5/8 19:15
     * @param        :
     * @return       :
     */
    alarmListStatisticsInit: function () {
      this.genData()
      this.handleTableLabel()
      this.handleTotal()
      if (this.activeName === 'second') {
        this.chartTypeChange()
      }
    },
    /**
     * @Description  : switchLabel
     * @author       : ls
     * @date         : 2020/5/11 15:02
     * @param        :
     * @return       :
     */
    switchLabel: function () {
      switch (this.staticDimension) {
        case 'deviceTypeKey':
          this.labelList = this.$t('AlarmStatistics.deviceType')
          break
        case 'displayName':
          this.labelList = this.$t('AlarmStatistics.deviceName')
          break
        case 'deviceModel':
          this.labelList = this.$t('AlarmStatistics.deviceModel')
          break
        case 'brand':
          this.labelList = this.$t('AlarmStatistics.deviceBrand')
          break
        case 'alarmCode':
          this.labelList = this.$t('AlarmStatistics.cause')
          break
      }
    },
    /**
     * @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++) {
    //       datas[this.showData[j]] = '0'
    //     }
    //     this.dataList.push(datas)
    //   }
    //   for (let m in this.dataList) {
    //     for (let n in this.alarmListStatistics) {
    //       if (this.dataList[m].time === this.alarmListStatistics[n][0]) {
    //         for (let q = 0; q < this.showData.length; q++) {
    //           if (this.showData[q] === this.alarmListStatistics[n][1]) {
    //             this.dataList[m][this.showData[q]] = this.alarmListStatistics[n][2]
    //           }
    //         }
    //       }
    //     }
    //   }
    // },
    /**
     * @Description  : genData
     * @author       : ls
     * @date         : 2020/5/11 11:54
     * @param        :
     * @return       :
     */
    genData: function () {
      this.dataList = []
      for (var i = 0; i < this.alarmListStatistics.length; i++) {
        var datas = {}
        datas[this.staticDimension] = this.alarmListStatistics[i][0]
        datas['告警次数'] = this.alarmListStatistics[i][1]
        this.dataList.push(datas)
      }
    },
    /**
     * @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/6/8 11:20
     * @param        :
     * @return       :
     */
    importFile: function () {
      this.innerVisible = true
    },
    /**
     * @Description  : 更多条件
     * @author       : ls
     * @date         : 2020/5/7 12:45
     * @param        :
     * @return       :
     */
    moreConditionOr: function () {
      this.conditionShowFlag = !this.conditionShowFlag
      this.resizeAll()
    },
    // 导出按钮显示
    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.echartPie === null) {
          this.$nextTick(function () {
            this.chartTypeChange()
          })
        }
      }
    },
    /**
     * @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')})
      }
    },
    /**
     * @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')})
      }
    },
    /**
     * @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/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/11 10:58
     * @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.alarmCause.length !== 0) {
        this.statisticsList.push({
          quaryAttribute: 'alarmCode',
          compareSymbol: 'in',
          compareValue: this.alarmCause.join(',')
        })
      }
      if (this.alarmLevel.length !== 0) {
        this.statisticsList.push({
          quaryAttribute: 'alarmLevel',
          compareSymbol: 'in',
          compareValue: this.alarmLevel.join(',')
        })
      }
      if (this.alarmStatus.length !== 0) {
        this.statisticsList.push({
          quaryAttribute: 'alarmStatus',
          compareSymbol: 'in',
          compareValue: this.alarmStatus.join(',')
        })
      }
      this.conditions.queryTerms = this.statisticsList
      this.conditions.reportType = 2
      this.conditions.startTime = HelperUtil.getTimeInit(this.beginTimestamp) + this.addTimestamp
      this.conditions.endTime = HelperUtil.getTimeInit(this.endTimestamp) + this.addTimestamp1
      this.conditions.xAxis = this.staticDimension
      this.conditions.yAxis = ''
      this.conditions.aggregateFunc = 4
      this.conditions.interval = -999
      if (this.topBottom === '0') {
        this.conditions.topN = this.num
        this.conditions.bottomN = -999
      } else {
        this.conditions.topN = -999
        this.conditions.bottomN = this.num
      }
    },
    /**
     * @Description  : handleTableLabel
     * @author       : ls
     * @date         : 2020/5/11 14:36
     * @param        :
     * @return       :
     */
    handleTableLabel: function () {
      this.tableLabel = []
      let map = {}
      map['label'] = this.labelList
      map['width'] = ''
      map['prop'] = this.staticDimension
      this.tableLabel.push(map)
    },

    /**
     * @Description  : 导出文件
     * @author       : ls
     * @date         : 2020/5/11 15:36
     * @param        :
     * @return       :
     */
    exportFile () {
      if (this.alarmListStatistics.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('告警TOP/BOTTOM N统计报表.xlsx')
        } else {
          HelperUtil.downloadImage()
        }
        loading.close()
      }
    },
    /**
     * @Description  : 导出表格
     * @author       : ls
     * @date         : 2020/5/11 15:36
     * @param        :
     * @return       :
     */
    exportExcel () {
      this.exportName = '告警TOP/BOTTOM N统计报表' + '.xlsx'
      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
    },
    /**
     * @Description  : resizeAll
     * @author       : ls
     * @date         : 2020/5/12 18:29
     * @param        :
     * @return       :
     */
    resizeAll: function () {
      if (this.chartType === 'pie') {
        this.echartPie.resize()
      } else {
        this.echartLine.resize()
      }
    }
  },
  mounted () {
    this.erd = elementResizeDetectorMaker()
    this.erd.listenTo(document.getElementById('staticId'), this.resizeAll())
  },
  components: {
    ImportReportTemplate
  },
  watch: {
    templateType: {
      handler () {
        this.valueX = ''
        this.valueY = ''
        this.deviceModel = []
        this.deviceName = []
        this.deviceBrand = []
        this.deviceType = []
        this.alarmCause = []
        this.alarmLevel = []
        this.alarmStatus = []
        this.valueX = this.templateType.statDimensionX
        this.valueY = this.templateType.statDimensionY
        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('alarmLevel')) {
          this.alarmLevel = obj['alarmLevel'].split(',').map(Number)
        }
        if (obj.hasOwnProperty('alarmStatus')) {
          this.alarmStatus = obj['alarmStatus'].split(',').map(Number)
        }
        if (obj.hasOwnProperty('alarmCode')) {
          this.alarmCause = obj['alarmCode'].split(',')
        }
        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(',')
        }
      }
    },
    dataList: {
      handler () {
        if (this.activeName === 'first' && this.echartPie !== null) {
          this.chartTypeChange()
        }
      }
    }
  }
}
</script>

<style>
</style>
