<template>
  <el-drawer
    v-model="drawerVisible"
    title="选择检验项目"
    size="900px"
    direction="rtl"
    :append-to-body="true"
    @closed="handleClose"
  >
    <el-table
      ref="tableRef"
      :data="inspectionItems"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="检验项目" />
      <el-table-column label="周期（小时）">
        <template #default="{ row }">
          <el-input-number
            v-model="row.duration"
            min="0"
            controls-position="right"
          />
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref } from "vue";
import * as Api from "@/api/statistic/consistencyInspection";

const drawerVisible = ref(false);
const inspectionItems = ref([]);
const selectedItems = ref([]);
const tableRef = ref(null);
const currentInspectType = ref(null);

// 打开侧边栏
const openDrawer = (inspectTypeId, selectedIds = [], durations = []) => {
  currentInspectType.value = inspectTypeId;
  drawerVisible.value = true;

  loadInspectionItems(inspectTypeId).then(() => {
    nextTick(() => {
      inspectionItems.value.forEach((item) => {
        const index = selectedIds.indexOf(item.id);
        if (index !== -1) {
          tableRef.value?.toggleRowSelection(item, true);
          item.duration = durations[index] || 0;
        }
      });
    });
  });
};
// 加载检验项目（保持不变）
const loadInspectionItems = async (inspectTypeId) => {
  try {
    const response = await Api.getSecondLevel(inspectTypeId);
    inspectionItems.value = response.data;
  } catch (error) {
    console.error("加载检验项目失败:", error);
  }
};

// 处理选择变化（保持不变）
const handleSelectionChange = (selection) => {
  selectedItems.value = selection;
};

// 确认选择（保持不变）
const handleConfirm = () => {
  // 检查是否有未填写duration的选中项
  const invalidItems = selectedItems.value.filter(
    (item) =>
      item.duration === undefined ||
      item.duration === null ||
      item.duration === ""
  );

  if (invalidItems.length > 0) {
    // 显示错误提示
    ElMessage.error(
      `请为 ${invalidItems.map((i) => i.name).join("、")} 填写周期`
    );
    return;
  }
  emit("confirm", selectedItems.value);
  drawerVisible.value = false;
};

// 关闭侧边栏（保持不变）
const handleClose = () => {
  tableRef.value?.clearSelection();
  selectedItems.value = [];
};

const emit = defineEmits(["confirm"]);

defineExpose({
  openDrawer: openDrawer, // 修改方法名
});
</script>

<style scoped>
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  padding: 16px;
}
</style>
