<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="oldFacilityId">
        <el-input
          v-model="queryParams.oldFacilityId"
          placeholder="请输入原设施ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="新设施ID" prop="newFacilityId">
        <el-input
          v-model="queryParams.newFacilityId"
          placeholder="请输入新设施ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更换日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeReplaceDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更换人" prop="replacePerson">
        <el-input
          v-model="queryParams.replacePerson"
          placeholder="请输入更换人"
          clearable
          @keyup.enter="handleQuery"
        />
      </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_replacement:replacement: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_replacement:replacement: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_replacement:replacement:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['fire_facility_replacement:replacement:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="replacementList" @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="oldFacilityId" />
      <el-table-column label="新设施ID" align="center" prop="newFacilityId" />
      <el-table-column label="更换日期" align="center" prop="replaceDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.replaceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更换原因" align="center" prop="replaceReason" />
      <el-table-column label="更换人" align="center" prop="replacePerson" />
      <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_replacement:replacement:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['fire_facility_replacement:replacement: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"
    />

    <!-- 添加或修改消防设施更换记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="replacementRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="原设施ID" prop="oldFacilityId">
          <el-input v-model="form.oldFacilityId" placeholder="请输入原设施ID" />
        </el-form-item>
        <el-form-item label="新设施ID" prop="newFacilityId">
          <el-input v-model="form.newFacilityId" placeholder="请输入新设施ID" />
        </el-form-item>
        <el-form-item label="更换日期" prop="replaceDate">
          <el-date-picker clearable
            v-model="form.replaceDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择更换日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更换原因" prop="replaceReason">
          <el-input v-model="form.replaceReason" placeholder="请输入更换原因" />
        </el-form-item>
        <el-form-item label="更换人" prop="replacePerson">
          <el-input v-model="form.replacePerson" placeholder="请输入更换人" />
        </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>
    <!-- 设施详情 -->
  <DetailDialog 
    ref="detailDialog" 
    :facility-id="currentFacilityId" 
    :new-facility-id="currentNewFacilityId" 
  />
</div>
</template>

<script setup name="Replacement">

import { listReplacement, getReplacement, delReplacement, addReplacement, updateReplacement } from "@/api/fire/replacement";
import DetailDialog from './DetailDialog.vue'
const { proxy } = getCurrentInstance();
const currentNewFacilityId = ref(null);  

const replacementList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeReplaceDate = ref([]);
const currentFacilityId = ref(null);
const detailDialog = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    oldFacilityId: null,
    newFacilityId: null,
    replaceDate: null,
    replacePerson: null,
  },
  rules: {
    oldFacilityId: [
      { required: true, message: "原设施ID不能为空", trigger: "blur" }
    ],
    newFacilityId: [
      { required: true, message: "新设施ID不能为空", trigger: "blur" }
    ],
    replaceDate: [
      { required: true, message: "更换日期不能为空", trigger: "blur" }
    ],
    replaceReason: [
      { required: true, message: "更换原因不能为空", trigger: "blur" }
    ],
    replacePerson: [
      { required: true, message: "更换人不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ]
  }
});

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

/** 查询消防设施更换记录列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeReplaceDate && '' != daterangeReplaceDate) {
    queryParams.value.params["beginReplaceDate"] = daterangeReplaceDate.value[0];
    queryParams.value.params["endReplaceDate"] = daterangeReplaceDate.value[1];
  }
  listReplacement(queryParams.value).then(response => {
    replacementList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 查看设施详情
const handleDetail = async (row) => {
  // 同时保存新老设施ID
  currentFacilityId.value = row.oldFacilityId;
  currentNewFacilityId.value = row.newFacilityId; // 新增保存newFacilityId

  try {
    console.log("查看设施详情", currentFacilityId.value, currentNewFacilityId.value);
    await nextTick();
    if (!detailDialog.value) {
      throw new Error("详情组件未初始化");
    }
    // 打开详情对话框
    detailDialog.value.open();
  } catch (error) {
    console.error("打开详情失败:", error);
    proxy.$modal.msgError("无法打开详情，请重试");
  }
};
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    oldFacilityId: null,
    newFacilityId: null,
    replaceDate: null,
    replaceReason: null,
    replacePerson: null,
    remark: null,
    createTime: null
  };
  proxy.resetForm("replacementRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeReplaceDate.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
  getReplacement(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改消防设施更换记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["replacementRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateReplacement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addReplacement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除消防设施更换记录编号为"' + _ids + '"的数据项？').then(function() {
    return delReplacement(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('fire_facility_replacement/replacement/export', {
    ...queryParams.value
  }, `replacement_${new Date().getTime()}.xlsx`)
}

getList();
</script>
