<template>
  <div class="app-page template-workbench">
    <div class="page-header">
      <h3>绩效模板</h3>
      <el-button type="primary" @click="openCreate"><el-icon><Plus /></el-icon> 添加模板</el-button>
    </div>

    <!-- Category filter chips -->
    <div class="filter-bar" v-if="categories.length > 1">
      <span class="filter-label">岗位筛选：</span>
      <el-radio-group v-model="selectedCategory" size="small" @change="onFilterChange">
        <el-radio-button value="">全部（{{ templates.length }}）</el-radio-button>
        <el-radio-button v-for="cat in categories" :key="cat" :value="cat">
          {{ cat }}（{{ countByCategory(cat) }}）
        </el-radio-button>
      </el-radio-group>
    </div>

    <div v-if="filteredTemplates.length === 0" class="empty">暂无 KPI 模板</div>

    <el-row :gutter="16">
      <el-col v-for="t in filteredTemplates" :key="t.id" :span="8">
        <el-card shadow="hover" class="tpl-card">
          <template #header>
            <div class="tpl-header">
              <span>{{ t.name }}</span>
              <div>
                <el-button link size="small" @click="editTpl(t)">编辑</el-button>
                <el-button link size="small" type="danger" @click="delTpl(t.id)">删除</el-button>
              </div>
            </div>
          </template>
          <el-tag size="small" effect="plain">{{ t.category || '通用' }}</el-tag>
          <div class="tpl-items" v-if="t.itemsJson">
            <div v-for="(item, i) in parseItems(t.itemsJson)" :key="i" class="tpl-item">
              <span class="tpl-item-name">{{ item.name || item }}</span>
              <el-tag size="small" type="info" effect="plain" round>{{ item.maxScore || 0 }}分</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog v-model="showForm" :title="editing ? '编辑模板' : '添加模板'" width="520px">
      <el-form label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="form.name" placeholder="如：前端开发工程师" />
        </el-form-item>
        <el-form-item label="岗位分类">
          <el-select v-model="form.category" filterable allow-create clearable placeholder="选择或输入岗位分类" style="width:100%">
            <el-option v-for="cat in categoryOptions" :key="cat" :label="cat" :value="cat" />
          </el-select>
        </el-form-item>
        <el-form-item label="指标项">
          <div class="item-list">
            <div v-for="(item, i) in form.items" :key="i" class="item-row">
              <span class="item-num">{{ i + 1 }}</span>
              <el-input v-model="item.name" placeholder="指标名称" style="flex:1" />
              <span class="item-label">权重</span>
              <el-input-number v-model="item.maxScore" :min="1" :max="60" :step="5" style="width:100px" />
              <span class="item-label">分</span>
              <el-button @click="form.items.splice(i,1)" :icon="'Delete'" circle size="small" :disabled="form.items.length <= 1" />
            </div>
          </div>
          <el-button size="small" @click="form.items.push({ name: '', maxScore: 20 })" :disabled="form.items.length >= 10">+ 添加指标</el-button>
          <div class="item-hint">权重之和建议控制在100分以内，各项按重要性分配</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showForm = false">取消</el-button>
        <el-button type="primary" @click="saveTpl">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { kpiApi } from '../../api'
import { ElMessage, ElMessageBox } from 'element-plus'

const templates = ref([])
const showForm = ref(false)
const editing = ref(null)
const selectedCategory = ref('')
const form = reactive({ name: '', category: '', items: [{ name: '', maxScore: 20 }] })

// Broad job-family categories
const categoryOptions = [
  '技术开发', '产品设计', '人力资源', '财务管理', '运营市场', '高管'
]

// Extract unique non-empty categories from loaded templates, merge with defaults
const categories = computed(() => {
  const cats = new Set(categoryOptions.filter(c => templates.value.some(t => t.category === c)))
  // Also add any ad-hoc categories that exist in templates but not in defaults
  for (const t of templates.value) {
    if (t.category) cats.add(t.category)
  }
  return [...cats].sort()
})

const filteredTemplates = computed(() => {
  if (!selectedCategory.value) return templates.value
  return templates.value.filter(t => (t.category || '通用') === selectedCategory.value)
})

function countByCategory(cat) {
  return templates.value.filter(t => (t.category || '通用') === cat).length
}

function onFilterChange() {} // triggers computed re-eval

onMounted(() => load())
async function load() { templates.value = await kpiApi.listTemplates() }

function parseItems(json) {
  try { const arr = JSON.parse(json); return Array.isArray(arr) ? arr : [] } catch { return [] }
}

function openCreate() {
  editing.value = null
  form.name = ''
  form.category = ''
  form.items = [{ name: '', maxScore: 20 }]
  showForm.value = true
}

function editTpl(t) {
  editing.value = t
  form.name = t.name
  form.category = t.category || ''
  const items = parseItems(t.itemsJson)
  form.items = items.length ? items.map(it => ({
    name: it.name || '',
    maxScore: it.maxScore || 0
  })) : [{ name: '', maxScore: 20 }]
  showForm.value = true
}

async function saveTpl() {
  const validItems = form.items.filter(i => i.name.trim())
  if (!form.name.trim()) { ElMessage.warning('请填写模板名称'); return }
  if (validItems.length === 0) { ElMessage.warning('请至少添加一个指标项'); return }
  const data = {
    name: form.name.trim(),
    category: form.category || '通用',
    itemsJson: JSON.stringify(validItems.map(i => ({ name: i.name.trim(), maxScore: i.maxScore || 0 })))
  }
  if (editing.value) {
    await kpiApi.updateTemplate(editing.value.id, data)
  } else {
    await kpiApi.createTemplate(data)
  }
  ElMessage.success('保存成功')
  showForm.value = false
  load()
}

async function delTpl(id) {
  await ElMessageBox.confirm('确定删除吗？', '提示', { type: 'warning' })
  await kpiApi.deleteTemplate(id)
  ElMessage.success('已删除')
  load()
}
</script>

<style scoped>
.page { width: 100%; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.page-header h3 { font-size: 16px; color: var(--color-text); margin: 0; }

.filter-bar { display: flex; align-items: center; gap: 8px; margin-bottom: 16px; flex-wrap: wrap; }
.filter-label { font-size: 13px; color: var(--color-text-secondary); flex-shrink: 0; }

.empty { color: var(--color-text-muted); padding: 40px; text-align: center; background: var(--color-surface); border-radius: 8px; }

.tpl-card { margin-bottom: 16px; }
.tpl-header { display: flex; justify-content: space-between; align-items: center; }
.tpl-items { margin-top: 8px; display: flex; flex-direction: column; gap: 4px; }
.tpl-item { display: flex; align-items: center; justify-content: space-between; font-size: 13px; color: var(--color-text-secondary); }
.tpl-item-name { flex: 1; }

.item-list { display: flex; flex-direction: column; gap: 6px; width: 100%; }
.item-row { display: flex; align-items: center; gap: 6px; }
.item-num { width: 18px; font-size: 12px; color: var(--color-text-muted); text-align: center; flex-shrink: 0; }
.item-label { font-size: 12px; color: var(--color-text-muted); flex-shrink: 0; }
.item-hint { font-size: 11px; color: var(--color-text-muted); margin-top: 6px; }
</style>
