<template> 
    <el-drawer v-model="drawerVisible" direction="rtl" title="请选择要加入房间的人员" size="40%">
        <template #header>
            <h4>请选择要加入房间的人员</h4>
        </template> 
        <div class="drawer-content">
        <!-- 搜索框 -->
        <div class="search-section">
            <el-input
                v-model="searchKeyword"
                placeholder="搜索人员或部门"
                clearable
                prefix-icon="Search"
                @input="handleSearch"
            />
        </div>
        
        <!-- 已选人员展示 -->
        <div class="selected-section" v-if="selectedUsers.length > 0">
            <div class="selected-header">
                <span>已选择 ({{ selectedUsers.length }})</span>
                <el-button type="text" @click="clearAllSelected">清空</el-button>
            </div>
            <div class="selected-tags">
                <el-tag
                v-for="user in selectedUsers"
                :key="user.uid"
                closable
                @close="removeSelectedUser(user)"
                class="selected-tag"
                >
                {{ user.name }}
                </el-tag>
            </div>
        </div>
        
        <!-- 树形结构 -->
        <el-scrollbar v-loading="leftListLoading" class="left-list-scrollbar" height="calc(100vh - 240px)">
            <el-tree
                ref="treeRef"
                lazy
                :load="handleLoadNode"
                :props="treeProps"
                node-key="uid"
                show-checkbox
                :default-expand-all="false"
                :expand-on-click-node="false"
                :check-strictly="false"
                :filter-node-method="filterNode"
                @check="handleCheckChange"
                style="width: 100%"
            >
                <template #default="{ node, data }">
                <div class="tree-item">
                    <div class="tree-item-content">
                    <span v-if="data.uid" class="user-icon">👤</span>
                    <span v-else class="dept-icon">📁</span>
                    <span class="tree-item-text">{{ data.name }}</span>
                    <span v-if="data.users_count" class="user-count">({{ data.users_count }})</span>
                    <!-- <span v-if="isNodeDisabled(data)" class="already-joined-tag">已在房间中</span> -->
                    </div>
                </div>
                </template>
            </el-tree>
        </el-scrollbar>
    </div>
    
        <template #footer>
            <div class="footer-actions">
            <el-button @click="cancelClick">取 消</el-button>
            <el-button type="primary" @click="confirmClick" :disabled="selectedUsers.length === 0">
                确 定 ({{ selectedUsers.length }})
            </el-button>
            </div>
        </template> 
    </el-drawer> 
</template>

<script setup>
import { 
    getDirectories,
    getDirectoriesUsers
  } from '@/api/coordinate.js'
  import { getParticipantsApi } from '@/api/conferencingRoom.js'
  import { nextTick, reactive, toRefs, watch, onMounted, ref } from "vue";
  
  // 定义 emit
  const emit = defineEmits(["confirmSelection"]);
  
  // 接收 props
  const props = defineProps({
    loading: {
      type: Boolean,
      default: true,
    },
  });
  
  // 响应式数据
  const drawerVisible = ref(false);
  const treeRef = ref();
  const searchKeyword = ref('');
  const selectedUsers = ref([]);
  const checkedNodes = ref([]);
  const leftListLoading = ref(false)
  const joinedUserIds = ref([]); // 存储已在房间中的用户ID
  // 树形配置
  const treeProps = reactive({
    children: 'users',
    label: 'name',
    value: 'uid',
    disabled: (data) => {
      // 只有人员节点（有uid）且该用户已在房间中时才禁用
      return data.uid && joinedUserIds.value.includes(data.uid);
    },
    isLeaf: (node) => {
      return !!node.uid; // 有 uid 的为叶子节点（人员）
    },
  });

  const isNodeDisabled = (data) => { 
    // 只有人员节点（有uid）且该用户已在房间中时才禁用
    return data.uid && joinedUserIds.value.includes(data.uid);
  };

  
  // 显示抽屉
  async function show(roomId) {
    drawerVisible.value = true;
    // 重置选择状态
    selectedUsers.value = [];
    checkedNodes.value = [];
    searchKeyword.value = '';
    
    // 获取已在房间中的用户
    try {
      const res = await getParticipantsApi(roomId);
      // 提取状态为1（在房间中）的用户ID
      joinedUserIds.value = res.data
        .filter(item => item.status == 1)
        .map(item => item.user_uid); 
    } catch (error) {
      console.error('获取房间参与者失败:', error);
      joinedUserIds.value = [];
    }
    
    // 延迟加载树形数据，确保 DOM 已渲染
    nextTick(() => {
      if (treeRef.value) {
        treeRef.value.setCheckedKeys([]);
      }
    });
  }
  async function getJoinUsers(){
    const res = await getParticipantsApi(roomId)
    const joinUsers = res.data.filter(item => item.status == 1).map(item => item.user_uid) 
    return joinUsers;
  }
  
  // 确认选择
  function confirmClick() {
    if (selectedUsers.value.length > 0) {
      emit('confirmSelection', selectedUsers.value);
      drawerVisible.value = false;
    }
  }
  
  // 取消选择
  function cancelClick() {
    drawerVisible.value = false;
  }
  
  // 加载树节点
  const handleLoadNode = async (node, resolve) => {  
    if(node?.level === 0){
        loadNode(resolve,'',node?.level)
    }else if(node?.level > 0){ 
        if(node.data.directory_uid){
            loadUserNode(resolve,node.data.directory_uid,node?.level)
        }else{
            resolve(resolve)
        }
        
    }
  }
  
  // 加载节点数据
  const loadNode = async (resolve, id) => {
    try {
        leftListLoading.value = true  
        let res = await getDirectories({level:1})
        if(res.meta.code == 200){ 
            resolve(res.data)
        } 
        leftListLoading.value = false
    } catch (error) {
        console.log(error)
        leftListLoading.value = false
    }
  }

  const loadUserNode = async(resolve,id,level)=>{
    try {
        leftListLoading.value = true 
        let userData = []
        let orgData = []
        const resOrg  = await getDirectories({level: 1,parent_uuid:id})
        if(resOrg?.data){ 
            orgData = resOrg.data
        }
        if(id){
            const res = await getDirectoriesUsers(id,{directory_uuid:id})
            userData = res.data 
        } 
        resolve([...orgData, ...userData]) 
        leftListLoading.value = false
    } catch (error) {
        console.log(error)
        leftListLoading.value = false
    }
}
  
  // 处理复选框选择变化
  const handleCheckChange = (checkedNode, checkedNodesInfo) => {
    // 获取所有选中的节点
    const checkedKeys = treeRef.value.getCheckedKeys();
    const halfCheckedKeys = treeRef.value.getHalfCheckedKeys();
    
    // 获取所有选中节点数据
    const allCheckedNodes = treeRef.value.getCheckedNodes(false, true);
    
    // 筛选出人员节点（有 uid 的节点）且不在已加入用户列表中的
    const userNodes = allCheckedNodes.filter(node => 
      node.uid && !joinedUserIds.value.includes(node.uid)
    );
    
    // 更新已选用户列表
    selectedUsers.value = userNodes;
    checkedNodes.value = allCheckedNodes;
  }
  
  // 移除已选用户
  const removeSelectedUser = (user) => {
    // 从已选列表中移除
    const index = selectedUsers.value.findIndex(u => u.uid === user.uid);
    if (index !== -1) {
      selectedUsers.value.splice(index, 1);
    }
    
    // 更新树的选中状态
    if (treeRef.value) {
      treeRef.value.setChecked(user.uid, false, false);
    }
  }
  
  // 清空所有选择
  const clearAllSelected = () => {
    selectedUsers.value = [];
    checkedNodes.value = [];
    if (treeRef.value) {
      treeRef.value.setCheckedKeys([]);
    }
  }
  
  // 搜索过滤
  const handleSearch = () => {
    if (treeRef.value) {
      treeRef.value.filter(searchKeyword.value);
    }
  }
  
  // 节点过滤方法
  const filterNode = (value, data) => {
    if (!value) return true;
    return data.name && data.name.toLowerCase().includes(value.toLowerCase());
  }
  
  // 暴露方法给父组件
  defineExpose({
    show,
    getSelectedUsers: () => selectedUsers.value
  });

</script>


<style lang="scss" scoped>
  .drawer-content {
    padding: 0 10px;
  }
  
  .search-section {
    margin-bottom: 16px;
  }
  
  .selected-section {
    margin-bottom: 16px;
    padding: 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
  
  .selected-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 14px;
    color: #606266;
  }
  
  .selected-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .selected-tag {
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .tree-item {
    display: flex;
    align-items: center;
    height: 36px;
    font-size: 14px;
    
    .tree-item-content {
      display: flex;
      align-items: center;
      width: 100%;
    }
    
    .user-icon, .dept-icon {
      margin-right: 8px;
      font-size: 16px;
    }
    
    .tree-item-text {
      color: #333333;
      font-weight: 500;
    }
    
    .user-count {
      margin-left: 6px;
      color: #999999;
      font-size: 12px;
    }
  }
  
  .footer-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
  
  :deep(.el-tree-node__content) {
    height: 40px;
  }
  
  :deep(.el-tree-node.is-current > .el-tree-node__content) {
    background-color: #f0f7ff;
  }
</style>