<template>
  <div class="app-page result-workbench">
    <div class="page-hero">
      <div class="hero-info">
        <h2>我的绩效</h2>
        <p>{{ data.period ? (data.period.name + ' · ' + data.period.startDate + ' ~ ' + data.period.endDate) : '数据驱动，结果可追溯' }}</p>
      </div>
      <el-button @click="$router.push('/scores/history')" round>历史记录</el-button>
    </div>

    <PeriodBanner v-if="periods.length" :periods="periods" v-model="periodId" @update:model-value="load" />

    <div v-if="!data.period" class="empty-state">暂无绩效数据，请选择周期</div>

    <!-- SELF-ASSESSMENT FORM (ASSESSING + no self submitted) -->
    <template v-else-if="showSelfForm">
      <div class="form-banner">请完成绩效自评后提交，上级将在此基础进行终审</div>

      <div class="form-card">
        <div class="form-section-title">OKR 目标达成自评 <span class="fst-sub">逐条 KR 打分（0.0-1.0），满分 40</span></div>
        <div v-if="okrRecords.length" class="kr-score-list">
          <div v-for="(kr, i) in okrRecords[0].keyResults" :key="kr.id" class="kr-score-row">
            <div class="ksr-label">
              <span class="ksr-num">KR{{ i+1 }}</span>
              <span class="ksr-title">{{ kr.title }}</span>
              <span class="ksr-progress">{{ kr.currentValue }}/{{ kr.targetValue }} ({{ kr.status }})</span>
            </div>
            <div class="ksr-inputs">
              <el-select v-model="krScores[i].score" size="default" style="width:120px">
                <el-option label="1.0 · 卓越" :value="1.0" />
                <el-option label="0.8 · 良好" :value="0.8" />
                <el-option label="0.6 · 达标" :value="0.6" />
                <el-option label="0.3 · 少量推进" :value="0.3" />
                <el-option label="0.0 · 未做" :value="0.0" />
              </el-select>
              <span class="ksr-eq">= {{ (krScores[i].score * 40 / okrRecords[0].keyResults.length).toFixed(1) }} 分</span>
            </div>
          </div>
        </div>
        <div v-else class="no-okr-hint">暂无 OKR 记录</div>
        <div class="okr-subtotal">
          OKR 得分 = 平均 {{ krAvg.toFixed(2) }} × 40 = <strong>{{ okrTotal.toFixed(1) }} / 40</strong>
        </div>
      </div>

      <div class="form-card">
        <div class="form-section-title">工作成果自评 <span class="fst-sub">按维度自述 + 打分，满分 60</span></div>
        <div v-for="(dim, i) in dimScores" :key="i" class="dim-row">
          <div class="dim-head">
            <span class="dim-num">{{ i+1 }}</span>
            <span class="dim-name">{{ dim.name }}</span>
            <span class="dim-max">满分 {{ dim.maxScore }} 分</span>
          </div>
          <el-input v-model="dim.description" type="textarea" :rows="2" :placeholder="'简述' + dim.name + '方面的工作成果'" style="margin-bottom:6px" />
          <el-input-number v-model="dim.score" :min="0" :max="dim.maxScore" :precision="1" size="small" controls-position="right" style="width:130px" />
          <span class="dim-score-hint">/ {{ dim.maxScore }} 分</span>
        </div>
        <div class="okr-subtotal">
          工作成果得分 = <strong>{{ dimTotal.toFixed(1) }} / 60</strong>
        </div>
      </div>

      <div class="form-card">
        <div class="form-section-title">专项加减分</div>
        <div class="bonus-row">
          <span class="bonus-label">加分（上限5）</span>
          <el-input-number v-model="form.bonus" :min="0" :max="5" :precision="1" size="large" controls-position="right" />
          <span class="bonus-label">扣分</span>
          <el-input-number v-model="form.penalty" :min="0" :precision="1" size="large" controls-position="right" />
        </div>
        <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="加减分说明" style="margin-top:8px" />
      </div>

      <div class="result-preview">
        <div class="rp-formula">OKR（{{ okrTotal.toFixed(1) }}）+ 工作成果（{{ dimTotal.toFixed(1) }}）+ 加分（{{ form.bonus }}）− 扣分（{{ form.penalty }}）</div>
        <div class="rp-score">{{ computedTotal }} <small>/ 100</small></div>
        <div class="rp-grade">自评评级 <strong>{{ computedGrade }}</strong></div>
      </div>

      <div class="submit-row">
        <el-button type="primary" size="large" @click="handleSelfSubmit" :loading="submitting" round>
          提交自评
        </el-button>
        <span class="submit-hint">提交后由直属上级审核终评</span>
      </div>
    </template>

    <!-- RESULT VIEW (has self or final score) -->
    <div v-else class="dashboard">
      <div class="score-hero" v-if="data.finalScore">
        <div class="grade-ring" :class="'grade-'+data.finalScore.grade">
          <span class="grade-letter">{{ data.finalScore.grade }}</span>
        </div>
        <div class="score-main">
          <div class="score-number">{{ data.finalScore.total }}<small> / 100</small></div>
          <div class="score-label">{{ gradeDesc(data.finalScore.grade) }}</div>
          <div class="score-meta">{{ data.period?.name }} · {{ data.period?.startDate }} ~ {{ data.period?.endDate }}</div>
        </div>
        <div class="score-breakdown">
          <div class="break-item">
            <span class="break-label">OKR 得分</span>
            <span class="break-value">{{ data.finalScore.okrScore }}<small> / 40</small></span>
          </div>
          <div class="break-item">
            <span class="break-label">工作成果</span>
            <span class="break-value">{{ data.finalScore.kpiScore }}<small> / 60</small></span>
          </div>
          <div class="break-item bonus">
            <span class="break-label">专项加分</span>
            <span class="break-value">+{{ data.finalScore.bonus }}</span>
          </div>
          <div class="break-item penalty">
            <span class="break-label">专项扣分</span>
            <span class="break-value">-{{ data.finalScore.penalty }}</span>
          </div>
        </div>
      </div>

      <div v-else-if="data.selfScore" class="score-hero self-submitted">
        <div class="pending-icon pending-icon--submitted" aria-hidden="true">
          <svg viewBox="0 0 48 48" focusable="false">
            <path d="M12 34h24M16 26l8-8 8 8M24 18v20M14 10h20a4 4 0 0 1 4 4v4M10 18v-4a4 4 0 0 1 4-4" />
          </svg>
        </div>
        <div class="score-main">
          <div class="score-number">{{ data.selfScore.total }}<small> / 100</small></div>
          <div class="score-label">自评已提交，等待上级终审</div>
        </div>
      </div>

      <div v-else class="score-pending">
        <div class="pending-icon"></div>
        <div class="pending-text">绩效考核尚未完成</div>
      </div>

      <div v-if="data.finalScore && !data.finalScore.confirmedAt" class="confirm-bar">
        <div class="confirm-info">
          <span class="confirm-icon"><el-icon><Check /></el-icon></span>
          <span>你的绩效结果如上，请审阅无误后确认。确认后本轮考核流程结束。</span>
        </div>
        <div class="confirm-actions">
          <el-button type="warning" size="large" plain @click="handleAppeal" :loading="appealing" round>提交申诉</el-button>
          <el-button type="success" size="large" @click="handleConfirm" :loading="confirming" round>确认绩效结果</el-button>
        </div>
      </div>
      <div v-else-if="data.finalScore?.confirmedAt" class="confirmed-bar">
        <span>已确认 · {{ data.finalScore.confirmedAt?.slice(0, 16) }}</span>
      </div>

      <div class="compare-row" v-if="data.selfScore && data.finalScore">
        <div class="compare-card self">
          <div class="compare-label">自评</div>
          <div class="compare-score">{{ data.selfScore.total }}<small>分</small></div>
        </div>
        <div class="compare-arrow">→</div>
        <div class="compare-card final">
          <div class="compare-label">终审</div>
          <div class="compare-score">{{ data.finalScore.total }}<small>分</small></div>
        </div>
      </div>

      <div class="two-col">
        <div class="col okr-col">
          <div class="col-head">当期 OKR 记录</div>
          <div v-for="o in data.okrRecords || []" :key="o.id" class="mini-okr">
            <div class="mini-o">{{ o.title }}</div>
            <div v-for="kr in o.keyResults" :key="kr.id" class="mini-kr">
              <span>{{ kr.title }}</span>
              <span class="mini-val">{{ kr.currentValue }}/{{ kr.targetValue }}</span>
            </div>
          </div>
        </div>
        <div class="col feedback-col">
          <div class="col-head">面谈反馈</div>
          <div v-if="data.feedback?.interviewNotes" class="fb-content">
            <div class="fb-block" v-if="data.feedback.highlights">
              <div class="fb-label">亮点</div>
              <div class="fb-text">{{ data.feedback.highlights }}</div>
            </div>
            <div class="fb-block" v-if="data.feedback.issues">
              <div class="fb-label">待改进</div>
              <div class="fb-text">{{ data.feedback.issues }}</div>
            </div>
            <div class="fb-block" v-if="data.feedback.improvements">
              <div class="fb-label">改进建议</div>
              <div class="fb-text">{{ data.feedback.improvements }}</div>
            </div>
            <div class="fb-block" v-if="data.feedback.interviewNotes">
              <div class="fb-label">面谈纪要</div>
              <div class="fb-text">{{ data.feedback.interviewNotes }}</div>
            </div>
          </div>
          <div v-else class="fb-empty">暂无面谈记录</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { periodApi, scoreApi, dimensionApi, scoreAppealApi } from '../../api'
import { ElMessage, ElMessageBox } from 'element-plus'
import PeriodBanner from '../../components/PeriodBanner.vue'

const periods = ref([])
const periodId = ref(null)
const data = ref({})
const confirming = ref(false)
const appealing = ref(false)
const submitting = ref(false)
const dimensions = ref([])
const krScores = ref([])
const dimScores = ref([])
const form = reactive({ bonus: 0, penalty: 0, remark: '' })

const okrRecords = computed(() => data.value.okrRecords || [])

// Show self-assessment form when ASSESSING and no self score submitted
const showSelfForm = computed(() => {
  return data.value.period?.status === 'ASSESSING' && !data.value.selfScore
})

const krAvg = computed(() => {
  if (!krScores.value.length) return 0
  const sum = krScores.value.reduce((a, b) => a + b.score, 0)
  return sum / krScores.value.length
})

const okrTotal = computed(() => {
  if (okrRecords.value.length && okrRecords.value[0].keyResults?.length) {
    const n = okrRecords.value[0].keyResults.length
    const sum = krScores.value.reduce((a, b) => a + b.score, 0)
    return Math.round(sum / n * 40 * 10) / 10
  }
  return 0
})

const dimTotal = computed(() => {
  return Math.round(dimScores.value.reduce((s, d) => s + (d.score || 0), 0) * 10) / 10
})

const computedTotal = computed(() => {
  return Math.round((okrTotal.value + dimTotal.value + form.bonus - form.penalty) * 10) / 10
})

const computedGrade = computed(() => {
  const t = computedTotal.value
  if (t >= 90) return 'S'
  if (t >= 75) return 'A'
  if (t >= 60) return 'B'
  return 'C'
})

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

async function load() {
  if (!periodId.value) return
  data.value = await scoreApi.getMyResult(periodId.value)

  // Load dimensions and init form state
  dimensions.value = await dimensionApi.list()
  dimScores.value = dimensions.value.map(d => ({
    id: d.id, name: d.name, maxScore: d.maxScore,
    score: 0, description: ''
  }))

  // Init KR scores from OKR records
  const okrs = data.value.okrRecords || []
  if (okrs.length && okrs[0].keyResults?.length) {
    krScores.value = okrs[0].keyResults.map(kr => ({ title: kr.title, score: 0.6 }))
  } else {
    krScores.value = []
  }
}

async function handleSelfSubmit() {
  if (dimScores.value.some(d => !d.description.trim())) {
    ElMessage.warning('请为每个维度填写工作成果自述')
    return
  }
  submitting.value = true
  try {
    const dimItems = dimScores.value.map(d => ({
      dimensionId: d.id, name: d.name, maxScore: d.maxScore,
      score: d.score, description: d.description
    }))
    await scoreApi.submitSelf({
      periodId: periodId.value,
      okrScore: okrTotal.value,
      kpiScore: dimTotal.value,
      bonus: form.bonus,
      penalty: form.penalty,
      commentsJson: JSON.stringify({
        krScores: krScores.value,
        dimensions: dimItems,
        remark: form.remark
      })
    })
    ElMessage.success('自评已提交，等待上级终审')
    await load()
  } finally { submitting.value = false }
}

async function handleConfirm() {
  confirming.value = true
  try {
    await scoreApi.confirm({ periodId: periodId.value })
    ElMessage.success('绩效结果已确认，本轮流程结束')
    await load()
  } finally { confirming.value = false }
}

async function handleAppeal() {
  const { value } = await ElMessageBox.prompt('请说明你对本次绩效结果的异议', '提交绩效申诉', {
    inputType: 'textarea',
    inputPlaceholder: '请描述需要复核的分数、事实依据或沟通记录',
    confirmButtonText: '提交申诉',
    cancelButtonText: '取消'
  })
  appealing.value = true
  try {
    await scoreAppealApi.submit({ periodId: periodId.value, reason: value })
    ElMessage.success('申诉已提交，HR 将收到通知')
  } finally { appealing.value = false }
}

function gradeDesc(g) {
  return { S: '卓越产出 · 团队标杆', A: '超出预期 · 高质量完成', B: '符合预期 · 满足岗位要求', C: '未达预期 · 需整改辅导' }[g] || ''
}
</script>

<style scoped>
.page { width: 100%; }
.page-hero { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 24px; }
.hero-info h2 { font-size: var(--font-size-2xl); font-weight: 700; color: var(--color-text); margin: 0; }
.hero-info p { font-size: var(--font-size-base); color: var(--color-text-secondary); margin: 4px 0 0; }
.empty-state { display: flex; align-items: center; justify-content: center; height: 300px; color: var(--color-text-muted); font-size: 15px; }

.form-banner { padding: 14px 20px; background: var(--color-surface-tint-info); border-radius: var(--radius-md); font-size: var(--font-size-base); color: var(--color-medical); border: 1px solid var(--color-border-soft); margin-bottom: 20px; }
.form-card { background: var(--color-surface); border-radius: var(--radius-md); padding: 20px 24px; margin-bottom: 16px; box-shadow: var(--shadow-panel); border: 1px solid var(--color-border-soft); }
.form-section-title { font-size: 15px; font-weight: 700; color: var(--color-text); margin-bottom: 16px; }
.fst-sub { font-size: var(--font-size-xs); color: var(--color-text-muted); font-weight: 400; }

.kr-score-row { display: flex; align-items: center; justify-content: space-between; padding: 10px 0; border-top: 1px solid var(--color-border-soft); }
.kr-score-row:first-child { border-top: none; }
.ksr-label { flex: 1; min-width: 0; }
.ksr-num { font-size: var(--font-size-xs); font-weight: 700; color: var(--color-accent); margin-right: 6px; }
.ksr-title { font-size: var(--font-size-sm); color: var(--color-text); }
.ksr-progress { font-size: 11px; color: var(--color-text-muted); margin-left: 6px; }
.ksr-inputs { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
.ksr-eq { font-size: var(--font-size-xs); color: var(--color-text-muted); white-space: nowrap; }
.no-okr-hint { font-size: var(--font-size-sm); color: var(--color-text-muted); padding: 20px 0; text-align: center; }
.okr-subtotal { text-align: right; font-size: var(--font-size-base); color: var(--color-brand); padding-top: 12px; border-top: 1px dashed var(--color-border); margin-top: 8px; }

.dim-row { padding: 14px 0; border-top: 1px solid var(--color-border-soft); }
.dim-row:first-child { border-top: none; }
.dim-head { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
.dim-num { width: 22px; height: 22px; border-radius: 50%; background: var(--color-brand); color: var(--color-white); display: flex; align-items: center; justify-content: center; font-size: var(--font-size-xs); font-weight: 700; }
.dim-name { font-size: var(--font-size-base); font-weight: 600; color: var(--color-text); }
.dim-max, .dim-score-hint, .bonus-label, .submit-hint { font-size: var(--font-size-sm); color: var(--color-text-muted); }
.bonus-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }

.result-preview {
  background: var(--color-surface-tint-brand);
  border-radius: var(--radius-md);
  padding: 20px;
  text-align: center;
  border: 1px solid var(--color-border-soft);
  margin-bottom: 16px;
}
.rp-formula { font-size: var(--font-size-xs); color: var(--color-text-secondary); }
.rp-score { font-size: 40px; font-weight: 700; color: var(--color-brand); margin: 6px 0; line-height: 1; }
.rp-score small { font-size: var(--font-size-xl); color: var(--color-text-muted); font-weight: 400; }
.rp-grade { font-size: var(--font-size-base); color: var(--color-text-secondary); }
.submit-row { display: flex; align-items: center; gap: 16px; }

.score-hero {
  display: flex; align-items: center; gap: 32px;
  background: var(--color-surface-tint-brand);
  border-radius: var(--radius-md);
  padding: 32px 40px; margin-bottom: 24px; border: 1px solid var(--color-border-soft);
}
.score-hero.self-submitted { background: var(--color-surface-tint-warning); border-color: var(--color-border-soft); }
.grade-ring {
  width: 100px; height: 100px; border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  border: 4px solid var(--color-border); flex-shrink: 0;
  background: var(--color-surface);
}
.grade-ring.grade-S { border-color: var(--color-grade-s); background: var(--color-surface-tint-success); }
.grade-ring.grade-A { border-color: var(--color-grade-a); background: var(--color-surface-tint-success); }
.grade-ring.grade-B { border-color: var(--color-grade-b); background: var(--color-surface-tint-brand); }
.grade-ring.grade-C { border-color: var(--color-grade-c); background: var(--color-surface-tint-danger); }
.grade-letter { font-size: 48px; font-weight: 700; color: var(--color-text); }

.score-main { flex: 1; }
.score-number { font-size: 48px; font-weight: 700; color: var(--color-text); line-height: 1; }
.score-number small { font-size: 20px; color: var(--color-text-muted); font-weight: 400; }
.score-label { font-size: 15px; color: var(--color-text-secondary); margin: 6px 0; }
.score-meta { font-size: var(--font-size-sm); color: var(--color-text-muted); }
.score-breakdown { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 16px; flex-shrink: 0; }
.break-item { text-align: right; }
.break-label { font-size: var(--font-size-xs); color: var(--color-text-muted); display: block; }
.break-value { font-size: var(--font-size-xl); font-weight: 600; color: var(--color-text); }
.break-value small { font-size: var(--font-size-xs); color: var(--color-text-muted); font-weight: 400; }
.break-item.bonus .break-value { color: var(--color-success); }
.break-item.penalty .break-value { color: var(--color-danger); }

.score-pending {
  background: var(--color-surface); border-radius: var(--radius-md); padding: 60px; text-align: center;
  margin-bottom: 24px; border: 1px solid var(--color-border-soft);
}
.pending-icon { width: 48px; height: 48px; margin: 0 auto 12px; color: var(--color-warning); }
.pending-icon svg { width: 48px; height: 48px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.pending-text { font-size: 15px; color: var(--color-text-muted); }

.confirm-bar {
  display: flex; align-items: center; justify-content: space-between;
  background: var(--color-surface-tint-warning); border: 1px solid var(--color-border-soft); border-radius: var(--radius-md);
  padding: 18px 24px; margin-bottom: 24px;
}
.confirm-info { display: flex; align-items: center; gap: 10px; font-size: var(--font-size-base); color: var(--color-warning); }
.confirm-icon { font-size: 20px; }
.confirm-actions { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }
.confirmed-bar {
  background: var(--color-surface-tint-success); border: 1px solid var(--color-border-soft); border-radius: var(--radius-md);
  padding: 14px 24px; text-align: center; font-size: var(--font-size-base); color: var(--color-success); margin-bottom: 24px;
}

.compare-row { display: flex; align-items: center; justify-content: center; gap: 20px; margin-bottom: 24px; }
.compare-card { background: var(--color-surface); border-radius: var(--radius-md); padding: 16px 28px; text-align: center; box-shadow: var(--shadow-panel); border: 1px solid var(--color-border-soft); }
.compare-card.self { border-left: 4px solid var(--color-info); }
.compare-card.final { border-left: 4px solid var(--color-success); }
.compare-label { font-size: var(--font-size-xs); color: var(--color-text-muted); margin-bottom: 4px; }
.compare-score { font-size: 28px; font-weight: 700; color: var(--color-text); }
.compare-score small { font-size: var(--font-size-base); color: var(--color-text-muted); font-weight: 400; }
.compare-arrow { font-size: 24px; color: var(--color-text-muted); }

.two-col { display: flex; gap: 20px; }
.col { flex: 1; background: var(--color-surface); border-radius: var(--radius-md); padding: 20px 24px; box-shadow: var(--shadow-panel); border: 1px solid var(--color-border-soft); }
.col-head { font-size: 15px; font-weight: 700; color: var(--color-text); margin-bottom: 16px; }
.mini-okr { padding: 10px; margin-bottom: 10px; background: var(--color-surface-subtle); border-radius: var(--radius-md); border: 1px solid var(--color-border-soft); }
.mini-o { font-weight: 600; font-size: var(--font-size-sm); color: var(--color-brand); margin-bottom: 6px; }
.mini-kr { display: flex; justify-content: space-between; font-size: var(--font-size-xs); color: var(--color-text-secondary); padding: 2px 0; }
.mini-val { color: var(--color-text-muted); }
.fb-block { margin-bottom: 14px; }
.fb-label { font-size: 11px; font-weight: 600; color: var(--color-accent-strong); text-transform: uppercase; letter-spacing: 0; margin-bottom: 4px; }
.fb-text { font-size: var(--font-size-sm); color: var(--color-text-secondary); line-height: 1.6; }
.fb-empty { color: var(--color-text-muted); font-size: var(--font-size-sm); text-align: center; padding: 30px; }

@media (max-width: 860px) {
  .score-hero { flex-direction: column; text-align: center; }
  .score-breakdown { grid-template-columns: 1fr; }
  .two-col { flex-direction: column; }
}
</style>
