<template>
  <div class="okr-detail-page">
    <div class="page-header">
      <el-button text @click="$router.back()">
        <el-icon><ArrowLeft /></el-icon> 返回
      </el-button>
      <h3>OKR 详情</h3>
    </div>

    <div v-if="loading" class="loading-wrap">
      <el-skeleton :rows="6" animated />
    </div>

    <template v-if="!loading && objective">
      <!-- 基本信息 -->
      <div class="info-card">
        <div class="info-row">
          <span class="info-label">目标</span>
          <span class="info-value">{{ objective.objective.title }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">描述</span>
          <span class="info-value">{{ objective.objective.description || '无描述' }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">维度</span>
          <el-tag size="small" :type="dimTagType(objective.objective.dimension)">
            {{ dimLabel(objective.objective.dimension) }}
          </el-tag>
        </div>
        <div class="info-row">
          <span class="info-label">季度</span>
          <span class="info-value">{{ objective.objective.quarter }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">进度</span>
          <el-progress :percentage="objective.objective.progress || 0" :stroke-width="8" style="flex:1;max-width:300px;" />
        </div>
        <div class="info-row">
          <span class="info-label">状态</span>
          <el-tag :type="statusTagType(objective.objective.status)">{{ statusLabel(objective.objective.status) }}</el-tag>
        </div>
        <div class="info-row">
          <span class="info-label">负责人</span>
          <span class="info-value">{{ objective.objective.owner || '未指定' }}</span>
        </div>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" class="detail-tabs">
        <el-tab-pane label="KR 列表" name="krs">
          <div v-if="!objective.key_results || objective.key_results.length === 0" class="empty-tab">
            暂无关联关键结果
          </div>
          <div v-else class="kr-list">
            <div v-for="kr in objective.key_results" :key="kr.id" class="kr-card">
              <div class="kr-header">
                <span class="kr-title">{{ kr.title }}</span>
                <el-tag size="small" :type="statusTagType(kr.status)">{{ statusLabel(kr.status) }}</el-tag>
              </div>
              <div class="kr-meta">
                <span v-if="kr.assignee" class="kr-meta-item">负责人: {{ kr.assignee }}</span>
                <span v-if="kr.due_date" class="kr-meta-item">截止: {{ kr.due_date.slice(0, 10) }}</span>
              </div>
              <el-progress :percentage="kr.progress || 0" :stroke-width="6" />
              <!-- 行动挂KR: KR下的达成行动 (2026-08-27) -->
              <div v-if="actionsOfKr(kr.id).length > 0" class="kr-actions">
                <div class="kr-actions-title">达成行动（{{ actionsOfKr(kr.id).length }}）</div>
                <div v-for="ap in actionsOfKr(kr.id)" :key="ap.id" class="kr-action-row">
                  <span class="kr-action-title">{{ ap.title }}</span>
                  <span v-if="ap.assignee" class="kr-action-meta">@{{ ap.assignee }}</span>
                  <el-tag size="small" :type="statusTagType(ap.status)" class="kr-action-tag">{{ statusLabel(ap.status) }}</el-tag>
                  <el-progress :percentage="ap.progress || 0" :stroke-width="4" style="width:80px;" />
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="本体追溯链" name="ontology">
          <div v-if="traceLoading" class="empty-tab">追溯链加载中...</div>
          <div v-else-if="!trace" class="empty-tab">暂无追溯链数据</div>
          <template v-else>
            <div class="chain-banner">
              <span class="chain-step">O 目标</span>
              <span class="chain-arrow">→</span>
              <span class="chain-step">KPI 指标 ({{ trace.kpis.length }})</span>
              <span class="chain-arrow">→</span>
              <span class="chain-step">科目 数据 ({{ trace.chain.subject_count }})</span>
            </div>

            <!-- KR(关键结果) -->
            <div class="trace-section" v-if="trace.krs && trace.krs.length">
              <div class="trace-section-title">关键结果 KR</div>
              <div class="kr-list">
                <div v-for="kr in trace.krs" :key="kr.id" class="kr-card">
                  <div class="kr-header">
                    <span class="kr-title">{{ kr.title }}</span>
                    <el-tag size="small" :type="statusTagType(kr.status)">{{ statusLabel(kr.status) }}</el-tag>
                  </div>
                  <div class="kr-meta">
                    <span v-if="kr.metric_kpi_name" class="kr-meta-item">度量KPI: {{ kr.metric_kpi_name }}</span>
                    <span class="kr-meta-item">目标: {{ kr.target_value }}</span>
                    <span class="kr-meta-item">当前: {{ kr.current_value }}</span>
                    <span v-if="kr.due_date" class="kr-meta-item">截止: {{ kr.due_date }}</span>
                  </div>
                  <el-progress :percentage="kr.progress || 0" :stroke-width="6" />
                </div>
              </div>
            </div>

            <!-- KPI → 科目 -->
            <div class="trace-section">
              <div class="trace-section-title">KPI → 科目（指标追溯到底层账）</div>
              <div v-for="k in trace.kpis" :key="k.kpi_id" class="kpi-trace-card">
                <div class="kpi-trace-head">
                  <span class="kpi-trace-code">{{ k.kpi_code }}</span>
                  <span class="kpi-trace-name">{{ k.kpi_name }}</span>
                  <el-tag size="small" :type="dimTagType(k.dimension)">{{ dimLabel(k.dimension) }}</el-tag>
                  <span v-if="k.unit" class="kpi-trace-unit">{{ k.unit }}</span>
                </div>
                <div v-if="k.subjects && k.subjects.length" class="subject-chips">
                  <el-tag v-for="s in k.subjects" :key="s.subject_code" size="small" effect="plain" class="subject-chip">
                    {{ s.subject_code }} {{ s.subject_name }}
                    <span class="subject-calc">({{ s.calc_type }}, {{ s.weight }})</span>
                  </el-tag>
                </div>
                <div v-else class="no-subject">非科目驱动指标（业务/调研数据源，不追溯账本）</div>
              </div>
            </div>
          </template>
        </el-tab-pane>
        <el-tab-pane label="分解视图" name="decomposition">
          <OkrDecomposition :okr-id="okrId" @refresh="loadData" />
        </el-tab-pane>
      </el-tabs>
    </template>

    <div v-if="!loading && !objective" class="not-found">
      <el-empty description="OKR不存在" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { okrApi, ontologyApi, actionPlanApi } from '../api/index'
import OkrDecomposition from '../components/okr/OkrDecomposition.vue'

const route = useRoute()
const okrId = computed(() => Number(route.params.id))

const loading = ref(true)
const objective = ref<any>(null)
const trace = ref<any>(null)
const traceLoading = ref(false)
const activeTab = ref('krs')
const actionPlans = ref<any[]>([])

// KR下的行动列表（行动挂KR 2026-08-27: O→KR→行动三层）
function actionsOfKr(krId: number) {
  return actionPlans.value.filter((p: any) => p.kr_id === krId)
}

const DIM_LABELS: Record<string, string> = {
  finance: '财务层', customer: '客户层', process: '流程层', learning: '学习成长层',
}

function dimLabel(d: string) { return DIM_LABELS[d] || d }
function dimTagType(d: string) {
  const types: Record<string, string> = { finance: 'danger', customer: 'primary', process: 'success', learning: 'warning' }
  return types[d] || ''
}
function statusLabel(s: string) {
  const labels: Record<string, string> = { active: '进行中', completed: '已完成', cancelled: '已取消', in_progress: '进行中', pending: '待开始' }
  return labels[s] || s
}
function statusTagType(s: string) {
  const types: Record<string, string> = { active: 'warning', completed: 'success', cancelled: 'danger', in_progress: 'warning', pending: 'info' }
  return types[s] || ''
}

async function loadData() {
  if (!okrId.value) return
  loading.value = true
  try {
    const res: any = await okrApi.get(okrId.value)
    objective.value = res
  } catch (e: any) {
    ElMessage.error('加载失败: ' + (e?.response?.data?.detail || e?.message || ''))
    objective.value = null
  } finally {
    loading.value = false
  }
}

// 加载行动方案（按kr_id关联，供KR下展示）
async function loadActions() {
  try {
    const r: any = await actionPlanApi.list({ page_size: 500 })
    actionPlans.value = r.data || []
  } catch {}
}

async function loadTrace() {
  if (!okrId.value) return
  traceLoading.value = true
  try {
    const res: any = await ontologyApi.trace(okrId.value)
    trace.value = res
  } catch (e: any) {
    ElMessage.warning('追溯链加载失败: ' + (e?.response?.data?.detail || e?.message || ''))
    trace.value = null
  } finally {
    traceLoading.value = false
  }
}

onMounted(() => {
  loadData()
  loadTrace()
  loadActions()
})
</script>

<style scoped>
.okr-detail-page {
  padding: 16px 20px;
}
.page-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
}
.page-header h3 {
  margin: 0;
  font-size: 18px;
}
.loading-wrap {
  padding: 40px;
}

/* ── 信息卡片 ── */
.info-card {
  background: #FAFBFC;
  border: 1px solid #EBEEF5;
  border-radius: 10px;
  padding: 16px 20px;
  margin-bottom: 20px;
}
.info-row {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #F0F0F0;
}
.info-row:last-child {
  border-bottom: none;
}
.info-label {
  width: 60px;
  font-size: 13px;
  color: #909399;
  flex-shrink: 0;
}
.info-value {
  font-size: 13px;
}

/* ── 标签页 ── */
.detail-tabs {
  margin-top: 4px;
}

/* ── KR列表 ── */
.kr-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.kr-card {
  background: #fff;
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  padding: 14px 16px;
}
.kr-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}
.kr-title {
  font-weight: 500;
  font-size: 14px;
}
.kr-meta {
  display: flex;
  gap: 14px;
  margin-bottom: 8px;
}
.kr-meta-item {
  font-size: 12px;
  color: #909399;
}
/* ── KR下的达成行动 ── */
.kr-actions {
  margin-top: 8px;
  padding: 8px 10px;
  background: #f8fafc;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}
.kr-actions-title {
  font-size: 12px;
  color: #409eff;
  font-weight: 500;
  margin-bottom: 4px;
}
.kr-action-row {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 3px 0;
  font-size: 12px;
}
.kr-action-title {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.kr-action-meta {
  color: #909399;
  font-size: 11px;
}
.kr-action-tag {
  flex-shrink: 0;
}
.empty-tab {
  text-align: center;
  color: #C0C4CC;
  padding: 40px 0;
  font-size: 14px;
}

/* ── 本体追溯链 ── */
.chain-banner {
  display: flex;
  align-items: center;
  gap: 10px;
  background: linear-gradient(90deg, #f0f5ff, #f6ffed);
  border: 1px solid #d9e8ff;
  border-radius: 8px;
  padding: 12px 16px;
  margin-bottom: 16px;
  font-size: 13px;
}
.chain-step {
  font-weight: 600;
  color: #303133;
}
.chain-arrow {
  color: #409EFF;
  font-weight: 700;
}
.trace-section {
  margin-bottom: 18px;
}
.trace-section-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
  padding-left: 8px;
  border-left: 3px solid #409EFF;
}
.kpi-trace-card {
  background: #fff;
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  padding: 12px 14px;
  margin-bottom: 10px;
}
.kpi-trace-head {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}
.kpi-trace-code {
  font-family: 'JetBrains Mono', Consolas, monospace;
  font-weight: 700;
  font-size: 13px;
  color: #409EFF;
  background: #ecf5ff;
  padding: 2px 8px;
  border-radius: 4px;
}
.kpi-trace-name {
  font-weight: 500;
  font-size: 14px;
}
.kpi-trace-unit {
  font-size: 12px;
  color: #909399;
}
.subject-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.subject-chip {
  font-size: 12px;
}
.subject-calc {
  color: #909399;
  margin-left: 2px;
}
.no-subject {
  font-size: 12px;
  color: #C0C4CC;
}
.not-found {
  padding: 60px 0;
}
</style>
