<template>
  <div>
    <div>
      <el-transfer v-model="selectedProjects" :data="allProjects" filterable :titles="['项目列表', '已关联项目']" @change="handleTransferChange" />
    </div>
    <div style="text-align: right; margin-top: 20px">
      <el-button type="primary" @click="$emit('close')">关闭</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, onMounted, ref, watch } from 'vue';
import { listProject } from '@/api/project/project';
import { addNewProjectRelevancy, listUserProjects, removeNewProjectRelevancy } from '@/api/project/projectRelevancy';
import { ProjectRelevancyVO } from '@/api/project/projectRelevancy/types';

// **从父组件接收 `userId`**
const props = defineProps<{ userId: number | string }>();

// **所有项目列表**
const allProjects = ref<{ key: number | string; label: string }[]>([]);

// **已关联的项目 ID 列表**
const selectedProjects = ref<(number | string)[]>([]);

// **获取所有项目列表**
const getProjectList = async () => {
  try {
    const res = await listProject();
    allProjects.value = res.rows.map((project) => ({
      key: project.id,
      label: project.projectName
    }));
  } catch (error) {
    console.error('获取项目列表失败:', error);
  }
};
const getUserProjects = async (s: string = '') => {
  if (!props.userId) return;
  try {
    const res = await listUserProjects({ userId: props.userId });
    selectedProjects.value = Array.isArray(res.rows) ? res.rows.map((item: ProjectRelevancyVO) => item.projectId) : [];s
  } catch (error) {
    console.error('获取用户关联的项目失败:', error);
    selectedProjects.value = []; // 请求失败时清空列表
  }
};

// **监听 `userId` 变化，重新加载关联数据**
watch(
  () => props.userId,
  async (newUserId) => {
    if (newUserId) {
      await getUserProjects();
    }
  },
  { immediate: true }
);

// **处理穿梭框变更**
const handleTransferChange = async (_: number[], direction: 'left' | 'right', movedKeys: number[]) => {
  try {
    if (direction === 'right') {
      // **添加关联**
      await addNewProjectRelevancy({
        userId: props.userId,
        projectIdList: movedKeys
      });
    } else {
      // **移除关联**
      await removeNewProjectRelevancy({
        userId: props.userId,
        projectIdList: movedKeys
      });
    }
  } catch (error) {
    console.error('更新项目关联失败:', error);
  }
};

// **初始化数据**
onMounted(async () => {
  await getProjectList();
});
</script>
