<template>
  <div class="app-container power-index-content">
    <el-row :gutter="10">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="areaName" placeholder="请输入服务区名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree ref="tree" :data="areaOptions" :default-expand-all="true" :expand-on-click-node="false"  :filter-node-method="filterNode" node-key="id" highlight-current @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-row :gutter="20">
          <el-col :span="12">
            <DeviceWaring />
          </el-col>
          <el-col :span="12">
            <LineChartBlock title="历史告警变化" :opt-cfg="devcWarningHis">
              <template v-slot:filters>
                <SwitchTag :ds="[{ val: 'year', text: '按年' }, { val: 'month', text: '按月' }, { val: 'day', 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: 'year', text: '按年' }, { val: 'month', text: '按月' }, { val: 'day', text: '按日' }]"
                  :defTag="dateType" :tagClick="onSubSysDateTypeSwitch" />
              </template>
            </BarChartBlock>
          </el-col>
        </el-row>
      </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 {areaTreeSelect} 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 {
      startRecTime: '',
      endRecTime: '',
      areaName: undefined,
      areaOptions: [],
      ALARM_STATE,
      dateType: {val: 'year'},
      areaCode: '',
      devcWarningHis: {
        unit: '  ',
        xAxis: {
          type: 'category',
          data: [],
        },
        series: [],
      },
      subSysIndex: {
        unit: '  ',
        xAxis: {
          type: 'category',
          data: [],
        },
        series: [],
      },
      realTimeTableData: [],
    };
  },
  watch: {
    // 根据名称筛选区域树
    areaName (val) {
      this.$refs.tree.filter(val)
    }
  },
  async mounted () {
    await this.getAreaTreeByTag('0', 1)
    this.queryCharts()
    this.getRecentSevenDays();
  },
  methods: {
    /**计算近7天的时间范围*/
    getRecentSevenDays() {
      const endRecTime = dayjs(); // 当前时间
      const startRecTime = endRecTime.subtract(7, 'days'); // 7天前的时间
      this.startRecTime = startRecTime.format('YYYY-MM-DD HH:mm:ss');
      this.endRecTime = endRecTime.format('YYYY-MM-DD HH:mm:ss');
    },
    /** 查询区域树结构 */
    async getAreaTreeByTag(areaCode, layer) {
      await areaTreeSelect(areaCode, layer).then(response => {
        this.areaOptions = [{
          id: '-1',
          label: '全部',
          children: []
        }].concat(response.data)
        this.areaCode = '-1'
      })
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleNodeClick (data, node) {
      this.areaCode = data.id
      this.queryCharts()
    },
    async onDateTypeSwitch (item) {
      if (item.val === 'day') {
        const xaxis = DateTool.getTime(60);
        const {data} = await fetchAlarmIndexDay({
          areaCode: this.areaCode,
        });
        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.areaCode});
        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.areaCode});
      const series = this.toSeries(data, xaxis);
      this.devcWarningHis.xAxis.data = xaxis;
      this.devcWarningHis.series = series;
    },
    async onSubSysDateTypeSwitch (item) {
      if (item.val === 'day') {
        const xaxis = DateTool.getTime(60);
        const {data} = await fetchSubSysIndexDay({
          areaCode: this.areaCode,
        });
        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.areaCode});
        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.areaCode});
      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;
    },
    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.areaCode,
        alarmStateList: [
          ALARM_STATE.new.value, ALARM_STATE.disposing.value,
        ],
        startRecTime: this.startRecTime,
        endRecTime: this.endRecTime,
      });
      if (ApiCode.SUCCESS === code && rows && rows.length > 0) {
        result = rows;
      }
      this.realTimeTableData = result;
    },
    async handleCommand (command, data) {
      await updateAlarmInfo({
        id: data.id,
        alarmState: ALARM_STATE[command].value,
      });
      await this.getRealTimeAlarm();
    },
  },
};
</script>
<style src="./index.scss" scoped lang="scss" />
