<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="选择采集项"
    width="800"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
  >
    <BasicTable @register="registerTable" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicTable, useTable } from '/@/components/Table';
import { getMesCollectionItemPage } from '/@/api/jcsj/cjx';
import { columns } from './collectionItemColumns';
import { useMessage } from '/@/hooks/web/useMessage';
const emit = defineEmits(['success']);


const { createMessage } = useMessage();
const contentType = ref<string>('');
const getExistingItemIds = ref<(() => string[]) | null>(null); // 获取已存在的采集项ID列表的函数

// 表格配置：不再维护外部 selection 状态
const [registerTable, {
  reload,
  clearSelectedRowKeys,
  getSelectRows,
  getDataSource,
  setTableData
}] = useTable({
  title: '采集项列表',
  rowSelection: {
    type: 'checkbox',
  },
  api: async (params) => {
    if (!contentType.value) {
      createMessage.warning('请先选择采集内容');
      return { list: [], total: 0 };
    }

    const ctParam = String(contentType.value || '');
    if (!ctParam) return { list: [], total: 0 };

    const queryParams = {
      ...params,
      contentType: ctParam,
      size: Math.min(params.pageSize || 50, 100),
    };

    try {
      const result = await getMesCollectionItemPage(queryParams);
      // 兼容多种返回格式
      if (Array.isArray(result)) {
        return { list: result, total: result.length };
      }
      if (result?.list) {
        return { list: result.list, total: result.total ?? result.list.length };
      }
      if (result?.records) {
        return { list: result.records, total: result.total ?? result.records.length };
      }
      // 泛型兼容：找第一个数组字段
      for (const key in result) {
        if (Array.isArray(result[key])) {
          return { list: result[key], total: result.total ?? result[key].length };
        }
      }
    } catch (error: any) {
      console.error('获取采集项失败:', error);
      createMessage.error(error?.message || '请求失败');
    }
    return { list: [], total: 0 };
  },
  columns,
  pagination: { pageSize: 50 },
  rowKey: 'id',
  canResize: false,
  showIndexColumn: false,
  useSearchForm: false,
});

// 弹窗注册
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  // 先重置所有状态，确保按钮可用
  setModalProps({
    confirmLoading: false,
    destroyOnClose: true,
  });

  // 提取 contentType
  let ctValue = data?.contentType;
  if (Array.isArray(ctValue)) ctValue = ctValue[0];
  contentType.value = ctValue ? String(ctValue) : '';

  // 保存获取已存在采集项ID列表的函数
  getExistingItemIds.value = typeof data?.getExistingItemIds === 'function' 
    ? data.getExistingItemIds 
    : null;

  if (!contentType.value) {
    createMessage.warning('请先选择采集内容');
    closeModal();
    return;
  }

  // 等待 DOM 更新
  await nextTick();

  // 清除可能遗留的选中状态和数据
  if (clearSelectedRowKeys) {
    clearSelectedRowKeys();
  }
  if (setTableData) {
    setTableData([]);
  }

  // 重新加载对应类型的数据
  await reload();

  // 再次确保选中已清空
  await nextTick();
  if (clearSelectedRowKeys) {
    clearSelectedRowKeys();
  }

  // 确保按钮状态正确
  setModalProps({
    confirmLoading: false,
  });
});

// 提交处理：直接从表格获取选中行
async function handleSubmit() {
  try {
    // 设置加载状态，防止重复点击
    setModalProps({ confirmLoading: true });

    const selectedRows = getSelectRows();
    console.log('handleSubmit - selectedRows:', selectedRows);

    if (!selectedRows || selectedRows.length === 0) {
      createMessage.warning('请至少选择一个采集项');
      setModalProps({ confirmLoading: false });
      return;
    }

    // 在提交时实时获取最新的采集项列表，检查是否重复
    let currentExistingItemIds: string[] = [];
    if (getExistingItemIds.value) {
      try {
        const ids = getExistingItemIds.value();
        currentExistingItemIds = Array.isArray(ids) 
          ? ids.map(id => String(id)).filter(Boolean)
          : [];
      } catch (error) {
        console.error('获取已存在的采集项列表失败:', error);
      }
    }

    // 检查是否与已存在的采集项重复
    const duplicateItems: any[] = [];
    selectedRows.forEach((item: any) => {
      const itemId = String(item.id || '');
      if (currentExistingItemIds.includes(itemId)) {
        duplicateItems.push(item);
      }
    });

    if (duplicateItems.length > 0) {
      const names = duplicateItems.map(item => item.name || item.code || item.id).join('、');
      createMessage.warning(`以下采集项已存在，不可重复选择：${names}`);
      setModalProps({ confirmLoading: false });
      return;
    }

    // 触发成功事件
    emit('success', selectedRows);

    // 重置加载状态
    setModalProps({ confirmLoading: false });

    // 清空所有数据和状态（这些操作即使失败也不应该影响成功流程）
    try {
      if (clearSelectedRowKeys) {
        clearSelectedRowKeys();
      }
      if (setTableData) {
        setTableData([]);
      }
    } catch (cleanupError) {
      console.warn('清空数据时出错（不影响提交）:', cleanupError);
    }
    
    // 使用 nextTick 确保状态更新后再关闭
    await nextTick();
    closeModal();
  } catch (error) {
    console.error('提交失败:', error);
    createMessage.error('提交失败，请重试');
    setModalProps({ confirmLoading: false });
  }
}

// 取消处理
function handleCancel() {
  // 确保按钮状态正确
  setModalProps({ confirmLoading: false });
  
  // 清空所有数据和状态
  if (clearSelectedRowKeys) {
    clearSelectedRowKeys();
  }
  if (setTableData) {
    setTableData([]);
  }
  
  closeModal();
}
</script>
