<template>
  <div class="app-page dimension-workbench">
    <div class="page-header">
      <h3>考核维度配置</h3>
      <el-button type="primary" @click="openCreate"><el-icon><Plus /></el-icon> 添加维度</el-button>
    </div>

    <div class="hint-bar">
      所有维度满分之和必须为 <strong>40</strong>，当前合计：<span :class="sumClass">{{ totalScore }}</span> / 40
    </div>

    <el-table :data="dimensions" style="width:100%" v-if="dimensions.length">
      <el-table-column label="排序" width="80">
        <template #default="{ row, $index }">
          <div class="sort-ctrl">
            <el-button link size="small" :disabled="$index === 0" @click="moveUp($index)"><el-icon><ArrowUp /></el-icon></el-button>
            <el-button link size="small" :disabled="$index === dimensions.length-1" @click="moveDown($index)"><el-icon><ArrowDown /></el-icon></el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="维度名称" />
      <el-table-column label="满分分值" width="120">
        <template #default="{ row }">
          <el-input-number v-model="row.maxScore" :min="1" :max="40" :step="1" size="small" @change="(v) => updateMaxScore(row, v)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row, $index }">
          <el-button link size="small" @click="editName(row)">改名</el-button>
          <el-button link size="small" type="danger" @click="delDim(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-else class="empty">暂无维度，请添加</div>

    <el-dialog v-model="showForm" :title="editing ? '编辑维度' : '添加维度'" width="400px">
      <el-form label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="form.name" placeholder="如：交付质量" />
        </el-form-item>
        <el-form-item label="满分分值">
          <el-input-number v-model="form.maxScore" :min="1" :max="40" :step="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showForm = false">取消</el-button>
        <el-button type="primary" @click="saveDim">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { dimensionApi } from '../../api'
import { ElMessage, ElMessageBox } from 'element-plus'

const dimensions = ref([])
const showForm = ref(false)
const editing = ref(null)
const form = ref({ name: '', maxScore: 10 })

const totalScore = computed(() => dimensions.value.reduce((s, d) => s + (d.maxScore || 0), 0))
const sumClass = computed(() => totalScore.value === 40 ? 'sum-ok' : 'sum-bad')

onMounted(() => load())
async function load() { dimensions.value = await dimensionApi.list() }

function openCreate() {
  editing.value = null
  form.value = { name: '', maxScore: 10 }
  showForm.value = true
}

function editName(row) {
  editing.value = row
  form.value = { name: row.name, maxScore: row.maxScore }
  showForm.value = true
}

async function saveDim() {
  if (!form.value.name.trim()) { ElMessage.warning('请填写维度名称'); return }
  try {
    if (editing.value) {
      await dimensionApi.update(editing.value.id, { name: form.value.name, maxScore: form.value.maxScore })
    } else {
      await dimensionApi.create({ name: form.value.name, maxScore: form.value.maxScore, sortOrder: dimensions.value.length + 1 })
    }
    ElMessage.success('保存成功')
    showForm.value = false
    await load()
  } catch (e) {
    ElMessage.error(e.message || '保存失败，请检查分值总和是否为40')
  }
}

async function updateMaxScore(row, val) {
  try {
    await dimensionApi.update(row.id, { name: row.name, maxScore: val, sortOrder: row.sortOrder })
  } catch (e) {
    ElMessage.error('分值总和必须为40')
    row.maxScore = row._oldScore || 10
  }
}

async function delDim(id) {
  await ElMessageBox.confirm('确定删除该维度？如果删除后分值总数不为40将无法保存。', '提示', { type: 'warning' })
  try {
    await dimensionApi.delete(id)
    await load()
    ElMessage.success('已删除')
  } catch (e) {
    ElMessage.error(e.message || '无法删除，分值总和必须保持40')
    await load()
  }
}

async function moveUp(idx) {
  if (idx === 0) return
  const a = dimensions.value[idx]; const b = dimensions.value[idx - 1]
  await dimensionApi.update(a.id, { ...a, sortOrder: b.sortOrder })
  await dimensionApi.update(b.id, { ...b, sortOrder: a.sortOrder })
  load()
}
async function moveDown(idx) {
  if (idx === dimensions.value.length - 1) return
  const a = dimensions.value[idx]; const b = dimensions.value[idx + 1]
  await dimensionApi.update(a.id, { ...a, sortOrder: b.sortOrder })
  await dimensionApi.update(b.id, { ...b, sortOrder: a.sortOrder })
  load()
}
</script>

<style scoped>
.page { width: 100%; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.page-header h3 { font-size: 16px; color: var(--color-text); margin: 0; }
.hint-bar { font-size: 13px; color: var(--color-text-secondary); margin-bottom: 16px; padding: 10px 16px; background: var(--color-surface-tint-brand); border-radius: 8px; }
.hint-bar strong { color: var(--color-brand); }
.sum-ok { color: var(--color-success); font-weight: 700; }
.sum-bad { color: var(--color-danger); font-weight: 700; }
.sort-ctrl { display: flex; gap: 2px; }
.empty { color: var(--color-text-muted); padding: 40px; text-align: center; background: var(--color-surface); border-radius: 8px; }
</style>
