<template>
  <el-container>
    <el-header>
      <el-card shadow="hover" style="margin-top: 10px">
        <el-row justify="end" align="middle">
          <el-col :span="19" style="text-align: right">
            <el-radio-group v-model="timeRadio" size="small" @change="handleDateRangeChange">
<!--              <el-radio-button label="今日" value="today" />-->
              <el-radio-button label="近7天" value="week" />
              <el-radio-button label="近30天" value="month" />
            </el-radio-group>
          </el-col>
          <el-col :span="5" style="text-align: right">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="margin-left: 10px; margin-right: 30px"
            />
          </el-col>
        </el-row>
      </el-card>
    </el-header>

    <el-main style="margin-top: 20px">
      <el-row :gutter="20">
        <el-col :span="6" v-for="(item, index) in stats" :key="index">
          <el-card shadow="hover" class="stat-card">
            <h3>{{ item.label }}</h3>
            <p :class="['number', item.class]">{{ item.value }}</p>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="18">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card shadow="hover">
                <h3>类型占比</h3>
                <div ref="typePie" class="chart-placeholder"></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover">
                <h3>告警级别</h3>
                <div ref="alarmLevel" class="chart-placeholder"></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover">
                <h3>告警问题统计</h3>
                <div ref="alarmCount" class="chart-placeholder"></div>
              </el-card>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px">
            <el-col :span="12">
              <el-card shadow="hover">
                <h3>在线时长排行</h3>
                <div ref="onlineTime" class="chart-placeholder"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card shadow="hover">
                <h3>告警数量排行</h3>
                <div ref="alarmNum" class="chart-placeholder"></div>
              </el-card>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <h3>告警清单</h3>
            <el-table v-loading="loading" :data="alarmList" row-key="id">
              <el-table-column label="设备名称" align="left" prop="deviceName" width="100" :show-overflow-tooltip="true" />
              <el-table-column label="告警等级" align="center" prop="errorLevel" width="80">
                <template #default="scope">
                  <dict-tag :options="smsb_device_error_level" :value="scope.row.errorLevel" />
                </template>
              </el-table-column>
              <el-table-column label="告警类型" align="center" prop="errorType" width="80">
                <template #default="scope">
                  <dict-tag :options="smsb_device_error_type" :value="scope.row.errorType" />
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="left" prop="createTime" width="160" />
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import { reactive } from 'vue';
import { deviceStatistics } from '@/api/smsb/device/device';
import * as echarts from 'echarts';
import { DeviceErrorRecordQuery, DeviceErrorRecordVO } from '@/api/smsb/device/errorRecord_type';
import { alarmCountByLevel, alarmCountByType, alarmNumTop, listDeviceErrorRecord, onlineTimeTop } from '@/api/smsb/device/errorRecord';

const alarmList = ref<DeviceErrorRecordVO[]>([]);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { smsb_device_error_level, smsb_device_error_type } = toRefs<any>(proxy?.useDict('smsb_device_error_level', 'smsb_device_error_type'));
const total = ref(0);
const loading = ref(true);
const timeRadio = ref('week');
const dateRange = ref(['2025-01-01', '2025-01-01']);
const typePie = ref();
const alarmLevel = ref();
const alarmCount = ref();
const alarmNum = ref();
const onlineTime = ref();
const dialogData = reactive<DialogPageData<DeviceErrorRecordQuery>>({
  dialogQueryParams: {
    pageNum: 1,
    pageSize: 18,
    deviceId: undefined,
    params: {}
  }
});
const { dialogQueryParams } = toRefs(dialogData);

const stats = reactive([
  { label: '设备总量', value: 0, class: '' },
  { label: '已上线设备', value: 0, class: 'success' },
  { label: '离线设备', value: 0, class: 'danger' },
  { label: '待接入设备', value: 0, class: 'warning' }
]);

const handleDateRangeChange = () => {
  const rangeType = timeRadio.value;
  const today = new Date();
  const startDate = new Date();
  const endDate = new Date();
  switch (rangeType) {
    case 'today':
      break;
    case 'week':
      startDate.setDate(today.getDate() - 7);
      break;
    case 'month':
      startDate.setMonth(today.getMonth() - 1);
      break;
    default:
      throw new Error('Invalid range type');
  }
  dateRange.value = [formatDate(startDate), formatDate(endDate)];
  alarmCountData();
  getAlarmLevel();
  getAlarmNumTop();
  getOnlineTimeTop();
};

const formatDate = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
const getOnlineTimeTop = async () => {
  const params = {
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  };
  const res = await onlineTimeTop(params);
  const onlineTimeTopInstance = echarts.init(onlineTime.value, 'macaroons');
  onlineTimeTopInstance.setOption({
    title: {
      text: ''
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {},
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: res.data.deviceNameList
    },
    series: [
      {
        name: '',
        type: 'bar',
        data: res.data.onlineTimeList
      }
    ]
  });
};
const getAlarmNumTop = async () => {
  const params = {
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  };
  const res = await alarmNumTop(params);
  const alarmNumTopInstance = echarts.init(alarmNum.value, 'macaroons');
  alarmNumTopInstance.setOption({
    title: {
      text: ''
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {},
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01]
    },
    yAxis: {
      type: 'category',
      data: res.data.deviceNameList
    },
    series: [
      {
        name: '',
        type: 'bar',
        data: res.data.alarmNumList
      }
    ]
  });
};
const alarmCountData = async () => {
  const params = {
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  };
  const res = await alarmCountByType(params);
  const alarmTypeInstance = echarts.init(alarmCount.value, 'macaroons');
  alarmTypeInstance.setOption({
    xAxis: {
      type: 'category',
      data: res.data.alarmType
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: res.data.alarmCount,
        type: 'bar'
      }
    ]
  });
};
const getAlarmLevel = async () => {
  const params = {
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  };
  const res = await alarmCountByLevel(params);

  const alarmLevelInstance = echarts.init(alarmLevel.value, 'macaroons');
  alarmLevelInstance.setOption({
    title: {
      text: ''
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['普通', '紧急']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: res.data.alarmDateList
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '普通',
        type: 'line',
        stack: 'Total',
        data: res.data.normalAlamList
      },
      {
        name: '紧急',
        type: 'line',
        stack: 'Total',
        data: res.data.dangerAlamList
      }
    ]
  });
};
const getDeviceStatistics = async () => {
  const res = await deviceStatistics();
  stats.forEach((item) => {
    switch (item.label) {
      case '设备总量':
        item.value = res.data.totalNum;
        break;
      case '已上线设备':
        item.value = res.data.onlineNum;
        break;
      case '离线设备':
        item.value = res.data.offlineNum;
        break;
      case '待接入设备':
        item.value = res.data.initNum;
        break;
    }
  });
  const typePieInstance = echarts.init(typePie.value, 'macaroons');
  typePieInstance.setOption({
    title: {
      text: '',
      subtext: '',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '类型占比',
        type: 'pie',
        radius: '65%',
        data: [
          { value: (res.data.onlineNum / res.data.totalNum) * 100, name: '在线' },
          { value: (res.data.offlineNum / res.data.totalNum) * 100, name: '离线' },
          { value: (res.data.initNum / res.data.totalNum) * 100, name: '待接入' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  });
};
const getAlarmList = async () => {
  loading.value = true;
  const res = await listDeviceErrorRecord(dialogQueryParams.value);
  alarmList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
onMounted(() => {
  handleDateRangeChange();
  getDeviceStatistics();
  getAlarmList();
  alarmCountData();
  getAlarmLevel();
  getAlarmNumTop();
  getOnlineTimeTop();
});
</script>

<style scoped>
.stat-card {
  text-align: center;
}

.number {
  font-size: 24px;
  font-weight: bold;
}

.success {
  color: green;
}

.danger {
  color: red;
}

.warning {
  color: orange;
}

.chart-placeholder {
  height: 250px;
  /*background: #f5f5f5;*/
  border-radius: 8px;
}
</style>
