<template>
  <div class="panel">
    <div class="toolbar">
      <el-input v-model="state.newName" placeholder="输入新单位名称" clearable style="max-width:280px" />
      <el-button type="primary" @click="create" :loading="state.loading">新增</el-button>
      <el-button @click="reload" :loading="state.loading">刷新</el-button>
    </div>
    <el-table :data="state.list" size="small" style="width:100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="名称">
        <template #default="{ row }">
          <el-input v-model="row.name" @change="update(row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="{ row }">
          <el-popconfirm title="确认删除该单位？若被引用将失败" @confirm="remove(row)">
            <template #reference>
              <el-button link type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
  </template>

<script setup lang="ts">
import { reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { get, post, put, del } from '../../api/http'

type Unit = { id: number; name: string }

const state = reactive({ list: [] as Unit[], newName: '', loading: false })

async function reload() {
  state.loading = true
  try {
    const res = await get<any>('/api/product-units')
    state.list = Array.isArray(res?.list) ? res.list : (Array.isArray(res) ? res : [])
  } catch (e: any) {
    ElMessage.error(e?.message || '加载失败')
  } finally { state.loading = false }
}

async function create() {
  if (!state.newName || !state.newName.trim()) { ElMessage.warning('请输入名称'); return }
  state.loading = true
  try {
    await post('/api/admin/dicts/units', { name: state.newName.trim() })
    state.newName = ''
    await reload()
    ElMessage.success('已新增')
  } catch (e: any) {
    ElMessage.error(e?.message || '新增失败')
  } finally { state.loading = false }
}

async function update(row: Unit) {
  if (!row?.id || !row.name?.trim()) return
  try {
    await put(`/api/admin/dicts/units/${row.id}`, { name: row.name.trim() })
    ElMessage.success('已保存')
  } catch (e: any) {
    ElMessage.error(e?.message || '保存失败')
  }
}

async function remove(row: Unit) {
  if (!row?.id) return
  try {
    await del(`/api/admin/dicts/units/${row.id}`)
    await reload()
    ElMessage.success('已删除')
  } catch (e: any) {
    ElMessage.error(e?.message || '删除失败')
  }
}

onMounted(reload)
</script>

<style scoped>
.toolbar { display:flex; gap:8px; margin-bottom:12px; }
</style>


