<template>
  <el-dialog
    :title="`设施详情 - ID: ${facilityId}`"
    v-model="visible"
    width="80%"
    append-to-body
    :close-on-click-modal="false"
  >
    <el-tabs type="border-card">
      <el-tab-pane label="设施详情">
        <el-table
          :data="facilityDetailList"
          v-loading="loading"
          style="width: 100%"
          border
          empty-text="未查询到该设施信息"
        >
     
          <el-table-column label="设施ID" align="center" prop="id" />
          <el-table-column label="位置ID" align="center" prop="locationId" />
          <el-table-column
            label="设施名称"
            align="center"
            prop="facilityName"
          />
          <el-table-column label="设施类型" align="center" prop="facilityType">
            <template #default="scope">
              <dict-tag
                :options="fire_facility_type"
                :value="scope.row.facilityType"
              />
            </template>
          </el-table-column>
          <el-table-column label="型号规格" align="center" prop="modelNumber" />
          <el-table-column label="数量" align="center" prop="quantity" />

          <el-table-column
            label="入库时间"
            align="center"
            prop="entryDate"
            width="180"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.entryDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="生产日期"
            align="center"
            prop="productionDate"
            width="180"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.productionDate, "{y}-{m}-{d}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="过期日期"
            align="center"
            prop="expiryDate"
            width="180"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.expiryDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>

          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag
                :options="fire_facility_status"
                :value="scope.row.status"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from "vue";
import { getFacility ,checkAndUpdateStatus} from "@/api/fire/facility";

const { proxy } = getCurrentInstance();

const props = defineProps({
  facilityId: {
    type: [String, Number],
    required: true,
  },
});

const visible = ref(false);
const loading = ref(false);
const facilityDetail = ref({});
const facilityDetailList = ref([]);

const { fire_facility_type, fire_facility_status } = proxy.useDict(
  "fire_facility_type",
  "fire_facility_status"
);

const fetchFacilityDetail = () => {
  loading.value = true;
  getFacility(props.facilityId)
    .then((response) => {
      // 关键修改：仅当response.data有效且包含必要字段时才添加到数组
      const data = response.data || {};
      if (data.id) {
        // 根据实际数据结构调整判断条件
        facilityDetail.value = data;
        facilityDetailList.value = [data];
      } else {
        facilityDetail.value = {};
        facilityDetailList.value = []; // 确保无数据时数组为空
      }
      console.log("设施详情数据:", facilityDetailList.value); // 调试用
    })
    .catch((error) => {
      console.error("获取设施详情失败:", error);
      proxy.$modal.msgError("获取设施详情失败");
      facilityDetailList.value = [];
    })
    .finally(() => {
      loading.value = false;
    });
};


const open = async () => {
  visible.value = true;
  // 调用checkAndUpdateStatus接口（传入设施ID）
  try {
    // 确定要检查状态的设施ID，优先使用新设施ID
    const targetId = props.newFacilityId || props.facilityId;
    if (!targetId) {
      console.warn("未获取到设施ID，跳过状态检查");
      fetchFacilityDetail(); // 直接加载详情
      return;
    }

    // 调用后端接口检查并更新状态
   let id= targetId
   console.log("检查设施状态：", id);
    const response = await checkAndUpdateStatus(id);
    // 显示后端返回的提示信息
    window.$message?.success(response.msg || "状态检查完成");
    
    // 状态检查后重新加载设施详情，确保数据最新
    fetchFacilityDetail();
  } catch (error) {
    // 捕获网络错误或请求异常
    console.error("调用状态检查接口失败:", error);
    window.$message?.error("状态检查失败，请稍后重试");
    // 即使接口调用失败，仍尝试加载详情
    fetchFacilityDetail();
  }
};



defineExpose({ open });
</script>

<style scoped>
.el-table {
  margin-top: 10px;
  min-height: 300px;
}
</style>