<template>
  <el-dialog
    :title="`设施详情`"
    v-model="visible"
    width="80%"
    append-to-body
    :close-on-click-modal="false"
    :height="dialogHeight"
  >
    <div class="facility-container">
      <!-- 旧设施区域 -->
      <div v-if="showOldFacility" class="facility-section">
        <div class="section-header">
          <el-tag type="info" size="large">旧设施信息</el-tag>
        </div>
        <el-table
          :data="oldFacilityList"
          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>{{ formatDate(scope.row.entryDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="生产日期"
            align="center"
            prop="productionDate"
            width="180"
          >
            <template #default="scope">
              <span>{{ formatDate(scope.row.productionDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="过期日期"
            align="center"
            prop="expiryDate"
            width="180"
          >
            <template #default="scope">
              <span>{{ formatDate(scope.row.expiryDate) }}</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>
      </div>

      <!-- 分隔线 -->
      <el-divider v-if="showOldFacility && showNewFacility" />

      <!-- 新设施区域 -->
      <div v-if="showNewFacility" class="facility-section">
        <div class="section-header">
          <el-tag type="success" size="large">新设施信息</el-tag>
        </div>
        <el-table
          :data="newFacilityList"
          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>{{ formatDate(scope.row.entryDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="生产日期"
            align="center"
            prop="productionDate"
            width="180"
          >
            <template #default="scope">
              <span>{{ formatDate(scope.row.productionDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="过期日期"
            align="center"
            prop="expiryDate"
            width="180"
          >
            <template #default="scope">
              <span>{{ formatDate(scope.row.expiryDate) }}</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>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { checkAndUpdateStatus, getFacility } from "@/api/fire/facility";
import { ref, computed, watch } from "vue";
import { useDict } from "@/utils/dict";
import DictTag from "@/components/DictTag"; // 假设存在该组件

// 定义props
const props = defineProps({
  facilityId: {
    type: [String, Number],
    required: false,
    default: null,
  },
  newFacilityId: {
    type: [String, Number],
    required: false,
    default: null,
  },
});

// 定义组件状态
const visible = ref(false);
const loading = ref(false);
const errorMessage = ref("");
const oldFacilityList = ref([]); // 旧设施数据列表
const newFacilityList = ref([]); // 新设施数据列表
const dialogHeight = ref("80vh"); // 对话框高度，确保内容可滚动

// 导入字典数据
const { fire_facility_type, fire_facility_status } = useDict(
  "fire_facility_type",
  "fire_facility_status"
);

// 控制区域显示
const showOldFacility = computed(() => {
  return !!props.facilityId || oldFacilityList.value.length > 0;
});

const showNewFacility = computed(() => {
  return !!props.newFacilityId || newFacilityList.value.length > 0;
});

// 日期格式化函数
const formatDate = (date) => {
  if (!date) return "-";

  try {
    // 尝试使用项目中的工具函数
    if (window.$utils?.parseTime) {
      return window.$utils.parseTime(date, "{y}-{m}-{d}");
    }

    // 备用日期格式化
    const d = new Date(date);
    return `${d.getFullYear()}-${(d.getMonth() + 1)
      .toString()
      .padStart(2, "0")}-${d.getDate().toString().padStart(2, "0")}`;
  } catch (e) {
    console.error("日期格式化失败:", e);
    return date;
  }
};

// 获取设施详情 - 发起两次请求
const fetchFacilityDetail = async () => {
  loading.value = true;
  errorMessage.value = "";
  oldFacilityList.value = [];
  newFacilityList.value = [];

  try {
    const requests = [];

    // 添加旧设施请求
    if (props.facilityId) {
      requests.push(
        getFacility(props.facilityId)
          .then((response) => {
            const data = response.data || {};
            if (data.id || data.facilityName) {
              return {
                ...data,
                oldFacilityId: data.oldFacilityId || props.facilityId,
                isNewFacility: false,
              };
            }
            return null;
          })
          .catch((error) => {
            console.error("获取旧设施详情失败:", error);
            return null;
          })
      );
    }

    // 添加新设施请求
    if (props.newFacilityId) {
      requests.push(
        getFacility(props.newFacilityId)
          .then((response) => {
            const data = response.data || {};
            if (data.id || data.facilityName) {
              return {
                ...data,
                newFacilityId: data.newFacilityId || props.newFacilityId,
                isNewFacility: true,
              };
            }
            return null;
          })
          .catch((error) => {
            console.error("获取新设施详情失败:", error);
            return null;
          })
      );
    }

    // 并行执行请求
    const results = await Promise.allSettled(requests);

    // 过滤成功的结果并分类
    const validResults = results
      .filter((result) => result.status === "fulfilled" && result.value)
      .map((result) => result.value);

    // 分离新旧设施数据
    oldFacilityList.value = validResults.filter((item) => !item.isNewFacility);
    newFacilityList.value = validResults.filter((item) => item.isNewFacility);

    if (validResults.length === 0) {
      throw new Error("未找到任何设施数据");
    }
  } catch (error) {
    console.error("获取设施详情失败:", error);
    errorMessage.value = error.message || "获取设施详情失败";
    window.$message?.error(errorMessage.value) ||
      console.error(errorMessage.value);
  } finally {
    loading.value = false;
  }
};

// 打开对话框
const open = async () => {
  visible.value = true;

  try {
    // 获取两个ID
    const id1 = props.newFacilityId;
    const id2 = props.facilityId;

    // 收集所有要调用的ID
    const idsToCheck = [id1, id2].filter(id => id); // 过滤掉 undefined 或 null

    if (idsToCheck.length === 0) {
      console.warn("未获取到设施ID，跳过状态检查");
      fetchFacilityDetail();
      return;
    }

    // 并发调用接口检查状态
    const responses = await Promise.all(
      idsToCheck.map(id => {
        console.log("检查设施状态：", id);
        return checkAndUpdateStatus(id);
      })
    );

    // 显示提示信息（可选：合并或显示多个提示）
    const successMsg = responses.map(r => r.msg).join("；") || "状态检查完成";
    window.$message?.success(successMsg);

    // 重新加载设施详情
    fetchFacilityDetail();
  } catch (error) {
    console.error("调用状态检查接口失败:", error);
    window.$message?.error("状态检查失败，请稍后重试");
    fetchFacilityDetail();
  }
};

// 关闭对话框
const close = () => {
  visible.value = false;
};

// 监听ID变化，重新加载数据
watch([() => props.facilityId, () => props.newFacilityId], () => {
  if (visible.value) {
    fetchFacilityDetail();
  }
});

// 暴露公共方法
defineExpose({ open, close });
</script>

<style scoped>
.facility-container {
  height: calc(80vh - 60px);
  overflow-y: auto;
  padding: 10px;
}

.facility-section {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.section-header {
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid #e6e6e6;
}

.el-table {
  margin-top: 10px;
  min-height: 200px;
}

/* 滚动条美化 */
.facility-container::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.facility-container::-webkit-scrollbar-thumb {
  border-radius: 4px;
  background-color: #ccc;
}

.facility-container::-webkit-scrollbar-track {
  background-color: #f5f5f5;
}
</style>
