<template>
  <div class="app-container power-index-content">
    <el-row type="flex" :gutter="20">
      <el-col :span="24">
        <div class="gl-filters">
          <SwitchTag
              :ds="areaTag"
              :def-tag="defArea"
              :tagClick="onSwitchTagClick"
          />
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <DeviceWaring />
      </el-col>
      <el-col :span="12">
        <LineChartBlock title="历史告警变化" :opt-cfg="devcWarningHis">
          <template v-slot:filters>
            <SwitchTag
                :ds="[{val: 'day', text: '按日'},{val: 'month', text: '按月'},{val: 'year', text: '按年'}]"
                :defTag="dateType"
                :tagClick="onDateTypeSwitch"
            />
          </template>
        </LineChartBlock>
      </el-col>
    </el-row>
    <el-row type="flex" :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <BlockTable title="实时告警" :table-data="realTimeTableData">
          <template v-slot:columns>
            <el-table-column
                type="index"
                label="序号"
                align="center"
            />
            <el-table-column
                prop="subSystemName"
                label="子系统"
                align="center"
            />
            <el-table-column
                prop="objName"
                label="对象名称"
                align="center"
            />
            <el-table-column
                prop="alarmMsg"
                label="描述"
                align="center"
            />
            <el-table-column
                prop="alarmTime"
                label="时间"
                align="center"
            />
            <el-table-column
                label="操作"
                align="center"
                width="100"
            >
              <template slot-scope="scope">
                <el-dropdown @command="(cmd)=>handleCommand(cmd, scope.row)"
                             v-if="![ALARM_STATE.dissolved.value, ALARM_STATE.dissolved.value].includes(scope.row.alarmState)">
          <span class="el-dropdown-link">
            <dict-tag :options="dict.type.alarm_state" :value="scope.row.alarmState"></dict-tag>
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="ALARM_STATE.disposing.code"
                                      v-if="scope.row.alarmState === ALARM_STATE.new.value">开始处理
                    </el-dropdown-item>
                    <el-dropdown-item :command="ALARM_STATE.disposed.code">已处理</el-dropdown-item>
                    <el-dropdown-item :command="ALARM_STATE.dissolved.code">已消散</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </template>
        </BlockTable>
      </el-col>
      <el-col :span="12">
        <BarChartBlock title="告警统计报表" :opt-cfg="subSysIndex">
          <template v-slot:filters>
            <SwitchTag
                :ds="[{val: 'day', text: '按日'},{val: 'month', text: '按月'},{val: 'year', text: '按年'}]"
                :defTag="dateType"
                :tagClick="onSubSysDateTypeSwitch"
            />
          </template>
        </BarChartBlock>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import {
  fetchAlarmIndexDay, fetchAlarmIndexMonth, fetchAlarmIndexYear, fetchSubSysIndexDay, fetchSubSysIndexMonth,
  fetchSubSysIndexYear, listAlarmInfo, updateAlarmInfo,
} from '@/api/alarm/alarm-info';
import { ApiCode } from '@/api/apiEmums';
import Block from '@/components/Block/block.vue';
import BlockTable from '@/components/Block/BlockTable/index.vue';
import BarChartBlock from '@/components/Block/charts/BarChartBlock.vue';
import PieChartBlock from '@/components/Block/charts/PieChartBlock.vue';
import { ALARM_STATE } from '@/enums/alarm';
import { DateTool } from '@/utils/DateTool';
import DeviceWaring from '@/views/analysis/device/DevcWarning/index.vue';
import Tag from '@/views/basecfg/tag/index.vue';
import dayjs from 'dayjs';
import { mapGetters, mapMutations } from 'vuex';
import * as areaApi from '../../../api/basecfg/area';
import LineChartBlock from '../../../components/Block/charts/LineChartBlock.vue';
import SwitchTag from '../../../components/SwitchTag/index.vue';

export default {
  dicts: ['alarm_type', 'alarm_state'],
  components: {
    Tag,
    BlockTable,
    DeviceWaring,
    Block,
    BarChartBlock,
    PieChartBlock,
    LineChartBlock,
    SwitchTag,
  },
  data() {
    return {
      ALARM_STATE,
      areaTag: [],
      defArea: {},
      dateType: { val: 'day' },
      devcWarningHis: {
        unit: '  ',
        xAxis: {
          type: 'category',
          data: [],
        },
        series: [],
      },
      subSysIndex: {
        unit: '  ',
        xAxis: {
          type: 'category',
          data: [],
        },
        series: [],
      },
      realTimeTableData: [],
    };
  },
  computed: {
    // 监听选中的区域，以更新数据
    selectedServiceArea() {
      return this.$store.state.userState.selectedServiceArea;
    },
    ...mapGetters('userState', ['getSelectedArea']),
  },
  watch: {
    selectedServiceArea(val) {
      this.queryCharts();
    },
  },
  mounted() {
    this.initData();
  },
  created() {
  },
  methods: {
    ...mapMutations('userState', ['setSelectedArea']),
    onSwitchTagClick(item) {
      this.setSelectedArea(item);
    },
    async onDateTypeSwitch(item) {
      if (!this.selectedServiceArea) {
        return;
      }
      if (item.val === 'day') {
        const xaxis = DateTool.getTime(60);
        const { data } = await fetchAlarmIndexDay({
          areaCode: this.selectedServiceArea.val,
        });
        const series = this.toSeries(data, xaxis);
        this.devcWarningHis.xAxis.data = xaxis;
        this.devcWarningHis.series = series;
        return;
      }
      if (item.val === 'month') {
        const xaxis = DateTool.getDayOfRange(
            dayjs().subtract(1, 'month'), dayjs(), DateTool.DateFormat.YYYY_MM_DD);
        const { data } = await fetchAlarmIndexMonth({ areaCode: this.selectedServiceArea.val });
        const series = this.toSeries(data, xaxis);
        this.devcWarningHis.xAxis.data = xaxis;
        this.devcWarningHis.series = series;
        return;
      }
      const xaxis = DateTool.getMonthsOfYearAgo();
      const { data } = await fetchAlarmIndexYear({ areaCode: this.selectedServiceArea.val });
      const series = this.toSeries(data, xaxis);
      this.devcWarningHis.xAxis.data = xaxis;
      this.devcWarningHis.series = series;
    },
    async onSubSysDateTypeSwitch(item) {
      if (!this.selectedServiceArea) {
        return;
      }
      if (item.val === 'day') {
        const xaxis = DateTool.getTime(60);
        const { data } = await fetchSubSysIndexDay({
          areaCode: this.selectedServiceArea.val,
        });
        const series = this.subSysIndexToSeries(data, xaxis);
        this.subSysIndex.xAxis.data = xaxis;
        this.subSysIndex.series = series;
        return;
      }
      if (item.val === 'month') {
        const xaxis = DateTool.getDayOfRange(
            dayjs().subtract(1, 'month'), dayjs(), DateTool.DateFormat.YYYY_MM_DD);
        const { data } = await fetchSubSysIndexMonth({ areaCode: this.selectedServiceArea.val });
        const series = this.subSysIndexToSeries(data, xaxis);
        this.subSysIndex.xAxis.data = xaxis;
        this.subSysIndex.series = series;
        return;
      }
      const xaxis = DateTool.getMonthsOfYearAgo();
      const { data } = await fetchSubSysIndexYear({ areaCode: this.selectedServiceArea.val });
      const series = this.subSysIndexToSeries(data, xaxis);
      this.subSysIndex.xAxis.data = xaxis;
      this.subSysIndex.series = series;
    },
    toSeries(data, xaxis) {
      const dayGroup = _.groupBy(data, 'alarmType');
      const series = [];
      Object.keys(dayGroup).forEach((alarmType) => {
        let ds = {};
        let typeName = this.selectDictLabel(this.dict.type.alarm_type, alarmType);
        dayGroup[alarmType].forEach(item => {
          ds[item.dateIndex] = item.cnt;
        });
        let seriesData = [];
        xaxis.forEach((item) => seriesData.push(ds[item] || 0));
        series.push({
          name: typeName,
          type: 'line',
          smooth: true,
          data: seriesData,
        });
      });
      return series;
    },

    subSysIndexToSeries(data, xaxis) {
      const dayGroup = _.groupBy(data, 'systemCode');
      const series = [];
      Object.keys(dayGroup).forEach((subSysCode) => {
        let ds = {};
        let systemName = dayGroup[subSysCode][0].systemName;
        dayGroup[subSysCode].forEach(item => {
          ds[item.dateIndex] = item.cnt;
        });
        let seriesData = [];
        xaxis.forEach((item) => seriesData.push(ds[item] || 0));
        series.push({
          name: systemName,
          type: 'bar',
          data: seriesData,
        });
      });
      return series;
    },
    async initData() {
      const {
        rows,
        total,
      } = await areaApi.listArea({
        pageNum: 1,
        pageSize: 10,
      });
      if (rows.length > 0) {
        rows.forEach(item => {
          this.areaTag.push({
            val: item.areaCode,
            text: item.areaName,
          });
        });
        this.defArea = this.areaTag[0];
        this.setSelectedArea(this.areaTag[0]);
      }
      this.queryCharts();
    },
    queryCharts() {
      this.onDateTypeSwitch(this.dateType);
      this.onSubSysDateTypeSwitch(this.dateType);
      this.getRealTimeAlarm();
    },
    async getRealTimeAlarm() {
      let result = [];
      const {
        code,
        rows,
      } = await listAlarmInfo({
        pageNum: 1,
        pageSize: 10,
        areaCode: this.selectedServiceArea.val,
        alarmStateList: [
          ALARM_STATE.new.value, ALARM_STATE.disposing.value,
        ],
      });
      if (ApiCode.SUCCESS === code && rows && rows.length > 0) {
        result = rows;
      }
      this.realTimeTableData = result;
    },
    async handleCommand(command, data) {
      debugger
      await updateAlarmInfo({
        id: data.id,
        alarmState: ALARM_STATE[command].value,
      });
      await this.getRealTimeAlarm();
    },
  },
};
</script>
<style src="./index.scss" lang="scss" />
