<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch, reactive } from 'vue';
import { Search } from '@element-plus/icons-vue';
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';

// 项目列表相关
const loading = ref(false);
const projectList = ref<any[]>([]);
const total = ref(0);
const queryParams = reactive({
  content: '',
  pageNum: 1,
  pageSize: 10
});

// 获取项目列表
const getProjectList = async () => {
  try {
    loading.value = true;
    const res = await request({
      url: '/home/workbench/list',
      method: 'get',
      params: queryParams
    });

    if (res.code === 200) {
      projectList.value = res.rows || [];
      total.value = res.total || 0;
    } else {
      ElMessage.error(res.msg || '获取项目列表失败');
    }
  } catch (error) {
    console.error('获取项目列表失败:', error);
    ElMessage.error('获取项目列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索项目
const handleSearch = () => {
  queryParams.pageNum = 1;
  getProjectList();
};

// 重置搜索
const resetSearch = () => {
  queryParams.content = '';
  handleSearch();
};

// 处理分页变化
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  getProjectList();
};

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  queryParams.pageNum = 1;
  getProjectList();
};

// 格式化时间显示
const formatTime = (timeStr: string, dateOnly = false) => {
  if (!timeStr) return '-';
  try {
    const options: Intl.DateTimeFormatOptions = dateOnly
      ? {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      }
      : {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      };

    const formatted = new Date(timeStr).toLocaleString('zh-CN', options);
    return formatted.replace(/\//g, '-');
  } catch (e) {
    return timeStr; // 如果解析失败，返回原始字符串
  }
};

// 获取进度条状态
const getProgressStatus = (percentage: number) => {
  if (percentage === null || percentage === undefined) return '';
  if (percentage < 30) return 'exception';
  if (percentage < 70) return 'warning';
  return 'success';
};

// 查看项目详情
const viewProjectDetail = (row: any) => {
  // TODO: 实现跳转到项目详情页
  console.log('View project detail:', row);
  // 这里可以添加路由跳转逻辑，例如：
  // router.push({
  //   path: '/project/detail',
  //   query: { id: row.id }
  // });
};

onMounted(async () => {
  await getProjectList();
});

onUnmounted(() => {
});
</script>

<template>
  <div class="workbench-container">
    <!-- 项目列表 -->
    <div class="project-list">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="header-title">参与项目</span>
          </div>
        </template>

        <!-- 搜索栏 -->
        <div class="search-container">
          <el-input v-model="queryParams.content" placeholder="请输入项目编号/项目名/PM/PD/CTA" style="width: 300px" clearable
            @keyup.enter="handleSearch">
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
          <el-button @click="resetSearch">重置</el-button>
        </div>

        <!-- 项目表格 -->
        <el-table v-loading="loading" :data="projectList" border style="width: 100%; margin-top: 15px">
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="code" label="项目编号" min-width="150" />
          <el-table-column prop="name" label="项目名称" min-width="180" show-overflow-tooltip />

          <!-- 项目进度相关 -->
          <el-table-column prop="onTimeSubmissionRate" label="按时提交率" min-width="130" align="center">
            <template #default="{ row }">
              {{ row.onTimeSubmissionRate !== null ? (row.onTimeSubmissionRate).toFixed(2) + '%' : '-' }}
            </template>
          </el-table-column>

          <el-table-column prop="lateSubmissionCount" label="逾期提交数" min-width="110" align="center" />

          <el-table-column prop="submissionProgress" label="提交进度" min-width="150">
            <template #default="{ row }">
              <el-progress :percentage="row.submissionProgress || 0" :show-text="false"
                :status="getProgressStatus(row.submissionProgress)" />
              <span style="margin-left: 10px">{{ row.submissionProgress !== null ? row.submissionProgress + '%' : '-'
              }}</span>
            </template>
          </el-table-column>

          <!-- 项目负责人 -->
          <el-table-column prop="pdGpd" label="PD/GPD" min-width="150" show-overflow-tooltip />
          <el-table-column prop="pmGpm" label="PM/GPM" min-width="150" show-overflow-tooltip />
          <el-table-column prop="ctaGcta" label="CTA/GCTA" min-width="150" show-overflow-tooltip />

          <!-- 时间信息 -->
          <el-table-column prop="createTime" label="创建时间" min-width="160" align="center">
            <template #default="{ row }">
              {{ formatTime(row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column prop="updateTime" label="更新时间" min-width="160" align="center">
            <template #default="{ row }">
              {{ formatTime(row.updateTime) }}
            </template>
          </el-table-column>

          <el-table-column prop="startTime" label="开始时间" min-width="120" align="center">
            <template #default="{ row }">
              {{ formatTime(row.startTime, true) }}
            </template>
          </el-table-column>

          <el-table-column prop="endTime" label="结束时间" min-width="120" align="center">
            <template #default="{ row }">
              {{ formatTime(row.endTime, true) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100" fixed="right" align="center">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="viewProjectDetail(row)">
                <el-icon>
                  <Search />
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped lang="scss">
.workbench-container {
  padding: 20px;

  .project-list {
    margin-top: 20px;
  }

  .project-list {
    .search-container {
      margin-bottom: 20px;
      display: flex;
      gap: 10px;
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }

    :deep(.el-table) {
      .cell {
        white-space: nowrap;
      }
    }
  }

  .chart-section {
    .chart-card {
      :deep(.el-card__header) {
        padding: 16px 20px;
        border-bottom: 1px solid #ebeef5;
      }

      :deep(.el-card__body) {
        padding: 20px;
      }

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .header-title {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }

      .pie-chart {
        width: 100%;
        height: 400px;
      }
    }
  }
}
</style>
