<template>
  <div v-if="visible" class="modal-overlay" @click.self="handleCancel">
    <div class="modal-content large">
      <div class="modal-header">
        <h3 class="modal-title">{{ title }}</h3>
        <button class="modal-close" @click="handleCancel">✕</button>
      </div>
      
      <div class="modal-body">
        <div class="generic-selector">
          <!-- 左侧：可选项 -->
          <div class="selector-panel">
            <div class="panel-header">
              <h4 class="panel-title">{{ leftTitle }}</h4>
              <span class="panel-count">
                {{ countText(availableList.length) }}
              </span>
            </div>
            <div class="panel-search" v-if="showSearch">
              <input 
                v-model="searchAvailable"
                type="text"
                :placeholder="searchPlaceholder"
                class="search-input-small"
              />
            </div>
            <div class="panel-body left-panel">
              <!-- 列表模式 -->
              <div v-if="!useTree" class="item-list">
                <div
                  v-for="item in filteredAvailable"
                  :key="getItemId(item)"
                  class="list-item"
                  :class="{ selected: getItemId(item) && selectedAvailable.includes(getItemId(item)) }"
                  @click="getItemId(item) && toggleAvailable(getItemId(item))"
                  @dblclick="getItemId(item) && moveToTarget(getItemId(item))"
                >
                  <input
                    type="checkbox"
                    :checked="!!(getItemId(item) && selectedAvailable.includes(getItemId(item)))"
                    @click.stop="getItemId(item) && toggleAvailable(getItemId(item))"
                  />
                  <span class="item-label">{{ getItemLabel(item) }}</span>
                  <span class="item-sublabel" v-if="getItemSublabel(item)">{{ getItemSublabel(item) }}</span>
                </div>
                
                <!-- 加载更多提示 -->
                <div v-if="usePagination && loadingMore" class="loading-more">
                  <div class="loading-spinner-small"></div>
                  <span>加载中...</span>
                </div>
                <div v-if="usePagination && !hasMore && availableList.length > 0" class="no-more">
                  已加载全部数据
                </div>
              </div>

              <!-- 树形模式 -->
              <div v-else class="tree-list">
                <TreeNode
                  v-for="node in treeData"
                  :key="getNodeId(node)"
                  :node="node"
                  :tree-props="treeProps"
                  :expanded-keys="expandedKeys"
                  :selected-ids="selectedAvailable"
                  :only-leaf-selectable="onlyLeafSelectable"
                  @toggle-expand="toggleExpand"
                  @toggle-select="toggleAvailable"
                  @dblclick="moveToTarget"
                />
              </div>
            </div>
          </div>

          <!-- 中间：操作按钮 -->
          <div class="selector-actions">
            <button 
              class="action-btn"
              @click="moveSelectedToTarget"
              :disabled="selectedAvailable.length === 0"
              :title="mode === 'add' ? '添加选中' : '删除选中'"
            >
              <span class="arrow">→</span>
              <span class="btn-text">{{ mode === 'add' ? '添加' : '删除' }}</span>
            </button>
            <button 
              class="action-btn"
              @click="moveAllToTarget"
              :disabled="availableList.length === 0"
              :title="mode === 'add' ? '全部添加' : '全部删除'"
            >
              <span class="arrow">⇒</span>
              <span class="btn-text">全部</span>
            </button>
            <button 
              class="action-btn"
              @click="moveBackSelected"
              :disabled="selectedTarget.length === 0"
              title="移回选中"
            >
              <span class="arrow">←</span>
              <span class="btn-text">移回</span>
            </button>
            <button 
              class="action-btn"
              @click="moveBackAll"
              :disabled="targetList.length === 0"
              title="全部移回"
            >
              <span class="arrow">⇐</span>
              <span class="btn-text">全部</span>
            </button>
          </div>

          <!-- 右侧：已选项 -->
          <div class="selector-panel">
            <div class="panel-header">
              <h4 class="panel-title">{{ rightTitle }}</h4>
              <span class="panel-count">{{ countText(targetList.length) }}</span>
            </div>
            <div class="panel-search" v-if="showSearch">
              <input 
                v-model="searchTarget"
                type="text"
                :placeholder="searchPlaceholder"
                class="search-input-small"
              />
            </div>
            <div class="panel-body">
              <div class="item-list">
                <div
                  v-for="item in filteredTarget"
                  :key="getItemId(item)"
                  class="list-item"
                  :class="{ selected: getItemId(item) && selectedTarget.includes(getItemId(item)) }"
                  @click="getItemId(item) && toggleTarget(getItemId(item))"
                  @dblclick="getItemId(item) && moveBackToAvailable(getItemId(item))"
                >
                  <input
                    type="checkbox"
                    :checked="!!(getItemId(item) && selectedTarget.includes(getItemId(item)))"
                    @click.stop="getItemId(item) && toggleTarget(getItemId(item))"
                  />
                  <span class="item-label">{{ getItemLabel(item) }}</span>
                  <span class="item-sublabel" v-if="getItemSublabel(item)">{{ getItemSublabel(item) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn-primary" @click="handleConfirm" :disabled="loading">
          {{ loading ? '处理中...' : '确定' }}
        </button>
        <button class="btn-default" @click="handleCancel">取消</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" generic="T extends Record<string, any>">
import { ref, computed, watch, nextTick } from 'vue';
import type { ResultDomain, PageParam } from '@/types';
import { TreeNode } from '@/components/base';

// 泛型项类型
type GenericItem = Record<string, any>;

interface ItemConfig {
  /** ID 字段名 */
  id: string;
  /** 显示标签字段名 */
  label: string;
  /** 副标签字段名（可选） */
  sublabel?: string;
}

interface Props {
  visible?: boolean;
  mode?: 'add' | 'remove';
  title?: string;
  leftTitle?: string;
  rightTitle?: string;
  /** 【新】获取所有可选项的接口 */
  fetchAvailableApi?: () => Promise<ResultDomain<GenericItem>>;
  /** 【新】获取已选项的接口 */
  fetchSelectedApi?: () => Promise<ResultDomain<GenericItem>>;
  /** 【新】过滤已选项的方法（返回过滤后的可选项） */
  filterSelected?: (available: GenericItem[], selected: GenericItem[]) => GenericItem[];
  /** 可选项列表（兼容旧方式，如果提供了fetchAvailableApi则忽略） */
  availableItems?: GenericItem[];
  /** 初始已选项列表（兼容旧方式，如果提供了fetchSelectedApi则忽略） */
  initialTargetItems?: GenericItem[];
  loading?: boolean;
  /** 字段配置 */
  itemConfig: ItemConfig;
  /** 单位名称（用于计数显示） */
  unitName?: string;
  /** 搜索占位符 */
  searchPlaceholder?: string;
  /** 是否显示搜索框 */
  showSearch?: boolean;
  /** 分页加载API方法 */
  fetchApi?: (pageParam: PageParam, filter?: any) => Promise<ResultDomain<GenericItem>>;
  /** 过滤参数 */
  filterParams?: any;
  /** 每页数量 */
  pageSize?: number;
  /** 是否使用分页加载 */
  usePagination?: boolean;
  /** 是否使用树形展示 */
  useTree?: boolean;
  /** 树形数据转换函数 */
  treeTransform?: (data: GenericItem[]) => any[];
  /** 树节点的配置 */
  treeProps?: {
    children?: string;
    label?: string;
    id?: string;
  };
  /** 是否只允许选择叶子节点（树形模式下有效） */
  onlyLeafSelectable?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  mode: 'add',
  title: '选择',
  leftTitle: '可选项',
  rightTitle: '已选项',
  availableItems: () => [],
  initialTargetItems: () => [],
  loading: false,
  unitName: '项',
  searchPlaceholder: '搜索...',
  showSearch: true,
  pageSize: 20,
  usePagination: false,
  useTree: false,
  treeProps: () => ({
    children: 'children',
    label: 'label',
    id: 'id'
  }),
  onlyLeafSelectable: false
});

const emit = defineEmits<{
  'update:visible': [value: boolean];
  confirm: [items: GenericItem[]];
  cancel: [];
}>();

// 数据列表
const availableList = ref<GenericItem[]>([]);
const targetList = ref<GenericItem[]>([]);

// 树形数据相关
const treeData = ref<any[]>([]);
const expandedKeys = ref<Set<string>>(new Set());

// 选中状态
const selectedAvailable = ref<string[]>([]);
const selectedTarget = ref<string[]>([]);

// 搜索关键词
const searchAvailable = ref('');
const searchTarget = ref('');

// 分页相关
const currentPage = ref(1);
const totalElements = ref(0);
const hasMore = ref(true);
const loadingMore = ref(false);
const availablePanelRef = ref<HTMLElement | null>(null);

// 获取项的 ID
function getItemId(item: GenericItem): string {
  return String(item[props.itemConfig.id] || '');
}

// 获取项的标签
function getItemLabel(item: GenericItem): string {
  return String(item[props.itemConfig.label] || '');
}

// 获取项的副标签
function getItemSublabel(item: GenericItem): string {
  if (!props.itemConfig.sublabel) return '';
  return String(item[props.itemConfig.sublabel] || '');
}

// 获取树节点 ID
function getNodeId(node: any): string {
  const idProp = props.treeProps?.id || 'id';
  return String(node[idProp] || '');
}

// 获取树节点标签
// function getNodeLabel(node: any): string {
//   const labelProp = props.treeProps?.label || 'label';
//   return String(node[labelProp] || '');
// }

// 获取树节点子节点
// function getNodeChildren(node: any): any[] {
//   const childrenProp = props.treeProps?.children || 'children';
//   return node[childrenProp] || [];
// }

// 计数文本
function countText(count: number): string {
  if (props.usePagination && totalElements.value > 0) {
    return `${count}/${totalElements.value} ${props.unitName}`;
  }
  return `${count} ${props.unitName}`;
}

// 监听props变化，初始化数据
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initializeData();
  } else {
    resetData();
  }
}, { immediate: true });

// 监听搜索关键词变化
watch(searchAvailable, () => {
  if (props.usePagination && props.fetchApi) {
    resetPaginationAndLoad();
  }
});

// 初始化数据
async function initializeData() {
  try {
    // 优先使用接口方式加载数据
    if (props.fetchAvailableApi || props.fetchSelectedApi) {
      await loadDataFromApis();
    } else if (props.usePagination && props.fetchApi) {
      // 使用分页方式
      currentPage.value = 1;
      hasMore.value = true;
      availableList.value = [];
      await loadAvailableItems();
      targetList.value = [...props.initialTargetItems];
    } else {
      // 使用传入的数据
      availableList.value = [...props.availableItems];
      targetList.value = [...props.initialTargetItems];
    }
    
    // 如果使用树形展示，转换数据
    if (props.useTree && props.treeTransform) {
      treeData.value = props.treeTransform(availableList.value);
      expandAllNodes(treeData.value);
    }
    
    selectedAvailable.value = [];
    selectedTarget.value = [];
    searchAvailable.value = '';
    searchTarget.value = '';
    
    await nextTick();
    bindScrollEvent();
  } catch (error) {
    console.error('初始化数据失败:', error);
  }
}

// 从接口加载数据
async function loadDataFromApis() {
  try {
    // 加载所有可选项
    if (props.fetchAvailableApi) {
      const availableResult = await props.fetchAvailableApi();
      if (availableResult.success) {
        const allAvailable = availableResult.dataList || [];
        
        // 加载已选项
        if (props.fetchSelectedApi) {
          const selectedResult = await props.fetchSelectedApi();
          if (selectedResult.success) {
            targetList.value = selectedResult.dataList || [];
            
            // 过滤已选项
            if (props.filterSelected) {
              availableList.value = props.filterSelected(allAvailable, targetList.value);
            } else {
              // 默认过滤逻辑：根据ID过滤
              const selectedIds = new Set(targetList.value.map(item => getItemId(item)));
              availableList.value = allAvailable.filter(item => !selectedIds.has(getItemId(item)));
            }
          }
        } else {
          // 如果没有提供已选接口，使用传入的初始数据
          targetList.value = [...props.initialTargetItems];
          const selectedIds = new Set(targetList.value.map(item => getItemId(item)));
          availableList.value = allAvailable.filter(item => !selectedIds.has(getItemId(item)));
        }
      }
    } else if (props.fetchSelectedApi) {
      // 只有已选接口
      const selectedResult = await props.fetchSelectedApi();
      if (selectedResult.success) {
        targetList.value = selectedResult.dataList || [];
      }
      availableList.value = [...props.availableItems];
      const selectedIds = new Set(targetList.value.map(item => getItemId(item)));
      availableList.value = availableList.value.filter(item => !selectedIds.has(getItemId(item)));
    }
  } catch (error) {
    console.error('从接口加载数据失败:', error);
    throw error;
  }
}

// 展开所有树节点
function expandAllNodes(nodes: any[]) {
  const childrenProp = props.treeProps?.children || 'children';
  nodes.forEach(node => {
    const nodeId = getNodeId(node);
    if (nodeId) {
      expandedKeys.value.add(nodeId);
    }
    const children = node[childrenProp] || [];
    if (children && children.length > 0) {
      expandAllNodes(children);
    }
  });
}

// 重置数据
function resetData() {
  availableList.value = [];
  targetList.value = [];
  treeData.value = [];
  expandedKeys.value.clear();
  selectedAvailable.value = [];
  selectedTarget.value = [];
  searchAvailable.value = '';
  searchTarget.value = '';
  currentPage.value = 1;
  totalElements.value = 0;
  hasMore.value = true;
  loadingMore.value = false;
  unbindScrollEvent();
}

// 加载可选项
async function loadAvailableItems() {
  if (!props.fetchApi) return;
  
  try {
    loadingMore.value = true;
    const pageParam: PageParam = {
      pageNumber: currentPage.value,
      pageSize: props.pageSize
    };
    
    const filter = searchAvailable.value 
      ? { ...props.filterParams, keyword: searchAvailable.value }
      : props.filterParams;
    
    const res = await props.fetchApi(pageParam, filter);
    
    if (res.success) {
      const newItems = res.dataList || [];
      const targetItemIds = targetList.value.map(item => getItemId(item));
      const filteredItems = newItems.filter(item => !targetItemIds.includes(getItemId(item)));
      
      if (currentPage.value === 1) {
        availableList.value = filteredItems;
      } else {
        availableList.value.push(...filteredItems);
      }
      
      totalElements.value = res.pageParam?.totalElements || 0;
      const totalPages = Math.ceil(totalElements.value / props.pageSize);
      hasMore.value = currentPage.value < totalPages;
    }
  } catch (error) {
    console.error('加载数据失败:', error);
  } finally {
    loadingMore.value = false;
  }
}

// 重置分页并重新加载
async function resetPaginationAndLoad() {
  currentPage.value = 1;
  hasMore.value = true;
  availableList.value = [];
  await loadAvailableItems();
}

// 绑定滚动事件
function bindScrollEvent() {
  const panelBody = document.querySelector('.panel-body.left-panel');
  if (panelBody) {
    availablePanelRef.value = panelBody as HTMLElement;
    panelBody.addEventListener('scroll', handleScroll);
  }
}

// 解绑滚动事件
function unbindScrollEvent() {
  if (availablePanelRef.value) {
    availablePanelRef.value.removeEventListener('scroll', handleScroll);
    availablePanelRef.value = null;
  }
}

// 处理滚动事件
function handleScroll(event: Event) {
  if (!props.usePagination || !props.fetchApi) return;
  
  const target = event.target as HTMLElement;
  const scrollTop = target.scrollTop;
  const scrollHeight = target.scrollHeight;
  const clientHeight = target.clientHeight;
  
  if (scrollHeight - scrollTop - clientHeight < 50 && hasMore.value && !loadingMore.value) {
    currentPage.value++;
    loadAvailableItems();
  }
}

// 过滤可选项
const filteredAvailable = computed(() => {
  if (props.usePagination) {
    return availableList.value;
  }
  
  if (!searchAvailable.value) {
    return availableList.value;
  }
  
  const keyword = searchAvailable.value.toLowerCase();
  return availableList.value.filter(item => {
    const label = getItemLabel(item).toLowerCase();
    const sublabel = getItemSublabel(item).toLowerCase();
    return label.includes(keyword) || sublabel.includes(keyword);
  });
});

// 过滤已选项
const filteredTarget = computed(() => {
  if (!searchTarget.value) {
    return targetList.value;
  }
  
  const keyword = searchTarget.value.toLowerCase();
  return targetList.value.filter(item => {
    const label = getItemLabel(item).toLowerCase();
    const sublabel = getItemSublabel(item).toLowerCase();
    return label.includes(keyword) || sublabel.includes(keyword);
  });
});

// 切换树节点展开/折叠
function toggleExpand(nodeId: string) {
  if (expandedKeys.value.has(nodeId)) {
    expandedKeys.value.delete(nodeId);
  } else {
    expandedKeys.value.add(nodeId);
  }
}

// 检查节点是否展开（暂未使用，保留供TreeNode组件使用）
// function isExpanded(nodeId: string): boolean {
//   return expandedKeys.value.has(nodeId);
// }

// 获取树节点的所有子节点ID（递归）
function getAllChildrenIds(node: any): string[] {
  const childrenProp = props.treeProps?.children || 'children';
  const children = node[childrenProp] || [];
  const ids: string[] = [];
  
  children.forEach((child: any) => {
    const childId = getNodeId(child);
    if (childId) {
      ids.push(childId);
      // 递归获取子节点的子节点
      ids.push(...getAllChildrenIds(child));
    }
  });
  
  return ids;
}

// 在树形数据中查找节点
function findNodeInTree(nodeId: string, nodes: any[]): any | null {
  for (const node of nodes) {
    const id = getNodeId(node);
    if (id === nodeId) {
      return node;
    }
    const childrenProp = props.treeProps?.children || 'children';
    const children = node[childrenProp] || [];
    if (children.length > 0) {
      const found = findNodeInTree(nodeId, children);
      if (found) return found;
    }
  }
  return null;
}

// 检查节点是否为叶子节点
function isLeafNode(node: any): boolean {
  const childrenProp = props.treeProps?.children || 'children';
  const children = node[childrenProp] || [];
  return children.length === 0;
}

// 切换可选项的选中状态（支持级联选择）
function toggleAvailable(itemId: string) {
  const index = selectedAvailable.value.indexOf(itemId);
  
  if (props.useTree && treeData.value.length > 0) {
    // 树形模式下的级联选择
    const node = findNodeInTree(itemId, treeData.value);
    if (node) {
      const childrenIds = getAllChildrenIds(node);
      
      if (index > -1) {
        // 取消选中：移除当前节点和所有子节点
        selectedAvailable.value = selectedAvailable.value.filter(
          id => id !== itemId && !childrenIds.includes(id)
        );
      } else {
        // 选中：添加当前节点和所有子节点
        selectedAvailable.value.push(itemId);
        childrenIds.forEach(childId => {
          if (!selectedAvailable.value.includes(childId)) {
            selectedAvailable.value.push(childId);
          }
        });
      }
    } else {
      // 节点未找到，按普通方式处理
      if (index > -1) {
        selectedAvailable.value.splice(index, 1);
      } else {
        selectedAvailable.value.push(itemId);
      }
    }
  } else {
    // 非树形模式，普通切换
    if (index > -1) {
      selectedAvailable.value.splice(index, 1);
    } else {
      selectedAvailable.value.push(itemId);
    }
  }
}

// 切换已选项的选中状态（暂不支持级联，因为已选项通常不需要级联）
function toggleTarget(itemId: string) {
  const index = selectedTarget.value.indexOf(itemId);
  if (index > -1) {
    selectedTarget.value.splice(index, 1);
  } else {
    selectedTarget.value.push(itemId);
  }
}

// 从树形数据中收集所有节点（扁平化）
function flattenTree(nodes: any[]): any[] {
  const result: any[] = [];
  const childrenProp = props.treeProps?.children || 'children';
  
  nodes.forEach(node => {
    result.push(node);
    const children = node[childrenProp] || [];
    if (children.length > 0) {
      result.push(...flattenTree(children));
    }
  });
  
  return result;
}

// 移动选中项到目标区域
function moveSelectedToTarget() {
  let itemsToMove: any[] = [];
  
  if (props.useTree && treeData.value.length > 0) {
    // 树形模式：从扁平化的树数据中查找
    const flatItems = flattenTree(treeData.value);
    itemsToMove = flatItems.filter(item => 
      selectedAvailable.value.includes(getNodeId(item))
    );
    
    // 如果只允许选择叶子节点，过滤掉非叶子节点
    if (props.onlyLeafSelectable) {
      itemsToMove = itemsToMove.filter(item => isLeafNode(item));
    }
  } else {
    // 列表模式：从可选列表中查找
    itemsToMove = availableList.value.filter(item => 
      selectedAvailable.value.includes(getItemId(item))
    );
  }
  
  targetList.value.push(...itemsToMove);
  
  if (props.useTree && treeData.value.length > 0) {
    // 树形模式：需要重新构建树（移除已选项）
    // 只移除叶子节点
    const idsToRemove = new Set(itemsToMove.map(item => getNodeId(item)));
    availableList.value = availableList.value.filter(item => 
      !idsToRemove.has(getItemId(item))
    );
    // 重新转换为树形结构
    if (props.treeTransform) {
      treeData.value = props.treeTransform(availableList.value);
    }
  } else {
    // 列表模式：直接过滤
    availableList.value = availableList.value.filter(item => 
      !selectedAvailable.value.includes(getItemId(item))
    );
  }
  
  selectedAvailable.value = [];
}

// 移动单个项到目标区域（双击）
function moveToTarget(itemId: string) {
  let item: any = null;
  let itemsToMove: any[] = [];
  
  if (props.useTree && treeData.value.length > 0) {
    // 树形模式：查找节点和所有子节点
    const node = findNodeInTree(itemId, treeData.value);
    if (node) {
      // 如果只允许选择叶子节点，检查是否为叶子节点
      if (props.onlyLeafSelectable && !isLeafNode(node)) {
        // 非叶子节点，不允许移动
        return;
      }
      
      item = node;
      const childrenIds = getAllChildrenIds(node);
      const flatItems = flattenTree(treeData.value);
      
      // 收集当前节点和所有子节点
      itemsToMove = flatItems.filter(i => {
        const id = getNodeId(i);
        return id === itemId || childrenIds.includes(id);
      });
      
      // 移动到已选列表
      targetList.value.push(...itemsToMove);
      
      // 从可选列表中移除
      const idsToRemove = new Set([itemId, ...childrenIds]);
      availableList.value = availableList.value.filter(i => 
        !idsToRemove.has(getItemId(i))
      );
      
      // 重新构建树
      if (props.treeTransform) {
        treeData.value = props.treeTransform(availableList.value);
      }
    }
  } else {
    // 列表模式
    item = availableList.value.find(i => getItemId(i) === itemId);
    if (item) {
      targetList.value.push(item);
      availableList.value = availableList.value.filter(i => getItemId(i) !== itemId);
    }
  }
}

// 移动所有项到目标区域
function moveAllToTarget() {
  if (props.useTree && treeData.value.length > 0) {
    // 树形模式：扁平化所有节点
    let flatItems = flattenTree(treeData.value);
    
    // 如果只允许选择叶子节点，过滤掉非叶子节点
    if (props.onlyLeafSelectable) {
      flatItems = flatItems.filter(item => isLeafNode(item));
    }
    
    targetList.value.push(...flatItems);
    
    // 从availableList中移除已移动的项
    const idsToRemove = new Set(flatItems.map(item => getNodeId(item)));
    availableList.value = availableList.value.filter(item => 
      !idsToRemove.has(getItemId(item))
    );
    
    // 重新构建树（如果还有非叶子节点）
    if (props.onlyLeafSelectable && props.treeTransform) {
      treeData.value = props.treeTransform(availableList.value);
    } else {
      treeData.value = [];
    }
  } else {
    // 列表模式
    targetList.value.push(...availableList.value);
    availableList.value = [];
  }
  selectedAvailable.value = [];
}

// 移回选中项到可选区域
function moveBackSelected() {
  const itemsToMoveBack = targetList.value.filter(item => 
    selectedTarget.value.includes(getItemId(item))
  );
  
  // 添加回可选列表
  availableList.value.push(...itemsToMoveBack);
  
  // 从已选列表中移除
  targetList.value = targetList.value.filter(item => 
    !selectedTarget.value.includes(getItemId(item))
  );
  
  // 如果是树形模式，重新构建树
  if (props.useTree && props.treeTransform) {
    // 清空展开状态
    expandedKeys.value.clear();
    // 重新构建树结构
    treeData.value = props.treeTransform(availableList.value);
    // 重新展开所有节点
    expandAllNodes(treeData.value);
  }
  
  selectedTarget.value = [];
}

// 移回单个项到可选区域（双击）
function moveBackToAvailable(itemId: string) {
  const item = targetList.value.find(i => getItemId(i) === itemId);
  if (item) {
    // 添加回可选列表
    availableList.value.push(item);
    
    // 从已选列表中移除
    targetList.value = targetList.value.filter(i => getItemId(i) !== itemId);
    
    // 如果是树形模式，重新构建树
    if (props.useTree && props.treeTransform) {
      // 清空展开状态
      expandedKeys.value.clear();
      // 重新构建树结构
      treeData.value = props.treeTransform(availableList.value);
      // 重新展开所有节点
      expandAllNodes(treeData.value);
    }
  }
}

// 移回所有项到可选区域
function moveBackAll() {
  // 添加回可选列表
  availableList.value.push(...targetList.value);
  
  // 清空已选列表
  targetList.value = [];
  
  // 如果是树形模式，重新构建树
  if (props.useTree && props.treeTransform) {
    // 清空展开状态
    expandedKeys.value.clear();
    // 重新构建树结构
    treeData.value = props.treeTransform(availableList.value);
    // 重新展开所有节点
    expandAllNodes(treeData.value);
  }
  selectedTarget.value = [];
}

// 确认
function handleConfirm() {
  emit('confirm', targetList.value);
  emit('update:visible', false);
}

// 取消
function handleCancel() {
  emit('cancel');
  emit('update:visible', false);
}
</script>

<style lang="scss" scoped>
@import './selector-styles.scss';
</style>

