<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="facilityId">
        <el-input
          v-model="queryParams.facilityId"
          placeholder="请输入设施ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维修日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeRepairDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="维修结果" prop="repairResult" style="width: 250px">
        <el-select
          v-model="queryParams.repairResult"
          placeholder="请选择维修结果"
          clearable
        >
          <el-option
            v-for="dict in fire_repair_result"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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 label="下次检查日期" style="width: 308px"  label-width="100px">
        <el-date-picker
          v-model="daterangeNextCheckDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </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_repair:repair: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_repair:repair: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_repair:repair:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['fire_facility_repair:repair:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="repairList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="30px" align="center" />
      <el-table-column label="维修信息ID" align="center" prop="id" />
      <el-table-column label="设施ID" align="center" prop="facilityId" />
      <el-table-column
        label="维修日期"
        align="center"
        prop="repairDate"
        width="180"
      >
        <template #default="scope">
          <span>{{ scope.row.repairDate ? parseTime(scope.row.repairDate, "{y}-{m}-{d}") : "暂无" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修内容" align="center" prop="repairContent" />
      <el-table-column label="维修结果" align="center" prop="repairResult">
        <template #default="scope">
          <dict-tag :options="fire_repair_result" :value="scope.row.repairResult" />
        </template>
      </el-table-column>
      <el-table-column label="操作人员" align="center" prop="replacePerson" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="下次检查日期"
        align="center"
        prop="nextCheckDate"
        width="180"
      >
        <template #default="scope">
          <span>{{ scope.row.nextCheckDate ? parseTime(scope.row.nextCheckDate, "{y}-{m}-{d}") : "暂无" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ scope.row.createTime ? parseTime(scope.row.createTime, "{y}-{m}-{d}") : "暂无" }}</span>
        </template>
      </el-table-column>
      <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_repair:repair:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fire_facility_repair:repair:remove']"
          >删除</el-button>
          <el-button
            link
            type="primary"
            icon="search"
            @click="handleDetail(scope.row)"
            v-hasPermi="['fire:facility:view']"
          >设施详情</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="repairRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设施ID" prop="facilityId">
          <el-input v-model="form.facilityId" placeholder="请输入设施ID" />
        </el-form-item>
        <el-form-item label="维修日期" prop="repairDate">
          <el-date-picker
            clearable
            v-model="form.repairDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择维修日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="维修内容" prop="repairContent">
          <el-input
            v-model="form.repairContent"
            type="textarea"
            placeholder="请输入维修内容"
          />
        </el-form-item>


        <el-form-item label="维修结果" prop="repairResult">
          <el-select
            v-model="form.repairResult"
            placeholder="请选择维修结果"
            style="width: 100%"
          >
            <el-option
              v-for="dict in fire_repair_result"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </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"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="下次检查日期" prop="nextCheckDate">
          <el-date-picker
            clearable
            v-model="form.nextCheckDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择下次检查日期"
            style="width: 100%"
          />
        </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>
  </div>
</template>

<script setup name="Repair">
import { ref, reactive, getCurrentInstance, onMounted, nextTick } from 'vue'
import { listRepair, getRepair, delRepair, addRepair, updateRepair } from "@/api/fire/repair";
import DetailDialog from './DetailDialog.vue'

const { proxy } = getCurrentInstance();

// 状态管理
const repairList = 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 daterangeRepairDate = ref([]);
const daterangeNextCheckDate = ref([]);
const currentFacilityId = ref(null);
const detailDialog = ref(null);


const { fire_repair_result } = proxy.useDict("fire_repair_result");

// 表单数据
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    facilityId: null,
    repairDate: null,
    repairResult: null,
    replacePerson: null,
    nextCheckDate: null,
  },
  rules: {
    facilityId: [{ required: true, message: "设施ID不能为空", trigger: "blur" }],
    repairDate: [{ required: true, message: "请选择维修日期", trigger: "change" }],
    repairContent: [{ required: true, message: "维修内容不能为空", trigger: "blur" }],
    repairResult: [{ required: true, message: "请选择维修结果", trigger: "change" }],
    replacePerson: [{ required: true, message: "操作人员不能为空", trigger: "blur" }],
    nextCheckDate: [{ required: true, message: "请选择下次检查日期", trigger: "change" }],
  },
});

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

// 获取列表数据
const getList = () => {
  loading.value = true;
  queryParams.value.params = {};

  // 处理日期范围查询
  if (daterangeRepairDate.value?.length === 2) {
    queryParams.value.params.beginRepairDate = daterangeRepairDate.value[0];
    queryParams.value.params.endRepairDate = daterangeRepairDate.value[1];
  }
  if (daterangeNextCheckDate.value?.length === 2) {
    queryParams.value.params.beginNextCheckDate = daterangeNextCheckDate.value[0];
    queryParams.value.params.endNextCheckDate = daterangeNextCheckDate.value[1];
  }

  listRepair(queryParams.value)
    .then(response => {
      repairList.value = response.rows;
      total.value = response.total;
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
};

// 重置表单
const reset = () => {
  form.value = {
    id: null,
    facilityId: null,
    repairDate: null,
    repairContent: null,
    repairResult: null,
    replacePerson: null,
    remark: null,
    nextCheckDate: null,
    createTime: null,
  };
  proxy.resetForm("repairRef");
};

// 搜索
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  daterangeRepairDate.value = [];
  daterangeNextCheckDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
};

// 选择变更
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 新增
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加消防设施维修记录";
};


const handleUpdate = (row) => {
  reset();
  const _id = row?.id || ids.value[0];
  getRepair(_id).then(response => {
    const resData = response.data || {};
    console.log("接口返回的repairResult:", resData.repairResult, typeof resData.repairResult);
    console.log("字典数据:", fire_repair_result.value);  // 注意这里添加了.value
    
    // 核心修复：通过.value访问Ref对象中的字典数组
    if (fire_repair_result.value && fire_repair_result.value.length > 0) {
      // 字典值是字符串类型（从调试信息可知：value: '0', '1', '2'）
      const dictValueType = typeof fire_repair_result.value[0].value;
      console.log("字典值类型:", dictValueType);
      
      // 确保回显值为字符串类型，与字典匹配
      resData.repairResult = String(resData.repairResult);
      console.log("转换后的repairResult:", resData.repairResult, typeof resData.repairResult);
    }
    
    form.value = resData;
    open.value = true;
    title.value = "修改消防设施维修记录";
  });
};

// 提交表单
const submitForm = () => {
  proxy.$refs.repairRef.validate(valid => {
    if (valid) {
      const api = form.value.id ? updateRepair : addRepair;
      api(form.value).then(() => {
        proxy.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功");
        open.value = false;
        getList();
      });
    }
  });
};

// 取消
const cancel = () => {
  open.value = false;
  reset();
};

// 删除
const handleDelete = (row) => {
  const _ids = row?.id || ids.value;
  proxy.$modal.confirm(`是否确认删除编号为"${_ids}"的记录？`)
    .then(() => delRepair(_ids))
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

// 导出
const handleExport = () => {
  proxy.download(
    "fire_facility_repair/repair/export",
    { ...queryParams.value },
    `repair_${Date.now()}.xlsx`
  );
};

// 查看设施详情
const handleDetail = async (row) => {
  currentFacilityId.value = row.facilityId;
  try {
    await nextTick();
    if (!detailDialog.value) {
      throw new Error("详情组件未初始化");
    }
    detailDialog.value.open();
  } catch (error) {
    console.error("打开详情失败:", error);
    proxy.$modal.msgError("无法打开详情，请重试");
  }
};

// 初始化加载
onMounted(getList);
</script>

<style scoped></style>
    