<template>
  <div class="play-dashboard-root">
    <div class="play-dashboard-page">
      <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-button label="自定义" value="diy"/>
                </el-radio-group>
              </el-col>
              <el-col :span="5" style="text-align: right">
                <el-date-picker v-model="dateRange" type="daterange" @change="handleDateRangeChange" range-separator="-"
                                start-placeholder="开始日期"
                                :disabled="diyFlag" :clearable="false" 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>
    </div>
  </div>
</template>

<script setup lang="ts">
// console.log('[device.vue] setup called');
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 diyFlag = ref(true);
const dialogData = reactive<DialogPageData<DeviceErrorRecordQuery>>({
  dialogQueryParams: {
    pageNum: 1,
    pageSize: 14,
    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 = () => {
  // console.log('[device.vue] handleDateRangeChange called');
  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);
      dateRange.value = [formatDate(startDate), formatDate(endDate)];
      diyFlag.value = true;
      break;
    case 'month':
      startDate.setMonth(today.getMonth() - 1);
      dateRange.value = [formatDate(startDate), formatDate(endDate)];
      diyFlag.value = true;
      break;
    case "diy" :
      diyFlag.value = false;
      dateRange.value = [formatDate(new Date(dateRange.value[0])), formatDate(new Date(dateRange.value[1]))];
      break;
    default:
      break;
    // throw new Error('Invalid range type');
  }
  console.log(dateRange.value);
  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 () => {
  // console.log('[device.vue] getOnlineTimeTop called');
  const params = {
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  };
  const res = await onlineTimeTop(params);
  if (!onlineTime.value) {
    // console.log('[onlineTime] ref is null when initializing echarts');
  } else {
    // console.log('[onlineTime] ref:', onlineTime.value);
    echarts.dispose(onlineTime.value);
    // console.log('[onlineTime] echarts instance disposed before init');
  }
  const onlineTimeTopInstance = echarts.init(onlineTime.value, 'macaroons');
  // console.log('[onlineTime] echarts instance created:', onlineTimeTopInstance);
  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 () => {
  // console.log('[device.vue] getAlarmNumTop called');
  const params = {
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  };
  const res = await alarmNumTop(params);
  if (!alarmNum.value) {
    // console.log('[alarmNum] ref is null when initializing echarts');
  } else {
    // console.log('[alarmNum] ref:', alarmNum.value);
    echarts.dispose(alarmNum.value);
    // console.log('[alarmNum] echarts instance disposed before init');
  }
  const alarmNumTopInstance = echarts.init(alarmNum.value, 'macaroons');
  // console.log('[alarmNum] echarts instance created:', alarmNumTopInstance);
  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 () => {
  // console.log('[device.vue] alarmCountData called');
  const params = {
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  };
  const res = await alarmCountByType(params);
  if (!alarmCount.value) {
    // console.log('[alarmCount] ref is null when initializing echarts');
  } else {
    // console.log('[alarmCount] ref:', alarmCount.value);
    echarts.dispose(alarmCount.value);
    // console.log('[alarmCount] echarts instance disposed before init');
  }
  const alarmTypeInstance = echarts.init(alarmCount.value, 'macaroons');
  // console.log('[alarmCount] echarts instance created:', alarmTypeInstance);
  alarmTypeInstance.setOption({
    xAxis: {
      type: 'category',
      data: res.data.alarmType
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: res.data.alarmCount,
        type: 'bar'
      }
    ]
  });
};
const getAlarmLevel = async () => {
  // console.log('[device.vue] getAlarmLevel called');
  const params = {
    startTime: dateRange.value[0],
    endTime: dateRange.value[1]
  };
  const res = await alarmCountByLevel(params);

  if (!alarmLevel.value) {
    // console.log('[alarmLevel] ref is null when initializing echarts');
  } else {
    // console.log('[alarmLevel] ref:', alarmLevel.value);
    echarts.dispose(alarmLevel.value);
    // console.log('[alarmLevel] echarts instance disposed before init');
  }
  const alarmLevelInstance = echarts.init(alarmLevel.value, 'macaroons');
  // console.log('[alarmLevel] echarts instance created:', alarmLevelInstance);
  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 () => {
  // console.log('[device.vue] getDeviceStatistics called');
  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;
    }
  });
  if (!typePie.value) {
    // console.log('[typePie] ref is null when initializing echarts');
  } else {
    // console.log('[typePie] ref:', typePie.value);
    echarts.dispose(typePie.value);
    // console.log('[typePie] echarts instance disposed before init');
  }
  const typePieInstance = echarts.init(typePie.value, 'macaroons');
  // console.log('[typePie] echarts instance created:', typePieInstance);
  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 () => {
  // console.log('[device.vue] getAlarmList called');
  loading.value = true;
  const res = await listDeviceErrorRecord(dialogQueryParams.value);
  alarmList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
onMounted(() => {
  // console.log('[device.vue] onMounted called');
  handleDateRangeChange();
  getDeviceStatistics();
  getAlarmList();
});
</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;
}

.play-dashboard-root {
  height: 100vh;
  overflow-y: auto;
}
</style>
