<script setup lang="ts">
import { computed, onActivated, ref } from 'vue';
import { fetchGetMyTeamLoad } from '@/service/api';
import { getWorkbenchItemColor } from '../composables/use-workbench-colors';
import {
  type WorkbenchTeamLoadLevel,
  type WorkbenchTeamLoadMemberSource,
  buildWorkbenchTeamLoadView
} from '../homepage';
import { useWorkbenchRefresh } from '../composables/use-workbench-refresh';
import WorkbenchModuleCard from './workbench-module-card.vue';

defineOptions({ name: 'WorkbenchTeamLoad' });

interface Props {
  editing?: boolean;
}
withDefaults(defineProps<Props>(), { editing: false });
defineEmits<{ (e: 'hide'): void }>();

const teamLoadMembers = ref<Api.Project.TeamLoadMember[]>([]);

async function loadTeamLoad() {
  const { error, data } = await fetchGetMyTeamLoad();
  teamLoadMembers.value = error || !data ? [] : data.members;
}

const { loading, refresh } = useWorkbenchRefresh(loadTeamLoad);

// 契约：members[0] 恒为当前用户，展示加「（我）」后缀（builder 内部会按负载等级重排，标记跟名字走）
function toTeamLoadSource(member: Api.Project.TeamLoadMember, index: number): WorkbenchTeamLoadMemberSource {
  return {
    memberId: member.userId,
    memberName: index === 0 ? `${member.userNickname}（我）` : member.userNickname,
    items: member.items.map(item => ({
      key: item.kind === 'project' && item.projectId ? item.projectId : item.kind,
      label: item.projectName ?? (item.kind === 'personal' ? '我的事项' : '其他'),
      kind: item.kind,
      count: item.count
    })),
    dueSoon: member.dueSoonCount,
    overdue: member.overdueCount
  };
}

const view = computed(() => buildWorkbenchTeamLoadView({ members: teamLoadMembers.value.map(toTeamLoadSource) }));

// 工作台路由 keepAlive：切回不重挂，用 onActivated 替代 onMounted，每次激活经 refresh 重拉（首挂也会触发，不漏首屏）
onActivated(refresh);

const LEVEL_LABEL: Record<WorkbenchTeamLoadLevel, string> = {
  high: '高负载',
  mid: '中负载',
  normal: '正常'
};
</script>

<template>
  <WorkbenchModuleCard
    v-loading="loading"
    title="团队负载"
    icon="mdi:scale-balance"
    :editing="editing"
    @hide="$emit('hide')"
    @refresh="refresh"
  >
    <div class="tl-kpis">
      <div class="tl-kpi">
        <span class="tl-kpi__label">高负载</span>
        <span class="tl-kpi__value" :class="{ 'is-danger': view.highCount > 0 }">
          {{ view.highCount }}
          <span class="tl-kpi__unit">人</span>
        </span>
      </div>
      <div class="tl-kpi">
        <span class="tl-kpi__label">中负载</span>
        <span class="tl-kpi__value" :class="{ 'is-warn': view.midCount > 0 }">
          {{ view.midCount }}
          <span class="tl-kpi__unit">人</span>
        </span>
      </div>
      <div class="tl-kpi">
        <span class="tl-kpi__label">临期 + 逾期</span>
        <span class="tl-kpi__value" :class="{ 'is-danger': view.urgentTotal > 0 }">
          {{ view.urgentTotal }}
          <span class="tl-kpi__unit">条</span>
        </span>
      </div>
    </div>

    <ul v-if="view.members.length" class="tl-list">
      <li v-for="m in view.members" :key="m.memberId" class="tl-row">
        <span class="tl-row__dot" :class="`is-${m.level}`" :title="LEVEL_LABEL[m.level]" />
        <span class="tl-row__name">{{ m.memberName }}</span>
        <div class="tl-row__bar-wrap">
          <div class="tl-row__bar">
            <ElTooltip
              v-for="seg in m.segments"
              :key="seg.key"
              :content="`${seg.label} · ${seg.count} 个`"
              placement="top"
            >
              <div
                class="tl-row__seg"
                :style="{
                  width: `${seg.widthPercent}%`,
                  background: getWorkbenchItemColor(seg.key, seg.kind)
                }"
              />
            </ElTooltip>
          </div>
        </div>
        <span class="tl-row__metrics">
          <span class="tl-row__metric">
            <b>{{ m.inProgress }}</b>
            未完成
          </span>
          <span v-if="m.dueSoon > 0" class="tl-row__metric is-due-soon">
            <b>{{ m.dueSoon }}</b>
            临期
          </span>
          <span v-if="m.overdue > 0" class="tl-row__metric is-overdue">
            <b>{{ m.overdue }}</b>
            逾期
            <SvgIcon icon="mdi:alert" class="tl-row__warn-icon" />
          </span>
        </span>
      </li>
    </ul>
    <ElEmpty v-else description="暂无团队负载数据" :image-size="72" class="tl-empty" />

    <div class="tl-hint">
      口径 = 未完成（含待开始/已暂停）· 高 = 未完成 ≥ 6 或 临期+逾期 ≥ 2 · 中 = 未完成 ≥ 4 或 临期+逾期 ≥ 1
    </div>
  </WorkbenchModuleCard>
</template>

<style scoped>
.tl-kpis {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 10px;
  margin-bottom: 12px;
}
.tl-kpi {
  display: flex;
  flex-direction: column;
  gap: 2px;
  padding: 10px 12px;
  background: var(--el-fill-color-lighter);
  border-radius: 8px;
  min-width: 0;
}
.tl-kpi__label {
  font-size: 11px;
  color: var(--el-text-color-secondary);
}
.tl-kpi__value {
  font-size: 20px;
  font-weight: 700;
  color: var(--el-text-color-primary);
  line-height: 1.2;
}
.tl-kpi__value.is-danger {
  color: var(--el-color-danger);
}
.tl-kpi__value.is-warn {
  color: var(--el-color-warning);
}
.tl-kpi__unit {
  font-size: 12px;
  font-weight: 500;
  color: var(--el-text-color-secondary);
  margin-left: 2px;
}

.tl-list {
  list-style: none;
  margin: 0;
  padding: 0;
  flex: 1;
  min-height: 0;
  overflow: auto;
}
.tl-list::-webkit-scrollbar {
  width: 6px;
}
.tl-list::-webkit-scrollbar-thumb {
  background: var(--el-fill-color-darker);
  border-radius: 3px;
}
.tl-list::-webkit-scrollbar-thumb:hover {
  background: var(--el-border-color);
}
.tl-row {
  display: grid;
  /* 指标列固定宽：每行右侧文字宽度不同（有无临期/逾期）会让 1fr 柱子列长短不一，固定后所有柱子等长对齐 */
  grid-template-columns: 10px 64px 1fr 200px;
  align-items: center;
  gap: 10px;
  padding: 7px 0;
  font-size: 13px;
  border-bottom: 1px dashed var(--el-border-color-lighter);
}
.tl-row:last-child {
  border-bottom: none;
}
.tl-row__dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--el-color-success);
}
.tl-row__dot.is-high {
  background: var(--el-color-danger);
}
.tl-row__dot.is-mid {
  background: var(--el-color-warning);
}
.tl-row__dot.is-normal {
  background: var(--el-color-success);
}
.tl-row__name {
  color: var(--el-text-color-primary);
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.tl-row__bar-wrap {
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 0;
}
/* 柱子恒撑满整行：长度不再编码数量（数量看右侧数字），段宽表示该成员内部构成占比；无数据时为空灰槽 */
.tl-row__bar {
  width: 100%;
  height: 8px;
  border-radius: 4px;
  background: var(--el-fill-color);
  overflow: hidden;
  display: flex;
  min-width: 0;
}
.tl-row__seg {
  height: 100%;
  transition: filter 0.15s ease;
  cursor: default;
}
.tl-row__seg:hover {
  filter: brightness(0.92);
}
.tl-row__seg + .tl-row__seg {
  box-shadow: inset 1px 0 0 rgba(255, 255, 255, 0.75);
}
.tl-row__metrics {
  display: inline-flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  white-space: nowrap;
}
/* 数字统一黑色，负载等级只靠行首圆点表达；仅临期（橙）/ 逾期（红）带警示色 */
.tl-row__metric {
  display: inline-flex;
  align-items: center;
  white-space: nowrap;
}
.tl-row__metric b {
  color: var(--el-text-color-primary);
  font-weight: 600;
  margin-right: 2px;
}
/* 临期用纯橙（el-color-warning 偏黄，与"逾期红"区分度不够） */
.tl-row__metric.is-due-soon,
.tl-row__metric.is-due-soon b {
  color: rgb(234 88 12);
}
.tl-row__metric.is-overdue,
.tl-row__metric.is-overdue b {
  color: var(--el-color-danger);
}
.tl-row__warn-icon {
  margin-left: 2px;
  font-size: 12px;
  color: var(--el-color-danger);
}

.tl-hint {
  margin-top: 10px;
  font-size: 11px;
  color: var(--el-text-color-placeholder);
  line-height: 1.5;
}

.tl-empty {
  flex: 1;
  min-height: 0;
  margin: auto;
  padding: 8px 0;
}
</style>
