<template>
  <div class="p-5">
    <div class="w-30% flex items-center gap-4 mb-4">
      <span class="whitespace-nowrap">选择时间：</span>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="flex-grow w-full"
        clearable
      />
      <el-button type="primary" @click="search">搜索</el-button>
    </div>
    <div>
      <el-card shadow="hover" class="mb-4">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">水浸报警统计</span>
          </div>
        </template>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div class="stat-card bg-blue-50 p-4 rounded-lg">
            <div class="text-blue-500 text-lg font-medium">当年报警数</div>
            <div class="text-2xl font-bold mt-2">{{ alarmStatis.currentYearAlarmCount}}</div>
          </div>
          <div class="stat-card bg-green-50 p-4 rounded-lg">
            <div class="text-green-500 text-lg font-medium">当月报警数</div>
            <div class="text-2xl font-bold mt-2">{{ alarmStatis.currentMonthAlarmCount}}</div>
          </div>
          <div class="stat-card bg-red-50 p-4 rounded-lg">
            <div class="text-red-500 text-lg font-medium">当天报警数</div>
            <div class="text-2xl font-bold mt-2">{{alarmStatis.currentDayAlarmCount}}</div>
          </div>
        </div>
      </el-card>
    </div>
    <el-table :data="tableData" v-loading="tableLoading" border stripe>
      <el-table-column prop="imeiCardNumber" label="设备编号" width="200" />
      <el-table-column prop="batteryLevel" label="电池电量" />
      <el-table-column label="报警状态" align="center">
        <template #default="scope">
          <el-tag
            :type="scope.row.alarmStatus === 0 ? 'success' : 'danger'"
            effect="dark"
          >
            <div class="flex items-center">
              <AlertTriangle v-if="scope.row.alarmStatus === 1" class="w-4 h-4 mr-1" />
              {{ scope.row.alarmStatus === 0 ? "正常" : "告警" }}
            </div>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="400" />
    </el-table>

    <pagination
      v-show="totals > 0"
      :total="totals"
      v-model:page="currentPage"
      v-model:limit="pageSize"
      @pagination="getManholeAllData"
    />
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import {getflipalarmDataAll} from "@/api/ldzh/index";
import {parseTime, parseTimeEnd} from "@/utils/ruoyi.js";

const tableData = ref([]);
const totals = ref(0);
const dateRange = ref([]);
const tableLoading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

const alarmStatis = ref({
  currentYearAlarmCount:1,
  currentMonthAlarmCount:1,
  currentDayAlarmCount:1
})

// 构建查询参数
const buildQueryParams = () => ({
  pageNum: currentPage.value,
  pageSize: pageSize.value,
  query: [
    { column: "water_infiltration_alarm_status", type: "ne", value: "0" },
    ...(dateRange.value?.length === 2
      ? [
          {
            column: "create_time",
            type: "between",
            value: `${parseTime(dateRange.value[0])},${parseTimeEnd(dateRange.value[1])}`,
          },
        ]
      : []),
  ],
});

// 获取数据
const getManholeAllData = async () => {
  try {
    tableLoading.value = true;
    const res = await getflipalarmDataAll(buildQueryParams());

    if (res.code !== 200) {
      ElMessage.error(res.msg);
      return;
    }

    totals.value = res.data.total;
    tableData.value = res.data.records || [];

  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error("数据加载失败，请稍后重试");
  } finally {
    tableLoading.value = false;
  }
};

const getYearAlarm = async () => {
  const startTime = parseTime(new Date(new Date().getFullYear(),0,1));
  const EndTime = parseTimeEnd(new Date(new Date().getFullYear(),11,31));
  const time = startTime+","+EndTime;
  const query = {
    pageNum: 1,
    pageSize: -1 >>> 1,
    query: [
      { column: "water_infiltration_alarm_status", type: "ne", value: "0" },
      {
        column: "create_time",
        type: "orderByDesc"
      },
      {
        column: "create_time",
        type: "between",
        value: time,
      },
    ],
  };
  const res = await getflipalarmDataAll(query);
  if(res.code !== 200){
    ElMessage.error(res.msg);
  }
  alarmStatis.value.currentYearAlarmCount = res.data.records.length;
}

const getDayAlarm = async () => {
  const startTime = parseTime(new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate()));
  const EndTime = parseTimeEnd(new Date());
  const time = startTime+","+EndTime;
  const query = {
    pageNum: 1,
    pageSize: -1 >>> 1,
    query: [
      { column: "water_infiltration_alarm_status", type: "ne", value: "0" },
      {
        column: "create_time",
        type: "orderByDesc"
      },
      {
        column: "create_time",
        type: "between",
        value: time,
      },
    ],
  };
  const res = await getflipalarmDataAll(query);
  if(res.code !== 200){
    ElMessage.error(res.msg);
  }
  alarmStatis.value.currentDayAlarmCount = res.data.records.length;
}

const getMonthAlarm = async () => {
  const startTime = parseTime(new Date(new Date().getFullYear(),new Date().getMonth(),1));
  const EndTime = parseTimeEnd(new Date(new Date().getFullYear(),new Date().getMonth()+1,0));
  const time = startTime+","+EndTime;
  const query = {
    pageNum: 1,
    pageSize: -1 >>> 1,
    query: [
      { column: "water_infiltration_alarm_status", type: "ne", value: "0" },
      {
        column: "create_time",
        type: "orderByDesc"
      },
      {
        column: "create_time",
        type: "between",
        value: time,
      },
    ],
  };
  const res = await getflipalarmDataAll(query);
  if(res.code !== 200){
    ElMessage.error(res.msg);
  }
  alarmStatis.value.currentMonthAlarmCount = res.data.records.length;
}

// 搜索时重置页码
const search = () => {
  currentPage.value = 1;
  getManholeAllData();
};

// 初始化加载
onMounted(()=>{
  getManholeAllData();
  getYearAlarm();
  getMonthAlarm();
  getDayAlarm();
});
</script>

<style scoped>
.flex-grow {
  flex-grow: 1;
  max-width: 400px;
}
</style>
