<template>
  <div>
    <div class="page-header">
      <h1>项目类型标签</h1>
      <p>管理研发填报工时时可选用的项目类型标签</p>
    </div>

    <div class="content-card">
      <div class="card-title">
        <span>当前标签 ({{ tags.length }} 个)</span>
      </div>

      <div class="tags-area" v-loading="loading">
        <el-tag
          v-for="tag in tags"
          :key="tag.id"
          closable
          effect="dark"
          size="large"
          class="tag-item"
          @close="handleDelete(tag)"
        >
          {{ tag.name }}
        </el-tag>

        <template v-if="!addingNew">
          <el-button class="add-tag-btn" size="small" @click="startAdd">+ 添加标签</el-button>
        </template>
        <template v-else>
          <el-input
            ref="inputRef"
            v-model="newTagName"
            class="new-tag-input"
            size="small"
            placeholder="输入标签名，回车确认"
            @keyup.enter="confirmAdd"
            @blur="confirmAdd"
            maxlength="20"
            show-word-limit
          />
        </template>
      </div>

      <div style="margin-top: 16px; color: var(--text-muted); font-size: 13px;">
        💡 点击标签右侧 × 可删除该标签。删除后，已填报的历史工时中标签名称不受影响。
      </div>
    </div>
  </div>
</template>

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

const tags = ref([])
const loading = ref(false)
const addingNew = ref(false)
const newTagName = ref('')
const inputRef = ref(null)

async function loadTags() {
  loading.value = true
  try {
    const res = await adminApi.getProjectTypes()
    tags.value = res.data
  } finally { loading.value = false }
}

async function startAdd() {
  addingNew.value = true
  newTagName.value = ''
  await nextTick()
  inputRef.value?.focus()
}

async function confirmAdd() {
  const name = newTagName.value.trim()
  if (!name) {
    addingNew.value = false
    return
  }
  try {
    const res = await adminApi.createProjectType({ name })
    tags.value.push(res.data)
    ElMessage.success(`标签「${name}」添加成功`)
  } catch (e) {
    // error already shown by api interceptor
  } finally {
    addingNew.value = false
    newTagName.value = ''
  }
}

async function handleDelete(tag) {
  await ElMessageBox.confirm(`确定删除标签「${tag.name}」吗？`, '确认删除', { type: 'warning' })
  await adminApi.deleteProjectType(tag.id)
  tags.value = tags.value.filter(t => t.id !== tag.id)
  ElMessage.success('已删除')
}

onMounted(loadTags)
</script>

<style scoped>
.tags-area {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  padding: 16px 0 8px;
  min-height: 60px;
}
.tag-item {
  font-size: 14px;
  border-radius: 20px;
  padding: 6px 14px;
}
.add-tag-btn {
  border-radius: 20px;
  border-style: dashed;
}
.new-tag-input {
  width: 160px;
}
</style>
