<template>
  <div>
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入项目名称或模块搜索"
        clearable
        @keyup.enter="handleSearch"
        class="search-input"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button v-if="searchKeyword" type="default" @click="resetSearch">重置</el-button>
    </div>

    <div>
      <el-tabs type="border-card">
        <el-tab-pane label="项目">
          <el-row :gutter="20">
            <!-- 循环渲染卡片 -->
            <el-col :span="6" v-for="item in filteredProjects" :key="item.projectId" class="card-item">
              <el-card shadow="hover" class="custom-card" @click.native="handleProjectDetail(item)">
                <div class="text-container">
                  <span class="main-text">{{ item.projectName }}</span>
                  <span class="sub-text">模块数: {{ item.moduleCount || 0 }}</span>
                </div>
              </el-card>
            </el-col>
            <!-- 创建项目卡片 -->
            <!-- <el-col :span="6" class="card-item" @click.native="handleCreateProject" style="cursor: pointer;">
              <el-card shadow="hover" class="custom-card create-card">
                <div class="text-container">
                  <span class="main-text">创建项目</span>
                </div>
              </el-card>
            </el-col> -->
          </el-row>

          <!-- 无搜索结果提示 -->
          <div v-if="filteredProjects.length === 0 && originalProjects.length > 0" class="no-result">
            没有找到匹配的项目，请尝试其他搜索关键词
          </div>

          <!-- 加载中提示 -->
          <div v-if="isLoading" class="loading">
            <el-loading-spinner></el-loading-spinner>
            <span>加载中...</span>
          </div>
        </el-tab-pane>

      </el-tabs>
    </div>
  </div>
</template>

<script>
import { listProject } from '@/api/project/project';

export default {

  //个人信息打印
  mounted() {
    const userInfo = this.$store.state.user;
    console.log('登录用户信息:', userInfo);
    console.log('登录用户的token:', userInfo.token);
    console.log('登录用户的名称:', userInfo.name);
  },
//假数据注入
  name: 'ProjectCards',
  data() {
    return {
      // 定义假数据作为备份
      fallbackProjects: [
        {id: 1, Project: '项目A00000', State: '0', Module: '模块X', Description: '这是一个示例项目A'},
        {id: 2, Project: '项目B', State: '0', Module: '模块Y', Description: '这是一个示例项目B'},
        {id: 3, Project: '项目C', State: '0', Module: '模块Z', Description: '这是一个示例项目C'},
        {id: 4, Project: '项目D', State: '0', Module: '模块W', Description: '这是一个示例项目D'}
      ],
      projects: [],
      searchKeyword: '',
      isLoading: false,
      originalProjects: [],
      moduleCounts: {} // 新增：存储每个项目的模块数
    };
  },
  computed: {
    filteredProjects() {
      // 如果没有搜索关键词，返回所有状态为0的项目
      if (!this.searchKeyword) {
        return this.originalProjects;
      }

      // 有搜索关键词时，进行模糊匹配
      const keyword = this.searchKeyword.toLowerCase();
      return this.originalProjects.filter(item =>
        item.projectName.toLowerCase().includes(keyword)
      );
    }
  },
  async created() {
    const user = this.$store.state.user;
    if (!user || !user.roles) {
      this.$message.error('无法获取用户信息');
      return;
    }
    const isAdmin = user.roles.includes('admin');

    try {
      this.isLoading = true;
      const response = await listProject({ pageNum: 1, pageSize: 9999 });
      this.originalProjects = response.rows || [];
      if (this.originalProjects.length === 0 && !isAdmin) {
        this.$message.error('您无权访问此页面');
        this.$router.push('/');
        return;
      }
    } catch (error) {
      this.$message.error('加载项目失败');
      console.error(error);
    } finally {
      this.isLoading = false;
    }

    // 检查路由是否正确注入
    console.log('路由实例是否存在:', this.$router ? '是' : '否');
    if (this.$router) {
      console.log('已配置的路由:', this.$router.options.routes);
    }
  },
  methods: {
    // 移除 isProjectOwner, fetchProjects (merge into created), fetchModuleCounts
    // 在模板中使用 item.moduleCount
    handleProjectDetail(project) {
      console.log('点击了项目详情:', project);
      // 传递项目ID到详情页
      console.log('准备跳转到项目详情页...',project);
      this.$router.push({ path: '/UnView/Project', query: { projectId: project.projectId } });
    },
    handleSearch() {
      console.log('搜索关键词:', this.searchKeyword);
      // 前端过滤已满足需求，无需重新请求
    },
    resetSearch() {
      this.searchKeyword = '';
    }
  }
};


</script>

<style scoped lang="scss">
.search-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.custom-card {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s ease;
  height: 100%;
}

.create-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.custom-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.text-container {
  position: relative;
  text-align: center;
  height: 60px;
}

.main-text {
  font-size: 16px;
  color: #fff;
  font-weight: 500;
}

.sub-text {
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
  opacity: 0;
  transform-origin: center;
}

.text-container:hover .sub-text {
  transform: translate(-50%, -10px) scale(1.1);
  opacity: 1;
  color: #fff;
}

.card-item {
  margin-bottom: 20px;
}

.no-result {
  text-align: center;
  padding: 40px 0;
  color: #666;
  font-size: 16px;
}

.loading {
  text-align: center;
  padding: 40px 0;
  color: #666;

  .el-loading-spinner {
    margin-right: 10px;
  }
}
</style>
