<template>
  <div class="app-container">
    <!-- 数据字典加载中提示 -->
    <template v-if="!isDictLoaded">
      <div class="text-center py-10">
        <el-progress type="circle" :percentage="50" />
        <div class="mt-2">数据字典加载中...</div>
      </div>
    </template>

    <!-- 主内容区域 -->
    <template v-else>
      <!-- 搜索表单 -->
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        label-width="80px"
        class="search-form"
      >
        <el-form-item label="设施类型" prop="facilityType">
          <el-select
            v-model="queryParams.facilityType"
            placeholder="请选择设施类型"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="dict in facilityTypes"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="loading">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片区域 -->
      <el-row :gutter="15" class="stat-card-row">
        <!-- 设备总数卡片 -->
        <el-col :span="24">
          <el-card class="stat-card" @click="showTotalDetail">
            <div class="stat-content">
              <div class="stat-label">设备总数</div>
              <div class="stat-value">{{ totalCount }}</div>
            </div>
          </el-card>
        </el-col>

        <!-- 状态卡片 -->
        <el-col :span="4" v-for="(status, index) in facilityStatuses" :key="index">
          <el-card class="stat-card" @click="showStatusDetail(status.value)">
            <div class="stat-content">
              <div class="stat-label">
                <dict-tag
                  :options="fire_facility_status"
                  :value="status.value"
                  :text-only="true"
                />
              </div>
              <div class="stat-value">
                <span :class="`status-color-${status.tagType}`">
                  {{ getStatusCount(status.value) }}
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详情弹窗(所有弹窗共用,均带分页) -->
      <el-dialog
        v-model="detailDialog"
        :title="dialogTitle"
        width="80%"
        destroy-on-close
      >
        <el-table
          :data="detailList"
          border
          stripe
          :loading="detailLoading"
          style="width: 100%"
        >
          <el-table-column prop="id" label="设施ID" width="100" align="center" />
          <el-table-column prop="locationId" label="位置ID" width="120" align="center" />
          <el-table-column prop="facilityName" label="设施名称" width="150" align="center" />
          <el-table-column label="设施类型" align="center">
            <template #default="scope">
              <dict-tag
                :options="fire_facility_type"
                :value="scope.row.facilityType"
              />
            </template>
          </el-table-column>
          <el-table-column prop="modelNumber" label="型号规格" width="120" align="center" />
          <el-table-column prop="quantity" label="数量" width="80" align="center" />
          <el-table-column prop="entryDate" label="入库时间" width="150" align="center">
            <template #default="scope">{{ parseTime(scope.row.entryDate) }}</template>
          </el-table-column>
          <el-table-column prop="expiryDate" label="过期日期" width="150" align="center">
            <template #default="scope">
              <el-tag :type="getExpiryTagType(scope.row.expiryDate)">
                {{ parseTime(scope.row.expiryDate) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" width="120">
            <template #default="scope">
              <dict-tag
                :options="fire_facility_status"
                :value="scope.row.status"
              />
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" />
        </el-table>

        <!-- 分页控件(所有弹窗均显示) -->
        <div class="pagination-wrap">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handlePageSizeChange"
            @current-change="handleCurrentPageChange"
          />
        </div>

        <template #footer>
          <el-button @click="detailDialog = false">关闭</el-button>
        </template>
      </el-dialog>
    </template>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from "vue";
import { Search, Refresh } from "@element-plus/icons-vue";
import { checkAndUpdateStatus } from "@/api/fire/facility";
import { getReportData, getDetailData, getAllData } from "@/api/fire/report";
import DictTag from "@/components/DictTag/index.vue";
import { getCurrentInstance } from "vue"; // 补充导入

// 获取当前实例
const { proxy } = getCurrentInstance();

// 1. 数据字典处理
const { fire_facility_type, fire_facility_status } = proxy.useDict(
  "fire_facility_type",
  "fire_facility_status"
);

// 计算属性 - 优化字典加载判断逻辑
const facilityTypes = computed(() => fire_facility_type.value || []);
const facilityStatuses = computed(() => fire_facility_status.value || []);
const isDictLoaded = computed(() => {
  // 不仅判断长度,还要验证是否包含有效数据(避免空数组误判)
  return facilityTypes.value.length > 0 && 
         facilityStatuses.value.length > 0 &&
         facilityTypes.value.some(item => item.value !== undefined) &&
         facilityStatuses.value.some(item => item.value !== undefined);
});

// 2. 响应式数据
const reportData = ref([]);
const detailList = ref([]);
const totalCount = ref(0);
const loading = ref(false);
const detailLoading = ref(false);
const detailDialog = ref(false);
const dialogTitle = ref("");

// 弹窗类型标识
const dialogType = ref(""); // 'total' 表示总数弹窗,'status' 表示状态弹窗
const currentStatusValue = ref(null);

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 查询参数 - 确保初始值为null(符合后端预期)
const queryParams = reactive({
  facilityType: null,
});

// 3. 核心方法:查询报表数据
const handleQuery = () => {
  loading.value = true;
  // 打印查询参数,便于调试
  console.log("查询参数:", queryParams);
  getReportData(queryParams)
    .then((res) => {
      console.log("报表数据返回:", res);
      reportData.value = Array.isArray(res.data) ? res.data : [];
      totalCount.value = reportData.value.reduce(
        (sum, item) => sum + (item.total || 0),
        0
      );
    })
    .catch((err) => {
      console.error("查询报表失败:", err);
      proxy.$message.error("获取数据失败,请稍后重试");
      reportData.value = [];
      totalCount.value = 0;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 4. 计算状态数量
const getStatusCount = (statusValue) => {
  const targetValue = String(statusValue);
  return reportData.value
    .filter((item) => String(item.status) === targetValue)
    .reduce((sum, item) => sum + (item.total || 0), 0);
};

// 5. 查看状态详情
const showStatusDetail = async (statusValue) => {
  dialogType.value = "status";
  currentStatusValue.value = statusValue;
  
  const statusItem = facilityStatuses.value.find(
    (item) => String(item.value) === String(statusValue)
  );
  dialogTitle.value = statusItem ? `${statusItem.label} 详情` : "设备详情";
  
  pagination.currentPage = 1;
  pagination.pageSize = 10;
  
  await loadStatusDetailPage();
  
  detailDialog.value = true;
};

// 加载指定页的状态详情数据
const loadStatusDetailPage = async () => {
  detailLoading.value = true;
  try {
    const requestParams = {
      status: currentStatusValue.value,
      facilityType: queryParams.facilityType,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    };
    
    console.log("状态详情请求参数:", requestParams);
    
    const res = await getDetailData(requestParams);
    
    console.log("状态详情接口返回:", res);
    
    if (!res || res.code !== 200) {
      throw new Error(res?.msg || "接口返回异常");
    }
    
    const responseData = res.data || {};
    pagination.total = Number(responseData.total) || 0;
    const currentPageList = Array.isArray(responseData.list) ? responseData.list : [];

    // 状态详情弹窗调用状态更新
    for (const item of currentPageList) {
      await checkAndUpdateStatus(item.id);
    }

    const updatedRes = await getDetailData(requestParams);
    const updatedData = updatedRes.data || {};
    detailList.value = Array.isArray(updatedData.list) ? updatedData.list : [];
    
    if (detailList.value.length === 0 && pagination.total > 0) {
      proxy.$message.info("当前页没有数据");
    } else if (pagination.total === 0) {
      proxy.$message.info("没有找到符合条件的数据");
    }
  } catch (err) {
    console.error("获取状态详情失败:", err);
    proxy.$message.error("获取详情失败: " + (err.message || err));
    detailList.value = [];
    pagination.total = 0;
  } finally {
    detailLoading.value = false;
  }
};

// 6. 查看总数详情
const showTotalDetail = async () => {
  dialogType.value = "total";
  dialogTitle.value = "设备总数详情";
  
  pagination.currentPage = 1;
  pagination.pageSize = 10;
  
  await loadTotalDetailPage();
  detailDialog.value = true;
};

// 加载指定页的总数详情数据
const loadTotalDetailPage = async () => {
  detailLoading.value = true;
  try {
    // 获取所有数据(不分页)用于计算总数和分页
    const allDataRes = await getAllData({
      facilityType: queryParams.facilityType
    });
    
    console.log("所有设备数据接口返回:", allDataRes);
    
    if (!allDataRes || allDataRes.code !== 200) {
      throw new Error(allDataRes?.msg || "获取所有设备数据失败");
    }
    
    // 处理所有数据获取总条数
    const allData = Array.isArray(allDataRes.data) ? allDataRes.data : [];
    pagination.total = allData.length; // 总条数
    
    // 执行前端分页
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    detailList.value = allData.slice(start, end);
    
    // 空数据提示
    if (detailList.value.length === 0 && pagination.total > 0) {
      proxy.$message.info("当前页没有数据");
    } else if (pagination.total === 0) {
      proxy.$message.info("没有找到符合条件的设备");
    }
  } catch (err) {
    console.error("获取总数详情失败:", err);
    proxy.$message.error("获取总数详情失败: " + (err.message || err));
    detailList.value = [];
    pagination.total = 0;
  } finally {
    detailLoading.value = false;
  }
};

// 分页事件处理
const handlePageSizeChange = (pageSize) => {
  pagination.pageSize = pageSize;
  pagination.currentPage = 1;
  
  if (dialogType.value === "status") {
    loadStatusDetailPage();
  } else if (dialogType.value === "total") {
    loadTotalDetailPage();
  }
};

const handleCurrentPageChange = (currentPage) => {
  pagination.currentPage = currentPage;
  
  if (dialogType.value === "status") {
    loadStatusDetailPage();
  } else if (dialogType.value === "total") {
    loadTotalDetailPage();
  }
};

// 7. 重置查询
const resetQuery = () => {
  queryParams.facilityType = null;
  const queryRef = proxy.$refs.queryRef;
  if (queryRef) {
    queryRef.resetFields();
  }
  handleQuery();
};

// 8. 辅助方法:时间格式化
const parseTime = (time) => {
  if (!time) return "-";
  const date = new Date(time);
  return date.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });
};

// 9. 辅助方法:过期日期标签类型
const getExpiryTagType = (expiryDate) => {
  if (!expiryDate) return "default";
  const today = new Date();
  const expDate = new Date(expiryDate);
  const diffDays = Math.ceil((expDate - today) / (1000 * 60 * 60 * 24));
  return diffDays < 0 ? "danger" : diffDays <= 30 ? "warning" : "success";
};

// 10. 初始化与监听 - 核心优化点
onMounted(() => {
  // 检查状态配置错误
  const invalidStatus = facilityStatuses.value.filter(item => !item.tagType);
  // if (invalidStatus.length) {
  //   console.error("以下状态缺少tagType配置:", invalidStatus);
  //   proxy.$message.warning(`检测到${invalidStatus.length}个状态样式配置错误`);
  // }

  // 初始化查询逻辑(确保字典加载后执行)
  const initQuery = () => {
    if (isDictLoaded.value) {
      handleQuery();
    } else {
      // 等待字典加载完成后执行查询
      const unwatch = watch(isDictLoaded, (loaded) => {
        if (loaded) {
          handleQuery();
          unwatch(); // 执行后销毁监听,避免重复调用
        }
      });
    }
  };

  // 立即执行初始化查询
  initQuery();
});

// 移除原有的watch(isDictLoaded),改用onMounted中的逻辑
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.search-form {
  margin-bottom: 15px;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
}
.stat-card-row {
  margin-bottom: 15px;
}
.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 6px;
}
.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.stat-content {
  text-align: center;
  padding: 15px 0;
}
.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}
.stat-value {
  font-size: 24px;
  font-weight: bold;
}
.status-color-success { color: #67c23a; }
.status-color-warning { color: #e6a23c; }
.status-color-danger { color: #f56c6c; }
.status-color-info { color: #909399; }
.status-color-primary { color: #409eff; }
.status-color-default { color: #333; }

.pagination-wrap {
  margin-top: 15px;
  text-align: right;
}

.empty-data {
  text-align: center;
  padding: 50px 0;
}
</style>
    