<template>
  <div class="app-page team-okr-workbench">
    <div class="data-toolbar">
      <span class="data-toolbar__title">团队 OKR</span>
      <span class="data-toolbar__sep">|</span>
      <span class="data-toolbar__meta">{{ subordinates.length }} 名直接下属</span>
    </div>

    <PeriodBanner v-if="periods.length" :periods="periods" v-model="selectedPeriodId" @update:model-value="selectPeriod" />
    <div v-if="!selectedPeriodId" class="empty-big">暂无进行中的考核周期</div>

    <template v-else>
      <!-- Summary bar -->
      <div class="summary-bar" v-if="subordinates.length">
        <div class="sum-item">
          <span class="sum-num okr-approved">{{ stats.approved }}</span>
          <span class="sum-label">已通过</span>
        </div>
        <div class="sum-item">
          <span class="sum-num okr-submitted">{{ stats.submitted }}</span>
          <span class="sum-label">待审核</span>
        </div>
        <div class="sum-item">
          <span class="sum-num okr-draft">{{ stats.notStarted }}</span>
          <span class="sum-label">未提交</span>
        </div>
        <div class="sum-item">
          <span class="sum-num okr-rejected">{{ stats.rejected }}</span>
          <span class="sum-label">已驳回</span>
        </div>
      </div>

      <div v-if="subordinates.length === 0" class="empty-big">暂无直接下属</div>

      <div v-for="sub in subordinates" :key="sub.id" class="sub-card">
        <div class="sub-card-head">
          <div class="sub-user">
            <span class="sub-avatar">{{ (sub.realName || '?')[0] }}</span>
            <div class="sub-info">
              <span class="sub-name">{{ sub.realName }}</span>
              <span class="sub-position">{{ sub.position || '员工' }}</span>
            </div>
          </div>
          <el-tag v-if="sub.okr" :type="okrTagType(sub.okr.status)" effect="dark" size="small" round>
            {{ okrStatusText(sub.okr.status) }}
          </el-tag>
          <el-tag v-else type="info" effect="plain" size="small" round>未制定</el-tag>
        </div>

        <div v-if="sub.okr" class="sub-okr-body">
          <div class="sub-o-title">{{ sub.okr.title }}</div>
          <div class="sub-krs">
            <div v-for="(kr, i) in sub.okr.keyResults" :key="kr.id" class="sub-kr-row">
              <span class="sub-kr-num">KR{{ i+1 }}</span>
              <span class="sub-kr-title">{{ kr.title }}</span>
              <span class="sub-kr-progress" v-if="period?.status === 'EXECUTING'">
                {{ kr.currentValue }}/{{ kr.targetValue }}
              </span>
              <el-progress v-if="period?.status === 'EXECUTING'"
                :percentage="krPercent(kr)" :color="krColor(kr.status)" :stroke-width="6" :show-text="false"
                style="width:80px;flex-shrink:0" />
              <el-tag v-if="kr.assignedToName" size="small" effect="dark" type="warning" round>
                @{{ kr.assignedToName }}
              </el-tag>
              <el-tag v-if="kr.sourceKrId" size="small" effect="plain" type="info" round>
                承接上级
              </el-tag>
            </div>
          </div>
          <div class="sub-okr-meta" v-if="sub.okr.reviewedAt">
            审核通过 · {{ sub.okr.reviewerName }} · {{ sub.okr.reviewedAt?.slice(0, 16) }}
          </div>
        </div>
        <div v-else class="sub-no-okr">
          {{ period?.status === 'OKR_ALIGN' ? '尚未提交 OKR' : '本周期未制定 OKR' }}
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { periodApi, okrApi } from '../../api'
import { ElMessage } from 'element-plus'
import PeriodBanner from '../../components/PeriodBanner.vue'

const periods = ref([])
const subordinates = ref([])
const selectedPeriodId = ref(null)

const period = computed(() => periods.value.find(p => p.id === selectedPeriodId.value))

const stats = computed(() => {
  let approved = 0, submitted = 0, notStarted = 0, rejected = 0
  for (const s of subordinates.value) {
    if (!s.okr) notStarted++
    else if (s.okr.status === 'APPROVED') approved++
    else if (s.okr.status === 'SUBMITTED') submitted++
    else if (s.okr.status === 'REJECTED') rejected++
    else notStarted++
  }
  return { approved, submitted, notStarted, rejected }
})

onMounted(async () => {
  periods.value = await periodApi.list()
  const active = periods.value.filter(p => p.status !== 'ARCHIVED')
  if (active.length) selectPeriod(active[0].id)
  else if (periods.value.length) selectPeriod(periods.value[0].id)
})

async function selectPeriod(pid) {
  selectedPeriodId.value = pid
  try {
    const okrs = await okrApi.getSubordinates(pid)
    // Build a map of userId -> okr
    const okrMap = {}
    for (const o of okrs) {
      okrMap[o.userId] = o
    }
    // Fetch actual subordinate user list from org API
    const { orgApi: oa } = await import('../../api')
    const users = await oa.getMySubordinates()
    subordinates.value = users.map(u => ({
      ...u,
      okr: okrMap[u.id] || null
    }))
  } catch {
    subordinates.value = []
  }
}

function okrTagType(s) {
  return { APPROVED: 'success', SUBMITTED: 'warning', REJECTED: 'danger', DRAFT: 'info' }[s] || 'info'
}
function okrStatusText(s) {
  return { APPROVED: '已通过', SUBMITTED: '待审核', REJECTED: '已驳回', DRAFT: '草稿' }[s] || s
}
function krPercent(kr) {
  if (!kr.targetValue || kr.targetValue === 0) return 0
  return Math.min((kr.currentValue / kr.targetValue) * 100, 100)
}
function krColor(s) {
  return { COMPLETED: 'var(--color-success)', BLOCKED: 'var(--color-warning)', IN_PROGRESS: 'var(--color-accent)', NOT_STARTED: 'var(--color-text-muted)' }[s] || 'var(--color-text-muted)'
}
</script>

<style scoped>
.page { width: 100%; }
.page-hero { margin-bottom: 16px; }
.hero-info h2 { font-size: 28px; font-weight: 700; color: var(--color-text); margin: 0; }
.hero-info p { font-size: 14px; color: var(--color-text-secondary); margin: 4px 0 0; }
.empty-big { display: flex; align-items: center; justify-content: center; height: 300px; font-size: 16px; color: var(--color-text-muted); }

/* Period Picker */
/* Summary bar */
.summary-bar { display: flex; gap: 24px; padding: 16px 20px; background: var(--color-surface); border-radius: 10px; margin-bottom: 20px; box-shadow: 0 1px 4px rgba(0,0,0,0.04); }
.sum-item { display: flex; flex-direction: column; align-items: center; }
.sum-num { font-size: 24px; font-weight: 700; }
.sum-num.okr-approved { color: var(--color-success); }
.sum-num.okr-submitted { color: var(--color-warning); }
.sum-num.okr-draft { color: var(--color-text-muted); }
.sum-num.okr-rejected { color: var(--color-danger); }
.sum-label { font-size: 12px; color: var(--color-text-muted); }

/* Subordinate cards */
.sub-card { background: var(--color-surface); border-radius: 10px; padding: 16px 20px; margin-bottom: 12px; box-shadow: 0 1px 4px rgba(0,0,0,0.04); border: 1px solid var(--color-border-soft); }
.sub-card-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; padding-bottom: 10px; border-bottom: 1px solid var(--color-border-soft); }
.sub-user { display: flex; align-items: center; gap: 10px; }
.sub-avatar { width: 32px; height: 32px; border-radius: 50%; background: var(--color-brand); color: var(--color-surface); display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 600; }
.sub-name { font-size: 15px; font-weight: 600; color: var(--color-text); }
.sub-position { font-size: 12px; color: var(--color-text-muted); }
.sub-o-title { font-size: 14px; font-weight: 600; color: var(--color-text); margin-bottom: 12px; }
.sub-krs { display: flex; flex-direction: column; gap: 10px; }
.sub-kr-row { display: flex; align-items: center; gap: 10px; padding: 8px 12px; background: var(--color-surface-subtle); border-radius: 8px; }
.sub-kr-num { font-size: 12px; font-weight: 700; color: var(--color-accent); width: 32px; flex-shrink: 0; }
.sub-kr-title { flex: 1; font-size: 13px; color: var(--color-text); }
.sub-kr-progress { font-size: 13px; color: var(--color-text-muted); flex-shrink: 0; }
.sub-okr-meta { margin-top: 10px; font-size: 12px; color: var(--color-text-muted); }
.sub-no-okr { font-size: 13px; color: var(--color-text-muted); text-align: center; padding: 16px 0; }
</style>
