<template>
  <div class="app-page feedback-workbench">
    <div class="page-hero">
      <div class="hero-info">
        <h2>绩效沟通</h2>
        <p>下属面谈记录与反馈</p>
      </div>
    </div>

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

    <div v-if="subordinates.length === 0" class="empty-state">暂无下属数据</div>

    <el-table v-else :data="subordinates" stripe @row-click="selectUser" style="width:100%" class="data-table">
      <el-table-column prop="targetUser.realName" label="姓名" min-width="100" show-overflow-tooltip />
      <el-table-column prop="targetUser.position" label="职位" min-width="120" show-overflow-tooltip />
      <el-table-column label="最终得分" min-width="150" align="center">
        <template #default="{ row }">
          <template v-if="row.finalScore">
            <span class="grade-chip" :class="'g-'+row.finalScore.grade">{{ row.finalScore.grade }}</span>
            <strong>{{ row.finalScore.total }} 分</strong>
          </template>
          <span v-else class="text-muted">未评</span>
        </template>
      </el-table-column>
      <el-table-column label="亮点" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">{{ row.feedback?.highlights || '--' }}</template>
      </el-table-column>
      <el-table-column label="待改进" min-width="200" show-overflow-tooltip>
        <template #default="{ row }">{{ row.feedback?.issues || '--' }}</template>
      </el-table-column>
      <el-table-column label="面谈状态" min-width="110" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.feedback?.status" :type="feedbackStatusType(row.feedback.status)" effect="plain" size="small" round>
            {{ feedbackStatusLabel(row.feedback.status) }}
          </el-tag>
          <el-tag v-else-if="row.feedback?.interviewNotes" type="warning" effect="plain" size="small" round>待回复</el-tag>
          <el-tag v-else type="info" effect="plain" size="small" round>待记录</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="showDialog" :title="'绩效沟通 · ' + selectedUser?.targetUser?.realName" width="900px" top="5vh">
      <div class="same-screen" v-if="selectedUser">
        <div class="okr-panel">
          <div class="panel-head">OKR 记录 & 得分</div>
          <div v-for="o in selectedUser.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>{{ kr.currentValue }}/{{ kr.targetValue }}</span>
            </div>
          </div>
          <div v-if="selectedUser.finalScore" class="mini-score-line">
            总分 {{ selectedUser.finalScore.total }} · {{ selectedUser.finalScore.grade }}
          </div>
        </div>
        <div class="form-panel">
          <div class="panel-head">面谈记录</div>
          <el-form label-position="top">
            <el-form-item label="亮点">
              <el-input v-model="form.highlights" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="待改进">
              <el-input v-model="form.issues" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="改进建议">
              <el-input v-model="form.improvements" type="textarea" :rows="2" />
            </el-form-item>
            <el-form-item label="面谈纪要">
              <el-input v-model="form.interviewNotes" type="textarea" :rows="3" />
            </el-form-item>
            <el-form-item v-if="selectedUser.feedback?.employeeFeedback" label="员工反馈">
              <div class="employee-reply">{{ selectedUser.feedback.employeeFeedback }}</div>
            </el-form-item>
          </el-form>
          <div class="dialog-actions">
            <el-button type="primary" size="large" @click="handleSave" :loading="saving" round>保存面谈记录</el-button>
            <el-button
              v-if="selectedUser.feedback?.employeeFeedback && selectedUser.feedback?.status !== 'CLOSED'"
              type="success"
              size="large"
              @click="handleClose"
              :loading="closing"
              round
            >
              关闭面谈
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

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

const periods = ref([])
const periodId = ref(null)
const subordinates = ref([])
const selectedUser = ref(null)
const showDialog = ref(false)
const saving = ref(false)
const closing = ref(false)
const form = ref({ highlights: '', issues: '', improvements: '', interviewNotes: '' })

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 loadSubordinates() }
})

async function loadSubordinates() {
  if (!periodId.value) return
  subordinates.value = await scoreApi.getSubordinates(periodId.value)
}

async function selectUser(row) {
  const full = await feedbackApi.getPage(periodId.value, row.targetUser.id)
  selectedUser.value = full
  form.value = {
    highlights: full.feedback?.highlights || '',
    issues: full.feedback?.issues || '',
    improvements: full.feedback?.improvements || '',
    interviewNotes: full.feedback?.interviewNotes || ''
  }
  showDialog.value = true
}

async function handleSave() {
  saving.value = true
  try {
    await feedbackApi.saveInterview({
      periodId: periodId.value,
      userId: selectedUser.value.targetUser.id,
      ...form.value
    })
    ElMessage.success('面谈记录已保存')
    showDialog.value = false
    loadSubordinates()
  } finally { saving.value = false }
}

async function handleClose() {
  closing.value = true
  try {
    await feedbackApi.close({
      periodId: periodId.value,
      userId: selectedUser.value.targetUser.id
    })
    ElMessage.success('面谈已关闭')
    showDialog.value = false
    loadSubordinates()
  } finally { closing.value = false }
}

function feedbackStatusLabel(status) {
  return {
    PENDING_EMPLOYEE: '待回复',
    REPLIED: '待关闭',
    CLOSED: '已关闭'
  }[status] || status
}

function feedbackStatusType(status) {
  return {
    PENDING_EMPLOYEE: 'warning',
    REPLIED: 'primary',
    CLOSED: 'success'
  }[status] || 'info'
}
</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: 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-state { display: flex; align-items: center; justify-content: center; height: 300px; color: var(--color-text-muted); font-size: 15px; background: var(--color-surface); border-radius: 8px; }
.text-muted { color: var(--color-text-muted); }
.data-table { border-radius: 8px; overflow: hidden; }
.data-table :deep(th) { white-space: nowrap; font-weight: 600; color: var(--color-text-secondary); background: var(--color-surface-subtle); }
.data-table :deep(td) { cursor: pointer; }
.grade-chip { display: inline-block; width: 24px; height: 24px; line-height: 24px; border-radius: 6px; font-weight: 700; font-size: 13px; color: var(--color-surface); margin-right: 6px; text-align: center; }
.g-S { background: var(--color-grade-s); color: var(--color-grade-s); }
.g-A { background: var(--color-success); }
.g-B { background: var(--color-info); }
.g-C { background: var(--color-danger); }

.same-screen { display: flex; gap: 20px; }
.okr-panel { flex: 1; max-height: 500px; overflow-y: auto; }
.form-panel { width: 440px; flex-shrink: 0; }
.panel-head { font-weight: 700; font-size: 14px; color: var(--color-text); margin-bottom: 12px; }
.mini-okr { padding: 8px; margin-bottom: 6px; background: var(--color-surface-subtle); border-radius: 6px; border: 1px solid var(--color-border-soft); font-size: 12px; }
.mini-o { font-weight: 600; color: var(--color-brand); }
.mini-kr { display: flex; justify-content: space-between; color: var(--color-text-secondary); padding: 1px 0; }
.mini-score-line { margin-top: 8px; text-align: center; font-weight: 700; font-size: 16px; color: var(--color-brand); }
.employee-reply { width: 100%; padding: 10px 12px; border-radius: 8px; background: var(--color-surface-tint-info); border: 1px solid var(--color-accent-soft); color: var(--color-medical); line-height: 1.6; }
.dialog-actions { display: flex; gap: 10px; align-items: center; }
</style>
