<template>
  <div class="dashboard-page">
    <div class="page-header">
      <h2 class="page-title">工作台</h2>
      <p class="page-desc">欢迎回来，{{ userName }}！这里是您的工作概览与待办事项。</p>
    </div>

    <!-- 概览卡片区 -->
    <el-row :gutter="24" class="stat-cards">
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card stat-pending">
          <div class="stat-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="12" cy="12" r="10"/>
              <polyline points="12 6 12 12 16 14"/>
            </svg>
          </div>
          <div class="stat-info">
            <div class="stat-title">待我审批的资料</div>
            <div class="stat-value">{{ pendingAuditCount }}</div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 这里预留其他卡片位置，比如进行中的会议、待财务确认等，根据权限展示 -->
      <el-col :span="8" v-if="canCreateMeeting">
        <el-card shadow="hover" class="stat-card stat-meetings">
          <div class="stat-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
              <circle cx="9" cy="7" r="4"/>
              <path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
              <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
            </svg>
          </div>
          <div class="stat-info">
            <div class="stat-title">活跃会议</div>
            <div class="stat-value">{{ activeMeetingCount }}</div>
            <div class="stat-desc">前往会议管理查看详情</div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8" v-if="canViewFinance">
        <el-card shadow="hover" class="stat-card stat-finance">
          <div class="stat-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="12" y1="1" x2="12" y2="23"/>
              <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/>
            </svg>
          </div>
          <div class="stat-info">
            <div class="stat-title">待财务确认账单</div>
            <div class="stat-value">{{ pendingFinanceCount }}</div>
            <div class="stat-desc">前往财务管理处理</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 待办任务区 -->
    <el-card class="todo-list-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>待办审批</span>
          <el-button type="primary" link @click="router.push('/audits')">查看全部</el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="myPendingTasks"
        style="width: 100%"
        stripe
        :empty-text="loading ? '加载中...' : '暂无待审批任务'"
      >
        <el-table-column prop="id" label="任务ID" width="80" />
        <el-table-column prop="meetingId" label="关联会议ID" width="100" />
        <el-table-column prop="moduleCode" label="模块" min-width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ formatModuleCode(row.moduleCode) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nodeStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              size="small"
              :type="row.nodeStatus === 'PENDING' ? 'warning' : 'info'"
            >
              {{ row.nodeStatus === 'PENDING' ? '待处理' : row.nodeStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="到达时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="goToAudit(row.meetingId)"
            >
              去处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { fetchAuditTasks, fetchDashboardStats } from "../../api/modules";
import { PERMS } from "../../constants/permissions";
import { useAuthStore } from "../../stores/auth";
import { toZhModuleCode } from "../../utils/status";

const router = useRouter();
const authStore = useAuthStore();
const userName = computed(() => authStore.userName || "用户");
const canCreateMeeting = computed(() => authStore.hasPermission(PERMS.meeting.manage));
const canViewFinance = computed(() => authStore.hasPermission(PERMS.finance.reconciliation));

const loading = ref(false);
const myPendingTasks = ref<any[]>([]);
const pendingAuditCount = ref(0);
const activeMeetingCount = ref(0);
const pendingFinanceCount = ref(0);

const formatModuleCode = (code: string) => toZhModuleCode(code);

const goToAudit = (meetingId?: number) => {
  if (meetingId) {
    router.push({ path: '/audits', query: { meetingId: String(meetingId) } });
  } else {
    router.push('/audits');
  }
};

const loadMyTasks = async () => {
  if (!authStore.hasPermission(PERMS.audit.read)) {
    return;
  }
  loading.value = true;
  try {
    const resp = await fetchAuditTasks({ mine: true, pageNo: 1, pageSize: 50 });
    const list = resp?.data?.list || [];
    // 过滤出PENDING的任务以供展示
    const pendings = list.filter((x: any) => x.nodeStatus === "PENDING" || x.nodeStatus === "CLAIMED");
    myPendingTasks.value = pendings.slice(0, 10); // 工作台只展示Top 10
    pendingAuditCount.value = pendings.length;
  } catch (e) {
    // ignore
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadMyTasks();
  loadDashboardStats();
});

const loadDashboardStats = async () => {
  try {
    const resp = await fetchDashboardStats();
    const stats = resp?.data || {};
    activeMeetingCount.value = stats.activeMeetingCount || 0;
    pendingFinanceCount.value = stats.pendingFinanceCount || 0;
  } catch (_e) {
    // 接口未就绪时静默失败
  }
};
</script>

<style scoped>
.dashboard-page {
  padding: 24px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  margin: 0 0 8px;
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.page-desc {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.stat-cards {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
}

.stat-card :deep(.el-card__body) {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 20px 24px;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-icon svg {
  width: 28px;
  height: 28px;
}

.stat-pending .stat-icon {
  background: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
}

.stat-meetings .stat-icon {
  background: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.stat-finance .stat-icon {
  background: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.stat-info {
  flex: 1;
  min-width: 0;
}

.stat-title {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  line-height: 1;
  color: var(--el-text-color-primary);
}

.stat-desc {
  margin-top: 8px;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.todo-list-card {
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
}
</style>
