<template>
  <!-- 自定义左侧抽屉-->
  <Drawer
    class="custom-drawer"
    :open="open"
    :closable="false"
    :mask="true"
    :maskClosable="false"
    :maskStyle="{ background: 'transparent', pointerEvents: 'none' }"
    placement="left"
    :width="400"
    :get-container="getContainer"
    @update:open="emit('update:open', $event)"
  >
    <!-- 抽屉头部：标题 + 关闭按钮 -->
    <template #title>
      老空区永久密闭管理
      <!-- <span class="custom-drawer-title"></span> -->
    </template>
    <template #extra>
      <CloseOutlined class="cursor-pointer" @click="emit('update:open', false)" />
    </template>

    <div class="h-full">
      <!-- 搜索区域 -->
      <!-- <div class="search-section">
          <MineCascader
            v-model:value="selectedMineId"
            placeholder="请选择煤矿"
            style="width: 60%; margin-right: 8px"
            :syncToStore="false"
            :initFromStore="false"
            :showSearch="true"
            :allowClear="true"
            @change="handleMineChange"
          />
          <a-button type="primary" @click="handleGoafSearch" style="margin-right: 8px">
            搜索
          </a-button>
          <a-button @click="handleRefresh">
            刷新
          </a-button>
        </div> -->
      <div class="mb-5px">
        <a-input v-model:value="searchValue" placeholder="密闭位置" style="width: 60%; margin-right: 8px" />
      </div>

      <!-- 传感器数据表格 -->
      <div class="table-section">
        <BasicTable
          :columns="columns"
          :data-source="filteredDataWithStatus"
          :pagination="true"
          :row-key="(record) => record.id"
          :scroll="{ y: 'calc(100vh - 320px)' }"
          size="middle"
        >
          <!-- 操作列自定义渲染 -->
          <template #operation="{ record }">
            <a-space>
              <a-button v-if="!record.isPlaced" size="small" @click="handleDeploy(record)"> 布点 </a-button>
              <a-button v-else size="small" danger @click="handleRemove(record)"> 移除 </a-button>
            </a-space>
          </template>
        </BasicTable>
      </div>
    </div>
  </Drawer>
</template>

<script lang="ts" setup>
  import { ref, computed, watch } from 'vue';
  import { Drawer, message } from 'ant-design-vue';
  import { BasicColumn, BasicTable } from '/@/components/Table';
  import { bindPosition, removePosition, getMarkerStatusList, renderGoafMarkers } from '../app';
  import { getGoafList } from '../cad.api';
  import { CloseOutlined } from '@ant-design/icons-vue';

  const props = defineProps<{
    open: boolean;
    mineCode: string;
    getContainer?: any;
  }>();

  const emit = defineEmits<{
    (e: 'update:open', value: boolean): void;
  }>();

  // 响应式数据
  const searchValue = ref('');
  // const pagination = ref({
  //   current: 1,
  //   pageSize: 10,
  //   total: 0, // 初始化为0，由接口数据决定
  // });
  const selectedMineId = ref(props.mineCode);
  // 新增：存储接口返回的密闭数据
  const goafList = ref<any[]>([]);

  // 表格列配置 - 修复字段拼写错误（devicePos → devicePos）
  const columns: BasicColumn[] = [
    {
      title: '操作',
      key: 'operation',
      slots: { customRender: 'operation' },
      width: 80,
      fixed: 'left',
    },
    {
      title: '密闭位置',
      dataIndex: 'devicePos', // 修正拼写错误
      key: 'devicePos',
      ellipsis: true,
      // tooltip: true,
    },
  ];

  // 表格数据过滤逻辑 - 核心修改：基于接口坐标判断isPlaced
  const filteredDataWithStatus = computed(() => {
    // 从接口返回的goafList过滤
    let filteredData = goafList.value.filter((item) => {
      // 密闭位置搜索匹配（兼容空值）
      const isSearchMatch = searchValue.value ? (item.devicePos || '').includes(searchValue.value) : true;
      return isSearchMatch;
    });

    // 关联标记状态 + 核心：优先判断接口返回的坐标
    const placedMarkers = getMarkerStatusList() || [];
    const dataWithStatus = filteredData.map((item) => {
      // 判断接口坐标是否有效（非null/""且为数字）
      const hasValidX = item.xcoordinate && !isNaN(Number(item.xcoordinate));
      const hasValidY = item.ycoordinate && !isNaN(Number(item.ycoordinate));
      // 兜底：本地标记是否存在（防止接口未同步的临时状态）
      const matchedMarker = placedMarkers.find((marker) => marker.data?.id === item.id);

      return {
        ...item,
        // 优先用接口坐标判断，无接口坐标时用本地标记
        isPlaced: hasValidX && hasValidY,
        sensorId: matchedMarker?.sensorId || item.id,
      };
    });

    // 分页逻辑
    // const start = (pagination.value.current - 1) * pagination.value.pageSize;
    // const end = start + pagination.value.pageSize;
    // pagination.value.total = filteredData.length;
    // return dataWithStatus.slice(start, end);
    return dataWithStatus;
  });

  // 搜索方法
  const handleGoafSearch = async () => {
    // 校验：必须选择煤矿
    if (!selectedMineId.value) {
      message.warning('请先选择煤矿！');
      return;
    }

    try {
      // 调用接口
      const res = await getGoafList({
        order: 'desc',
        mineCode: selectedMineId.value,
      });
      goafList.value = res || [];
      // pagination.value.current = 1; // 搜索后重置页码到第一页
      renderGoafMarkers(goafList.value); // 渲染标记
    } catch (error) {
      goafList.value = [];
      message.error(`查询失败：${(error as Error).message}`);
      console.error('接口请求失败：', error);
    }
  };

  // 刷新方法 - 优化：强制重新请求接口
  const handleRefresh = async () => {
    searchValue.value = '';
    // pagination.value.current = 1;
    // pagination.value = { ...pagination.value }; // 触发响应式更新

    // 如果已选择煤矿，刷新时重新请求接口（保证数据最新）
    if (selectedMineId.value) {
      await handleGoafSearch();
    } else {
      goafList.value = []; // 未选煤矿则清空表格
    }
  };

  // 表格分页变化
  // const handleTableChange = (pag: any) => {
  //   pagination.value = { ...pagination.value, ...pag };
  // };

  // 布点方法 - 优化：布点后主动刷新接口数据
  const handleDeploy = async (record: any) => {
    try {
      const marker = await bindPosition({
        id: record.id,
        devicePos: record.devicePos,
      });
      if (!marker) {
        message.warning('布点操作已取消');
        return;
      }
      // 布点成功后刷新接口数据，保证按钮状态同步
      await handleRefresh();
    } catch (error) {
      message.error(`布点失败：${(error as Error).message}`);
      console.error('布点失败：', error);
    }
  };

  // 移除后主动刷新接口数据
  const handleRemove = async (record: any) => {
    try {
      const isSuccess = await removePosition(record.sensorId, record.id);
      if (isSuccess) {
        // 移除成功后刷新接口数据，保证按钮状态同步
        await handleRefresh();
      }
    } catch (error) {
      message.error(`移除失败：${(error as Error).message}`);
      console.error('移除失败：', error);
    }
  };

  // 煤矿选择变化
  // const handleMineChange = (mineId: string) => {
  //   selectedMineId.value = mineId;
  // };

  // watch(
  //   () => props.mineCode,
  //   (newVal) => {
  //     if (newVal) {
  //       selectedMineId.value = newVal;
  //     }
  //   },
  //   { immediate: true }
  // );

  // 监听抽屉显隐：打开时刷新数据
  watch(
    () => props.open,
    (v) => {
      v && handleRefresh(); // 异步数据加载
    },
    { immediate: true }
  );

  // 初始化：分页总数同步为接口数据量
  // onMounted(() => {
  //   pagination.value.total = goafList.value.length;
  // });
</script>

<style scoped></style>
