<template>
  <div class="select-container">
    <label for="projectSelect" class="select-label">项目列表:</label>
    <el-select
      id="projectSelect"
      v-model="selectedProjectId"
      placeholder="全部工程项目"
      clearable
      filterable
      @change="handleSelect"
      style="width: 150px; margin-right: 20px"
    >
      <el-option v-for="project in projects" :key="project.id" :label="project.name" :value="project.id" />
    </el-select>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { getProjectTeam } from '@/utils/projectTeam';

const userStore = useUserStore();
const projects = computed(() => [
  // { id: '', name: '全部工程项目' }, // 添加空选项
  ...userStore.projects
]);

const selectedProjectId = ref(userStore.selectedProject?.id || '');

// 监听 userStore.selectedProject 变化，更新 selectedProjectId
watch(
  () => userStore.selectedProject,
  (newProject) => {
    selectedProjectId.value = newProject?.id ?? ''; // 避免 undefined 导致 placeholder 显示
  },
  { deep: true }
);

const handleSelect = (projectId: string) => {
  const selectedProject = projects.value.find((p) => p.id === projectId);
  if (selectedProject) {
    userStore.setSelectedProject(selectedProject);
    console.log(userStore.selectedProject); // 打印选中的项目
  }
};
</script>

<style lang="scss" scoped>
.select-container {
  display: flex;
  align-items: center; // 上下居中对齐
  gap: 10px; // label 和 select 之间的间距
}

.select-label {
  font-weight: bold;
  color: #333;
  white-space: nowrap; // 防止 label 换行
  font-size: 14px; // 设置字体大小
}

#projectSelect {
  .el-select {
    width: 400px; // 保持宽度

    .el-input__inner {
      height: 38px;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);

      &:hover {
        border-color: #409eff;
      }

      &:focus {
        border-color: #409eff;
        box-shadow: 0 0 5px rgba(64, 158, 255, 0.3);
      }
    }

    .el-input__icon {
      line-height: 38px;
    }
  }

  &.is-focus .el-input__inner {
    border-color: #409eff;
  }
}

// 响应式设计（可选）
@media (max-width: 768px) {
  .select-container {
    flex-direction: column; // 栈式布局
    align-items: flex-start; // 左对齐

    .select-label {
      margin-bottom: 5px; // label 和 select 之间的垂直间距
    }

    #projectSelect .el-select {
      width: 100%; // 在小屏幕上占满宽度
    }
  }
}
</style>
