<template>
  <div class="app-container">
    <!-- 搜索表单区域 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="位置ID" prop="locationId">
        <el-input
          v-model="queryParams.locationId"
          placeholder="请输入位置ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设施名称" prop="facilityName">
        <el-input
          v-model="queryParams.facilityName"
          placeholder="请输入设施名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设施类型" prop="facilityType">
        <el-select
          v-model="queryParams.facilityType"
          placeholder="请选择设施类型"
          clearable
          style="width: 250px"
        >
          <el-option
            v-for="dict in fire_facility_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入库时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeEntryDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="过期日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeExpiryDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status" style="width: 250px">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in fire_facility_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['fire:facility:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fire:facility:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fire:facility:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['fire:facility:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['fire:facility:import']"
          >导入</el-button
        >
      </el-col>





    








      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="facilityList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <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-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fire:facility:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fire:facility:remove']"
            >删除</el-button
          >
          <!-- 查看详情 -->
          <el-button
            link
            type="primary"
            icon="search"
            @click="handleDetail(scope.row)"
            v-hasPermi="['fire:facility:remove']"
            >查看详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 详情弹窗 -->
    <DetailDialog ref="detailDialog" :facility-id="currentFacilityId" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="facilityRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="位置ID" prop="locationId">
          <el-input v-model="form.locationId" placeholder="请输入位置ID" />
        </el-form-item>
        <el-form-item label="设施名称" prop="facilityName">
          <el-input v-model="form.facilityName" placeholder="请输入设施名称" />
        </el-form-item>
        <el-form-item label="设施类型" prop="facilityType">
          <el-select v-model="form.facilityType" placeholder="请选择设施类型">
            <el-option
              v-for="dict in fire_facility_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="型号规格" prop="modelNumber">
          <el-input v-model="form.modelNumber" placeholder="请输入型号规格" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="入库时间" prop="entryDate">
          <el-date-picker
            clearable
            v-model="form.entryDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择入库时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker
            clearable
            v-model="form.productionDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择生产日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="过期日期" prop="expiryDate">
          <el-date-picker
            clearable
            v-model="form.expiryDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择过期日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in fire_facility_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      title="导入消防设施数据"
      v-model="importVisible"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :action="importUrl"
        :headers="headers"
        :on-success="handleImportSuccess"
        :on-error="handleImportError"
        :before-upload="beforeUpload"
        :show-file-list="true"
        :auto-upload="false"
        accept=".xlsx,.xls"
        :limit="1"
        v-model:file-list="fileList"
      >
        <template #trigger>
          <el-button type="primary">选择Excel文件</el-button>
        </template>
        <div class="el-upload__tip">
          <el-checkbox v-model="updateSupport" /> 存在则更新
          <br />
          仅支持.xlsx或.xls格式文件，
          <a href="javascript:void(0)" @click="downloadTemplate">下载模板</a>
        </div>
      </el-upload>
      <div class="dialog-footer">
        <el-button @click="handleImportCancel">取消</el-button>
        <el-button type="primary" @click="submitImport">确认导入</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Facility">
import {
  ref,
  reactive,
  toRefs,
  getCurrentInstance,
  nextTick,
  onMounted,
} from "vue";
import {
  listFacility,
  getFacility,
  delFacility,
  addFacility,
  updateFacility,

} from "@/api/fire/facility";
import { getToken } from "@/utils/auth";
import axios from "axios";
import DetailDialog from "./DetailDialog.vue";

// 引用详情弹窗组件
const detailDialog = ref(null);
const currentFacilityId = ref(null);

// 查看详情方法 - 改进版
const handleDetail = async (row) => {
  console.log("准备打开详情弹窗，当前设施ID:", row.id);
  currentFacilityId.value = row.id;

  try {
    // 等待DOM更新完成，确保组件实例已挂载
    await nextTick();

    // 检查detailDialog是否已正确初始化
    if (!detailDialog.value) {
      console.error("DetailDialog 组件实例未找到，尝试重新渲染");

      // 尝试手动触发组件重新渲染
      currentFacilityId.value = null;
      await nextTick();
      currentFacilityId.value = row.id;
      await nextTick();

      // 再次检查
      if (!detailDialog.value) {
        throw new Error("DetailDialog 组件初始化失败，请检查组件路径和注册");
      }
    }

    // 检查组件是否暴露了open方法
    if (typeof detailDialog.value.open !== "function") {
      throw new Error("DetailDialog 组件未正确暴露open方法");
    }

    // 打开详情弹窗
    let SearchId = row.id;
    detailDialog.value.open(SearchId);

    console.log("详情弹窗已成功打开");
  } catch (error) {
    console.error("打开详情弹窗时出错:", error);
    proxy.$modal.msgError("无法打开详情窗口，请刷新页面后重试");
  }
};

// 定义 uploadRef 引用
const uploadRef = ref(null);

const { proxy } = getCurrentInstance();
// 获取字典数据（设施类型和状态）
const { fire_facility_type, fire_facility_status } = proxy.useDict(
  "fire_facility_type",
  "fire_facility_status"
);

// 表格数据和状态管理
const facilityList = ref([]);
const open = ref(false); // 添加/修改弹窗显示控制
const loading = ref(true); // 表格加载状态
const showSearch = ref(true); // 搜索表单显示控制
const ids = ref([]); // 选中的记录ID
const single = ref(true); // 是否单选
const multiple = ref(true); // 是否多选
const total = ref(0); // 总记录数
const title = ref(""); // 弹窗标题
const daterangeEntryDate = ref([]); // 入库日期范围
const daterangeProductionDate = ref([]); // 生产日期范围
const daterangeExpiryDate = ref([]); // 过期日期范围
const importVisible = ref(false); // 导入弹窗显示控制
const updateSupport = ref(false); // 导入时是否更新已存在数据
const importUrl = ref(
  `${import.meta.env.VITE_APP_BASE_API}/fire/facility/importData`
);
const headers = ref({ Authorization: "Bearer " + getToken() });
const fileList = ref([]); // 上传文件列表

// 表单数据和验证规则
const data = reactive({
  form: {}, // 表单数据
  queryParams: {
    // 查询参数
    pageNum: 1,
    pageSize: 10,
    locationId: null,
    facilityName: null,
    facilityType: null,
    entryDate: null,
    expiryDate: null,
    status: null,
  },
  rules: {
    // 表单验证规则
    locationId: [
      { required: true, message: "位置ID不能为空", trigger: "blur" },
    ],
    facilityName: [
      { required: true, message: "设施名称不能为空", trigger: "blur" },
    ],
    facilityType: [
      { required: true, message: "设施类型不能为空", trigger: "change" },
    ],
    quantity: [{ required: true, message: "数量不能为空", trigger: "blur" }],
    entryDate: [
      { required: true, message: "入库时间不能为空", trigger: "blur" },
    ],
    expiryDate: [
      { required: true, message: "过期日期不能为空", trigger: "blur" },
    ],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/**
 * 查询消防设施列表
 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};

  // 处理日期范围查询参数
  if (daterangeEntryDate.value && daterangeEntryDate.value.length) {
    queryParams.value.params["beginEntryDate"] = daterangeEntryDate.value[0];
    queryParams.value.params["endEntryDate"] = daterangeEntryDate.value[1];
  }
  if (daterangeProductionDate.value && daterangeProductionDate.value.length) {
    queryParams.value.params["beginProductionDate"] =
      daterangeProductionDate.value[0];
    queryParams.value.params["endProductionDate"] =
      daterangeProductionDate.value[1];
  }
  if (daterangeExpiryDate.value && daterangeExpiryDate.value.length) {
    queryParams.value.params["beginExpiryDate"] = daterangeExpiryDate.value[0];
    queryParams.value.params["endExpiryDate"] = daterangeExpiryDate.value[1];
  }

  // 调用API获取列表数据
  listFacility(queryParams.value).then((response) => {
    facilityList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/**
 * 重置表单数据
 */
function reset() {
  form.value = {
    id: null,
    locationId: null,
    facilityName: null,
    facilityType: null,
    modelNumber: null,
    quantity: null,
    entryDate: null,
    productionDate: null,
    expiryDate: null,
    status: null,
    remark: null,
    createTime: null,
    updateTime: null,
  };
  proxy.resetForm("facilityRef");
}

/**
 * 搜索按钮操作
 */
function handleQuery() {
  queryParams.value.pageNum = 1; // 重置为第一页
  getList();
}

/**
 * 重置查询条件
 */
function resetQuery() {
  daterangeEntryDate.value = [];
  daterangeProductionDate.value = [];
  daterangeExpiryDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/**
 * 多选框选中数据处理
 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1; // 是否单选
  multiple.value = !selection.length; // 是否多选
}

/**
 * 新增消防设施
 */
function handleAdd() {
  reset(); // 重置表单
  open.value = true; // 显示弹窗
  title.value = "添加消防设施";
}

/**
 * 修改消防设施
 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value[0]; // 获取选中的ID
  getFacility(_id).then((response) => {
    form.value = response.data; // 填充表单数据
    open.value = true; // 显示弹窗
    title.value = "修改消防设施";
  });
}

/**
 * 提交表单（新增或修改）
 */
function submitForm() {
  proxy.$refs["facilityRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        // 修改操作
        updateFacility(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false; // 关闭弹窗
          getList(); // 刷新列表
        });
      } else {
        // 新增操作
        addFacility(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false; // 关闭弹窗
          getList(); // 刷新列表
        });
      }
    }
  });
}

/**
 * 删除消防设施
 */
function handleDelete(row) {
  const _ids = row.id || ids.value; // 获取选中的ID
  proxy.$modal
    .confirm('是否确认删除facilities编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delFacility(_ids);
    })
    .then(() => {
      getList(); // 刷新列表
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/**
 * 导出数据
 */
function handleExport() {
  proxy.download(
    "fire/facility/export",
    {
      ...queryParams.value,
    },
    `facility_${new Date().getTime()}.xlsx`
  );
}

/**
 * 导入数据（打开导入弹窗）
 */
function handleImport() {
  importVisible.value = true;
  updateSupport.value = false;
  fileList.value = [];
}

/**
 * 文件上传前的校验
 */
const beforeUpload = (file) => {
  const isExcel =
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    file.type === "application/vnd.ms-excel";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isExcel) {
    proxy.$modal.msgError("只能上传 .xls 或 .xlsx 格式的文件");
    return false;
  }
  if (!isLt2M) {
    proxy.$modal.msgError("上传文件大小不能超过 2MB");
    return false;
  }
  return true;
};

/**
 * 提交导入
 */
const submitImport = () => {
  try {
    if (fileList.value.length === 0) {
      proxy.$modal.msgWarning("请先选择需要导入的文件");
      return;
    }

    const file = fileList.value[0].raw;
    if (!file) {
      proxy.$modal.msgWarning("获取文件失败，请重新选择");
      return;
    }

    const formData = new FormData();
    formData.append("file", file);
    formData.append("updateSupport", updateSupport.value ? "1" : "0");

    axios
      .post(importUrl.value, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: headers.value.Authorization,
        },
      })
      .then((response) => {
        handleImportSuccess(response);
      })
      .catch((error) => {
        handleImportError(error);
      });
  } catch (error) {
    proxy.$modal.msgError(`导入过程中发生错误: ${error.message}`);
    console.error("导入错误:", error);
  }
};

/**
 * 下载导入模板
 */
function downloadTemplate() {
  window.location.href = `${
    import.meta.env.VITE_APP_BASE_API
  }/fire/facility/importTemplate?token=${getToken()}`;
}

/**
 * 导入成功处理
 */
const handleImportSuccess = (response) => {
  const res = response.data || {};
  if (res.code === 200) {
    proxy.$modal.msgSuccess(res.data || "导入成功");
    importVisible.value = false; // 关闭导入弹窗
    getList(); // 刷新列表
  } else {
    proxy.$modal.msgError(res.msg || "导入失败，请重试");
  }
};

/**
 * 导入失败处理
 */
const handleImportError = (error) => {
  console.error("导入失败:", error);
  proxy.$modal.msgError("导入失败，请检查网络连接或文件格式");
};



/**
 * 关闭添加/修改弹窗
 */
function cancel() {
  open.value = false; // 关闭弹窗
  reset(); // 重置表单
}

/**
 * 关闭导入弹窗
 */
function handleImportCancel() {
  console.log("导入弹窗取消按钮触发");
  importVisible.value = false; // 关闭弹窗
  fileList.value = []; // 清空文件列表
}

// 生命周期钩子：组件挂载后初始化数据
onMounted(async () => {
  try {
 
    getList();
  } catch (error) {
    console.error("初始化失败:", error);
    proxy.$modal.msgError("数据加载失败，请刷新页面后重试");
  }

  console.log("主组件已挂载，detailDialog 状态:", detailDialog.value);
  if (!detailDialog.value) {
    console.warn("DetailDialog 组件未初始化，可能导致详情弹窗无法打开");
  }
});
</script>

<style scoped>
.upload-demo {
  margin-bottom: 20px;
}
</style>