<template>
  <div class="project-detail-container">
    <!-- 页面头部 - 项目信息 -->
    <header class="project-header">
      <div class="header-left">
        <h1 class="project-title">{{ projectInfo.name || $route.query.projectName }}</h1>
        <div class="project-subinfo">
          <span class="project-manager">项目负责人: {{ projectInfo.manager }}</span>
          <span class="project-date">创建时间: {{ projectInfo.createDate }}</span>
          <span class="project-status">状态: <el-tag :type="getProjectStatusType()">{{ projectInfo.status }}</el-tag></span>
        </div>
      </div>
      <div class="header-right">
        <el-button size="small" class="ml-2">刷新数据</el-button>
      </div>
    </header>

    <!-- 项目进度概览 -->
    <div class="progress-overview">
      <div class="progress-chart">
        <h3 class="section-title">项目完成进度</h3>
        <div id="progressPieChart" ref="progressPieChart" class="chart-container"></div>
      </div>
      <div class="progress-stats">
        <div class="stat-item">
          <div class="stat-number">{{ projectProgress.totalModules }}</div>
          <div class="stat-label">总模块数</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ projectProgress.completedModules }}</div>
          <div class="stat-label">已完成模块</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ projectProgress.pendingModules }}</div>
          <div class="stat-label">未完成模块</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ projectProgress.completionRate }}%</div>
          <div class="stat-label">完成率</div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <main class="project-main">
      <!-- 成员信息表 -->
      <div class="table-section">
        <h3 class="section-title">项目成员信息</h3>
        <el-table
          :data="membersList"
          stripe
          style="width: 100%"
          border>
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="totalModules" label="模块量" width="100" align="center" />
          <el-table-column prop="completedModules" label="完成量" width="100" align="center" />
          <el-table-column label="完成率" width="120" align="center">
            <template slot-scope="scope">
              {{ Math.round((scope.row.completedModules / scope.row.totalModules) * 100) }}%
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 项目模块进度表 -->
      <div class="table-section">
        <div class="section-header">
          <h3 class="section-title">项目模块进度</h3>
          <el-radio-group v-model="moduleTab" size="small" class="tab-buttons">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="completed">已完成</el-radio-button>
            <el-radio-button label="pending">未完成</el-radio-button>
          </el-radio-group>
        </div>
        <!-- 搜索栏和重置按钮 -->
        <div class="search-container">
          <el-input
            v-model="searchManager"
            placeholder="输入负责人姓名搜索"
            prefix-icon="el-icon-search"
            style="width: 200px; margin-bottom: 16px"
          />
          <el-button
            type="primary"
            size="small"
            @click="searchByManager"
            style="margin-bottom: 16px; margin-left: 8px"
          >
            搜索
          </el-button>
          <el-button
            size="small"
            @click="resetSearch"
            style="margin-bottom: 16px; margin-left: 8px"
          >
            重置
          </el-button>
        </div>
        <el-table
          :data="filteredModules"
          stripe
          style="width: 100%"
          border>
          <el-table-column prop="moduleName" label="模块名称" width="180" />
          <el-table-column prop="manager" label="负责人" width="120" />
          <el-table-column prop="status" label="完成状态" width="120" align="center">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="进度" width="120" align="center">
            <template slot-scope="scope">
              <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row.progress)" stroke-width="6" />
            </template>
          </el-table-column>
          <el-table-column prop="evaluation" label="评价" />
        </el-table>
      </div>

      <!-- 成员上传文件表 -->
      <div class="table-section">
        <h3 class="section-title">成员上传文件</h3>
        <el-table
          :data="filesList"
          stripe
          style="width: 100%"
          border>
          <el-table-column prop="fileName" label="文件名称" />
          <el-table-column prop="uploader" label="上传人" width="120" />
          <el-table-column prop="uploadTime" label="上传时间" width="180" />
          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="downloadFile(scope.row)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </main>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { listProject, getProject } from '@/api/project/project'
import { listModule } from '@/api/project/module'
import { listDoc } from '@/api/project/doc'
import { listUser } from '@/api/system/user'

export default {
  name: 'ProjectDetail',
  data() {
    return {
      projectInfo: {
        name: this.$route.query.projectName || this.$route.query.table || '',
        manager: '',
        createDate: '',
        status: ''
      },
      projectId: this.$route.query.projectId ? Number(this.$route.query.projectId) : null,
      projectProgress: {
        totalModules: 0,
        completedModules: 0,
        pendingModules: 0,
        completionRate: 0
      },
      moduleTab: 'all', // all, completed, pending
      searchManager: '',
      isSearching: false,
      membersList: [],
      modulesList: [],
      filesList: [],
      progressChart: null,
      userMap: {} // 新增用户ID到姓名的映射
    }
  },
  computed: {
    filteredModules() {
      let filtered = [];

      // 先根据标签筛选基础数据
      if (this.moduleTab === 'all') {
        filtered = [...this.modulesList];
      } else if (this.moduleTab === 'completed') {
        // 已完成类别包含已完成和完成逾期，且完成逾期排在前面
        const completedOverdue = this.modulesList.filter(module => module.status === '完成逾期');
        const completed = this.modulesList.filter(module => module.status === '已完成');
        filtered = [...completedOverdue, ...completed];
      } else if (this.moduleTab === 'pending') {
        // 未完成类别包含未完成逾期、进行中和未开始，且未完成逾期排在前面
        const pendingOverdue = this.modulesList.filter(module => module.status === '未完成逾期');
        const pendingOther = this.modulesList.filter(module => module.status === '进行中' || module.status === '未开始');
        filtered = [...pendingOverdue, ...pendingOther];
      }

      // 如果正在搜索，则进一步过滤
      if (this.isSearching && this.searchManager.trim()) {
        const searchTerm = this.searchManager.trim().toLowerCase();
        filtered = filtered.filter(module =>
          module.manager.toLowerCase().includes(searchTerm)
        );
      }

      return filtered;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initProgressChart();
    });
    window.addEventListener('resize', this.handleResize);
    this.bootstrapLoad();
  },
  beforeDestroy() {
    if (this.progressChart) {
      this.progressChart.dispose();
      this.progressChart = null;
    }
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    async bootstrapLoad() {
      try {
        const id = await this.resolveProjectId();
        if (!id) {
          this.$message.error('未找到对应项目');
          return;
        }
        this.projectId = id;
        await this.loadUsers(); // 新增加载用户映射
        await Promise.all([
          this.loadProjectInfo(id),
          this.loadModules(id),
          this.loadDocs(id)
        ]);
        this.updateProgressFromModules();
        this.refreshChart();
      } catch (e) {
        this.$message.error('加载项目数据失败');
      }
    },
    async resolveProjectId() {
      if (this.projectId) return this.projectId;
      const name = this.$route.query.projectName || this.$route.query.table || this.projectInfo.name;
      if (!name) return null;
      const res = await listProject({ projectName: name });
      if (res && res.rows && res.rows.length > 0) {
        return res.rows[0].projectId;
      }
      return null;
    },
    async loadUsers() {
      try {
        const usersRes = await listUser({ pageNum: 1, pageSize: 9999 });
        const users = (usersRes && usersRes.rows) ? usersRes.rows : [];
        this.userMap = users.reduce((acc, u) => {
          acc[u.userId] = u.nickName || u.userName || String(u.userId);
          return acc;
        }, {});
      } catch (e) {
        console.error('加载用户失败', e);
      }
    },
    async loadProjectInfo(projectId) {
      const res = await getProject(projectId);
      if (res && res.data) {
        const p = res.data;
        this.projectInfo = {
          name: p.projectName,
          manager: this.userMap[p.ownerId] || p.ownerId || '未知',
          createDate: p.createTime,
          status: this.mapProjectStatus(p.status)
        };
      }
    },
    async loadModules(projectId) {
      const res = await listModule({ projectId });
      const rows = (res && res.rows) ? res.rows : [];
      const normalize = rows.map(r => ({
        moduleName: r.moduleName,
        manager: this.userMap[r.assignee] || r.assignee || '-',
        statusCode: r.status,
        status: this.mapModuleStatus(r.status),
        progress: this.estimateProgress(r.status),
        evaluation: ''
      }));
      this.modulesList = normalize;
      const stats = {};
      normalize.forEach(m => {
        const key = m.manager || '-';
        if (!stats[key]) stats[key] = { name: key, totalModules: 0, completedModules: 0 };
        stats[key].totalModules += 1;
        if (m.statusCode === '2' || m.status === '已完成') stats[key].completedModules += 1;
      });
      this.membersList = Object.values(stats);
    },
    async loadDocs(projectId) {
      const res = await listDoc({ projectId, kindType: '0' });
      const rows = (res && res.rows) ? res.rows : [];
      this.filesList = rows.map(d => ({
        fileName: d.fileName,
        uploader: d.uploadBy,
        uploadTime: d.uploadTime,
        fileSize: ''
      }));
    },
    updateProgressFromModules() {
      const total = this.modulesList.length;
      const completed = this.modulesList.filter(m => m.statusCode === '2' || m.status === '已完成').length;
      const pending = total - completed;
      this.projectProgress.totalModules = total;
      this.projectProgress.completedModules = completed;
      this.projectProgress.pendingModules = pending;
      this.projectProgress.completionRate = total > 0 ? Math.round((completed / total) * 100) : 0;
    },
    refreshChart() {
      if (this.progressChart) {
        const option = this.progressChart.getOption();
        if (option && option.series && option.series[0] && option.series[0].data) {
          option.series[0].data = [
            { value: this.projectProgress.completedModules, name: '已完成', itemStyle: { color: '#52c41a' } },
            { value: this.projectProgress.totalModules - this.projectProgress.completedModules - this.projectProgress.pendingModules, name: '进行中', itemStyle: { color: '#1890ff' } },
            { value: this.projectProgress.pendingModules, name: '未开始', itemStyle: { color: '#faad14' } },
            { value: 0, name: '逾期', itemStyle: { color: '#ff4d4f' } }
          ];
          this.progressChart.setOption(option, true);
        }
      }
    },
    // 初始化进度饼图
    initProgressChart() {
      const chartDom = this.$refs.progressPieChart;
      if (chartDom) {
        this.progressChart = echarts.init(chartDom);
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: ['已完成', '进行中', '未开始', '逾期']
          },
          series: [
            {
              name: '项目进度',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 20,
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: [
                {
                  value: this.projectProgress.completedModules,
                  name: '已完成',
                  itemStyle: { color: '#52c41a' }
                },
                {
                  value: this.projectProgress.totalModules - this.projectProgress.completedModules - this.projectProgress.pendingModules,
                  name: '进行中',
                  itemStyle: { color: '#1890ff' }
                },
                {
                  value: this.projectProgress.pendingModules,
                  name: '未开始',
                  itemStyle: { color: '#faad14' }
                },
                {
                  value: 2, // 逾期模块数量
                  name: '逾期',
                  itemStyle: { color: '#ff4d4f' }
                }
              ]
            }
          ]
        };
        this.progressChart.setOption(option);
      }
    },
    // 处理窗口大小变化
    handleResize() {
      if (this.progressChart) {
        this.progressChart.resize();
      }
    },
    // 获取项目状态对应的标签类型
    getProjectStatusType() {
      switch (this.projectInfo.status) {
        case '已完成':
          return 'success';
        case '进行中':
          return 'primary';
        case '未开始':
          return 'warning';
        case '逾期':
          return 'danger';
        default:
          return 'info';
      }
    },
    mapProjectStatus(code) {
      if (code === '1') return '已完成';
      if (code === '0') return '进行中';
      return '隐藏';
    },
    // 获取状态对应的标签类型
    getStatusType(status) {
      switch (status) {
        case '已完成':
          return 'success';
        case '进行中':
          return 'primary';
        case '未开始':
          return 'warning';
        case '完成逾期':
        case '未完成逾期':
          return 'danger';
        default:
          return 'info';
      }
    },
    // 获取进度条状态
    getProgressStatus(progress) {
      if (progress === 100) return 'success';
      if (progress > 60) return 'primary';
      if (progress > 30) return 'warning';
      return '';
    },
    mapModuleStatus(code) {
      if (code === '2') return '已完成';
      if (code === '1') return '进行中';
      return '未开始';
    },
    estimateProgress(code) {
      if (code === '2') return 100;
      if (code === '1') return 60;
      return 0;
    },
    // 下载文件
    downloadFile(file) {
      this.$message(`下载文件: ${file.fileName}`);
      // 这里可以添加实际的文件下载逻辑
    },
    // 按负责人搜索
    searchByManager() {
      this.isSearching = true;
    },
    // 重置搜索
    resetSearch() {
      this.searchManager = '';
      this.isSearching = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.project-detail-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* 页面头部样式 */
.project-header {
  background-color: #1890ff;
  color: white;
  padding: 20px 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.project-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.project-subinfo {
  display: flex;
  gap: 20px;
  font-size: 14px;
  opacity: 0.9;
}

/* 进度概览区域 */
.progress-overview {
  display: flex;
  background: white;
  margin: 20px 24px;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  gap: 40px;
}

.progress-chart {
  flex: 1;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.progress-stats {
  width: 320px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 主要内容区域 */
.project-main {
  flex: 1;
  padding: 0 24px 24px 24px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 表格区域 */
.table-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.tab-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 搜索容器样式 */
.search-container {
  margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .progress-overview {
    flex-direction: column;
    gap: 20px;
  }

  .progress-stats {
    width: 100%;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-around;
  }

  .stat-item {
    flex: 1;
    min-width: calc(50% - 10px);
  }
}

@media (max-width: 768px) {
  .project-header {
    padding: 16px;
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .project-subinfo {
    flex-direction: column;
    gap: 8px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .tab-buttons {
    width: 100%;
    justify-content: space-between;
  }

  .search-container {
    display: flex;
    flex-wrap: wrap;
  }

  .search-container .el-input {
    width: 100%;
  }

  .progress-stats {
    flex-direction: column;
  }

  .stat-item {
    min-width: 100%;
  }
}
</style>
