<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.X") }}</label>
              <el-select size='mini' v-model="valueX"
                         @change="valueXChange"
                         placeholder="请选择">
                <el-option
                  v-for="item in valueList"
                  :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"
                         placeholder="请选择"
                         @change="valueYChange">
                <el-option
                  v-for="item in valueList"
                  :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("AlarmStatistics.AlarmCause") }}</label>
              <el-select size='mini' v-model="alarmCause"
                         multiple
                         collapse-tags
                         placeholder="请选择">
                <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.deviceKey">
                </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.deviceModel">-->
<!--                </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="dataList"
              stripe
              tooltip-effect="dark"
              height="auto"
              border
              :highlight-current-row="true">
              <el-table-column
                v-if="this.showFlag"
                type="index"
                :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>
            <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 id="staticId" style="height: 100%">
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
    <ImportReportTemplate :innerVisible.sync="innerVisible"
                          :templateType.sync=templateType
                          :title="title"
                          :detailType="0">
    </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 ImportReportTemplate from '../StatementManagement/ImportReportTemplate'
import HelperUtil from '../../utils/HelperUtil'
import legitimacyCheck from '../../utils/legitimacyCheck'
import Echart from 'echarts'
import elementResizeDetectorMaker from 'element-resize-detector'

export default {
  name: 'AlarmDistributionStatisticReport',
  data: function () {
    return {
      conditionShowFlag: false,
      msg: this.$t('AlarmStatistics.exportStatisticResult'),
      valueX: 'alarmCode',
      valueY: 'alarmLevel',
      // Table表头
      deviceNameShow: false,
      causeShow: false,
      alarmLevelShow: true,
      alarmStatusShow: false,
      // 导出文件名称
      exportName: '告警统计结果',

      // Tab页
      activeName: 'first',
      se: [],
      chartType: 'bar',
      optionsAlarmCause: [],
      alarmListStatistics: [],
      chartTypeList: [
        {
          value: 'bar',
          label: this.$t('AlarmStatistics.bar')
        },
        {
          value: 'line',
          label: this.$t('AlarmStatistics.line')
        }
      ],
      valueList: [
        {
          value: 'alarmCode',
          label: this.$t('AlarmStatistics.cause')
        },
        {
          value: 'alarmLevel',
          label: this.$t('AlarmStatistics.alarmLevel')
        },
        {
          value: 'alarmStatus',
          label: this.$t('AlarmStatistics.alarmStatus')
        },
        {
          value: 'deviceTypeKey',
          label: this.$t('AlarmStatistics.deviceType')
        },
        {
          value: 'deviceModel',
          label: this.$t('AlarmStatistics.deviceModel')
        },
        {
          value: 'displayName',
          label: this.$t('AlarmStatistics.deviceName')
        },
        {
          value: 'brand',
          label: this.$t('AlarmStatistics.deviceBrand')
        }
      ],
      // 统计维度
      optionsAspect: [
        {
          value: 'displayName',
          label: this.$t('AlarmStatistics.deviceKey'),
          disabled: false
        },
        {
          value: 'deviceModel',
          label: this.$t('AlarmStatistics.deviceType'),
          disabled: false
        },
        {
          value: 'alarmCode',
          label: this.$t('AlarmStatistics.alarmType'),
          disabled: false
        },
        {
          value: 'alarmLevel',
          label: this.$t('AlarmStatistics.alarmLevel1'),
          disabled: false
        },
        {
          value: 'alarmStatus',
          label: this.$t('AlarmStatistics.alarmStatus1'),
          disabled: false
        }
      ],
      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: [],

      // 日期控件
      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: [], // 告警等级
      dataList: [],
      dataList1: [],
      pageSize: 20,
      currentPage: 1,
      total: 0,
      showFlag: false,
      tableLabel: [],
      // 统计条件
      statisticsList: [],
      conditions: {},
      chartData: [],
      showData: [],
      showYAxis: [],
      showYAxisY: [],
      t1: [],
      erd: null,
      xData: [],
      echartLine: null,
      echartPie: null,
      check: null,
      innerVisible: false,
      templateType: {},
      title: this.$t('ReportTemplateManagement.alarmDistribution')
    }
  },
  created: function () {
    this.check = legitimacyCheck()
    this.setDefaultDateTime()
    this.getAlarmTypeList()
    this.getAllDevice()
    this.getAllDeviceModel()
    this.getAllDeviceType()
  },
  methods: {
    /**
     * @Description  : handleSizeChange
     * @author       : ls
     * @date         : 2020/5/15 11:46
     * @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/6/3 10:02
     * @param        :
     * @return       :
     */
    importFile: function () {
      this.innerVisible = true
    },
    /**
     * @Description  : 图标切换
     * @author       : ls
     * @date         : 2020/6/3 10:03
     * @param        :
     * @return       :
     */
    chartTypeChange: function () {
      this.closeAll()
      this.chartInit()
      this.genChart()
    },
    /**
     * @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', '#434348', '#90ed7d', '#8085e9',
            '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1'],
          grid: {
            bottom: '10%'
          },
          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  : 去重
     * @author       : ls
     * @date         : 2020/6/3 11:59
     * @param        :
     * @return       :
     */
    unique: function (arr) {
      return Array.from(new Set(arr))
    },
    handleData: function () {
      this.t1 = []
      for (var i = 0; i < this.showData.length; i++) {
        this.t1.push(this.showData[i])
      }
    },
    /**
     * @Description  : 获取数据
     * @author       : ls
     * @date         : 2020/5/7 16:02
     * @param        :
     * @return       :
     */
    getData: function () {
      this.unique(this.alarmListStatistics.map(function (val) {
        return val[1]
      }))
      this.chartData = []
      this.xData = []
      for (var i = 0; i < this.alarmListStatistics.length; i++) {
        this.chartData.push(this.alarmListStatistics[i][2])
        this.xData.push(this.alarmListStatistics[i][0])
      }
    },
    /**
     * @Description  : loadData
     * @author       : ls
     * @date         : 2020/5/12 9:39
     * @param        :
     * @return       :
     */
    loadData: function () {
      let _this = this
      let loadingInstance = _this.Loading.openLoading()
      AlarmManagerService.queryReportService(this.conditions).then(result => {
        // _this.alarmListStatistics = Object.values(result)
        _this.alarmListStatistics = 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  : alarmListStatisticsInit
     * @author       : ls
     * @date         : 2020/5/15 11:10
     * @param        :
     * @return       :
     */
    alarmListStatisticsInit: function () {
      if (this.valueY === 'alarmLevel') {
        for (var index = 0; index < this.alarmListStatistics.length; index++) {
          if (this.alarmListStatistics[index][1] === 0) {
            this.alarmListStatistics[index][1] = this.$t('AlarmStatistics.MinorAlarm')
          } else if (this.alarmListStatistics[index][1] === 1) {
            this.alarmListStatistics[index][1] = this.$t('AlarmStatistics.MajorAlarm')
          } else if (this.alarmListStatistics[index][1] === 2) {
            this.alarmListStatistics[index][1] = this.$t('AlarmStatistics.CriticalAlarm')
          }
        }
      }
      if (this.valueY === 'alarmStatus') {
        for (var idf = 0; idf < this.alarmListStatistics.length; idf++) {
          if (this.alarmListStatistics[idf][1] === 0) {
            this.alarmListStatistics[idf][1] = this.$t('AlarmStatistics.Notconfirmed')
          } else if (this.alarmListStatistics[idf][1] === 1) {
            this.alarmListStatistics[idf][1] = this.$t('AlarmStatistics.Confirmed')
          } else if (this.alarmListStatistics[idf][1] === 2) {
            this.alarmListStatistics[idf][1] = this.$t('AlarmStatistics.Cleared')
          } else if (this.alarmListStatistics[idf][1] === 3) {
            this.alarmListStatistics[idf][1] = this.$t('AlarmStatistics.Restored')
          } else if (this.alarmListStatistics[idf][1] === 4) {
            this.alarmListStatistics[idf][1] = this.$t('AlarmStatistics.Delete')
          }
        }
      }
      if (this.valueX === 'alarmLevel') {
        for (var m = 0; m < this.alarmListStatistics.length; m++) {
          if (this.alarmListStatistics[m][0] === 0) {
            this.alarmListStatistics[m][0] = this.$t('AlarmStatistics.MinorAlarm')
          } else if (this.alarmListStatistics[m][0] === 1) {
            this.alarmListStatistics[m][0] = this.$t('AlarmStatistics.MajorAlarm')
          } else if (this.alarmListStatistics[m][0] === 2) {
            this.alarmListStatistics[m][0] = this.$t('AlarmStatistics.CriticalAlarm')
          }
        }
      }
      if (this.valueX === 'alarmStatus') {
        for (var n = 0; n < this.alarmListStatistics.length; n++) {
          if (this.alarmListStatistics[n][0] === 0) {
            this.alarmListStatistics[n][0] = this.$t('AlarmStatistics.Notconfirmed')
          } else if (this.alarmListStatistics[n][0] === 1) {
            this.alarmListStatistics[n][0] = this.$t('AlarmStatistics.Confirmed')
          } else if (this.alarmListStatistics[n][0] === 2) {
            this.alarmListStatistics[n][0] = this.$t('AlarmStatistics.Cleared')
          } else if (this.alarmListStatistics[n][0] === 3) {
            this.alarmListStatistics[n][0] = this.$t('AlarmStatistics.Restored')
          } else if (this.alarmListStatistics[n][0] === 4) {
            this.alarmListStatistics[n][0] = this.$t('AlarmStatistics.Delete')
          }
        }
      }
      this.showData = this.unique(this.alarmListStatistics.map(function (val) {
        return val[0]
      }))
      this.showYAxis = this.unique(this.alarmListStatistics.map(function (val) {
        return val[1]
      }))
      this.showYAxisY = []
      for (var k = 0; k < this.showYAxis.length; k++) {
        if (this.showYAxis[k].indexOf('.') !== -1) {
          this.showYAxisY.push(this.showYAxis[k].split('.').join(''))
        } else {
          this.showYAxisY.push(this.showYAxis[k])
        }
      }
      this.handleData()
      // this.genData()
      this.genData2()
      // this.getData()
      this.handleTableLabel()
      this.handleTotal()
      if (this.activeName === 'second') {
        this.chartTypeChange()
      }
    },
    /**
     * @Description  : 生成数据
     * @author       : ls
     * @date         : 2020/6/3 9:38
     * @param        :
     * @return       :
     */
    genData: function () {
      this.dataList = []
      for (var i = 0; i < this.alarmListStatistics.length; i++) {
        for (var j = 0; j < this.showData.length; j++) {
          var datas = {}
          if (this.showData[j] === this.alarmListStatistics[i][0]) {
            datas[this.valueX] = this.alarmListStatistics[i][0]
            datas[this.showData[j]] = this.alarmListStatistics[i][2]
            this.dataList.push(datas)
            break
          }
        }
      }
      for (var k = 0; k < this.alarmListStatistics.length; k++) {
        for (var t = 0; t < this.showData.length; t++) {
          if (this.dataList[k][this.showData[t]] === undefined) {
            this.dataList[k][this.showData[t]] = 0
          }
        }
      }
    },
    /**
     * @Description  : 处理数据
     * @author       : ls
     * @date         : 2020/6/5 14:47
     * @param        :
     * @return       :
     */
    genData2: function () {
      this.dataList = []
      for (var i = 0; i < this.t1.length; i++) {
        var datas = {}
        datas[this.valueX] = this.t1[i]
        for (var j = 0; j < this.showYAxis.length; j++) {
          // if (this.valueY === 'deviceModel') {
          //   var val = ''
          //   val = this.showYAxis[j].split('.').join('')
          //   datas[val] = '0'
          // } else {
          //   datas[this.showYAxis[j]] = '0'
          // }
          datas[this.showYAxisY[j]] = '0'
        }
        this.dataList.push(datas)
      }
      for (let m in this.dataList) {
        for (let n in this.alarmListStatistics) {
          if (this.dataList[m][this.valueX] === this.alarmListStatistics[n][0]) {
            for (let q = 0; q < this.showYAxis.length; q++) {
              if (this.showYAxis[q] === this.alarmListStatistics[n][1]) {
                // if (this.valueY === 'deviceModel') {
                //   var val1 = ''
                //   val1 = this.showYAxis[q].split('.').join('')
                //   this.dataList[m][val1] = this.alarmListStatistics[n][2]
                // } else {
                //   this.dataList[m][this.showYAxis[q]] = this.alarmListStatistics[n][2]
                // }
                this.dataList[m][this.showYAxisY[q]] = this.alarmListStatistics[n][2]
              }
            }
          }
        }
      }
    },
    /**
     * @Description  : closeAll
     * @author       : ls
     * @date         : 2020/5/12 9:46
     * @param        :
     * @return       :
     */
    closeAll: function () {
      if (this.echartLine) {
        this.echartLine.clear()
      }
    },
    /**
     * @Description  : 绘图
     * @author       : ls
     * @date         : 2020/5/7 16:13
     * @param        :
     * @return       :
     */
    genChart: function () {
      this.xData = []
      this.se = []
      for (var i = 0; i < this.showYAxis.length; i++) {
        this.chartData = []
        for (var j = 0; j < this.dataList.length; j++) {
          this.chartData.push(this.dataList[j][this.showYAxisY[i]])
        }
        this.se.push(
          {
            type: this.chartType,
            name: this.showYAxis[i],
            data: this.chartData
          }
        )
      }
      this.echartLine.setOption({
        series: this.se,
        legend: {
          left: 'center',
          top: 30
        },
        title: {
          text: '告警分布统计',
          x: 'center'
        },
        yAxis: {
          name: '告警次数',
          minInterval: 1,
          type: 'value'
        },
        xAxis:
          {
            type: 'category',
            data: this.showData,
            splitLine: {
              show: false
            },
            boundaryGap: ['10%', '10%'],
            axisLabel: {
              showMinLabel: true,
              showMaxLabel: true
            }
          }
      })
    },
    /**
     * @Description  : 校验
     * @author       : ls
     * @date         : 2020/6/4 16:46
     * @param        :
     * @return       :
     */
    submitCheck: function () {
      if (this.valueY === this.valueX) {
        this.InfoTip.warningTip_alarm(this, HelperUtil.getCheckStatusCodeObjectByCode(this.successCode.NOT_EQUAL))
        return false
      }
      return true
    },
    /**
     * @Description  : check
     * @author       : ls
     * @date         : 2021/2/20 23:26
     * @param        :
     * @return       :
     */
    checks: function () {
      if (this.valueX === '') {
        var obj = {}
        obj.message = '轴系列输入不能为空！'
        this.InfoTip.warningTip_alarm(this, obj, 'X')
        return false
      }
      if (this.valueY === '') {
        var obj1 = {}
        obj1.message = '轴系列输入不能为空！'
        this.InfoTip.warningTip_alarm(this, obj1, 'Y')
        return false
      }
      return true
    },
    /**
     * @Description  : 统计数据
     * @author       : ls
     * @date         : 2020/5/7 15:44
     * @param        :
     * @return       :
     */
    staticsData: function () {
      if (!this.checks()) {
        return
      }
      this.setStatisticsList()
      this.loadData()
    },
    /**
     * @Description  : y转换
     * @author       : ls
     * @date         : 2020/5/12 10:03
     * @param        :
     * @return       :
     */
    switchLabel: function () {
      // switch (this.valueY) {
      //   case "alarmCause":
      //     this.labelList =
      //
      // }
    },
    /**
     * @Description  : 设置统计条件
     * @author       : ls
     * @date         : 2020/5/12 9:30
     * @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 = 0
      this.conditions.startTime = HelperUtil.getTimeInit(this.beginTimestamp) + this.addTimestamp
      this.conditions.endTime = HelperUtil.getTimeInit(this.endTimestamp) + this.addTimestamp1
      this.conditions.xAxis = this.valueX
      this.conditions.yAxis = this.valueY
      this.conditions.aggregateFunc = 4
      this.conditions.interval = -999
      this.conditions.topN = -999
      this.conditions.bottomN = -999
    },
    /**
     * @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  : 更多条件
     * @author       : ls
     * @date         : 2020/5/7 12:45
     * @param        :
     * @return       :
     */
    moreConditionOr: function () {
      this.conditionShowFlag = !this.conditionShowFlag
      this.resizeAll()
    },
    /**
     * @Description  : 导出按钮提示
     * @author       : ls
     * @date         : 2020/5/15 11:52
     * @param        :
     * @return       :
     */
    handleClick (activeName, oldActiveName) {
      if (activeName === 'first') {
        this.msg = this.$t('AlarmStatistics.exportStatisticResult')
      } else {
        this.msg = this.$t('AlarmStatistics.exportStatisticGraph1')
      }
      return true
    },
    /**
     * @Description  : handleClick1
     * @author       : ls
     * @date         : 2020/5/15 11:52
     * @param        :
     * @return       :
     */
    handleClick1 () {
      if (this.activeName === 'second' && this.dataList.length !== 0) {
        if (this.echartLine === 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')})
      }
      // 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/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  : handleTableLabel
     * @author       : ls
     * @date         : 2020/5/15 11:33
     * @param        :
     * @return       :
     */
    handleTableLabel: function () {
      this.tableLabel = []
      switch (this.valueX) {
        case 'alarmCode':
          this.tableLabel.push(
            {
              'label': this.$t('AlarmStatistics.cause'),
              'prop': 'alarmCode'
            }
          )
          break
        case 'alarmLevel':
          this.tableLabel.push(
            {
              'label': this.$t('AlarmStatistics.alarmLevel'),
              'prop': 'alarmLevel'
            }
          )
          break
        case 'alarmStatus':
          this.tableLabel.push(
            {
              'label': this.$t('AlarmStatistics.alarmStatus'),
              'prop': 'alarmStatus'
            }
          )
          break
        case 'displayName':
          this.tableLabel.push(
            {
              'label': this.$t('AlarmStatistics.deviceName'),
              'prop': 'displayName'
            }
          )
          break
        case 'deviceModel':
          this.tableLabel.push(
            {
              'label': this.$t('AlarmStatistics.deviceModel'),
              'prop': 'deviceModel'
            }
          )
          break
        case 'deviceTypeKey':
          this.tableLabel.push(
            {
              'label': this.$t('AlarmStatistics.deviceType'),
              'prop': 'deviceTypeKey'
            }
          )
          break
        case 'brand':
          this.tableLabel.push(
            {
              'label': this.$t('AlarmStatistics.brand'),
              'prop': 'brand'
            }
          )
          break
      }
      // for (let i = 0; i < this.alarmListStatistics.length; i++) {
      //   let flag1 = 0 // 标记该维度是否已经存在在表头列表中了，0是不存在
      //   for (let j = 0; j < this.tableLabel.length; j++) {
      //     if (this.tableLabel[j].label === this.alarmListStatistics[i][1]) {
      //       console.log(this.tableLabel)
      //       flag1 = 1
      //     }
      //   }
      //   // 判断，如果不存在就把该维度添加到表头列表当中
      //   if (flag1 === 0) {
      //     let map = {}
      //     map['label'] = this.alarmListStatistics[i][1]
      //     map['width'] = ''
      //     map['prop'] = this.alarmListStatistics[i][1]
      //     // TODO：设备类型时应剔除 "."
      //     if (this.valueY === 'deviceModel') {
      //       let propList = this.alarmListStatistics[i][1].split('.')
      //       map['prop'] = propList.join('')
      //     }
      //     this.tableLabel.push(map)
      //   }
      // }

      for (let k = 0; k < this.showYAxis.length; k++) {
        this.tableLabel.push(
          {
            label: this.showYAxis[k],
            width: '',
            prop: this.showYAxisY[k]
          }
        )
      }
    },

    /**
       * ---------------------------导出功能实现---------------------------
       * */
    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('告警分布统计报表.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'
    },
    /**
     * @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())
    window.onresize('resize', function () {
      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.echartLine !== null) {
          this.chartTypeChange()
        }
      }
    }
  }
}
</script>

<style>
</style>
