<template>
	<view class="page">
		<view class="toolbar">
			<input v-model.trim="name" placeholder="新单位名称" />
			<button size="mini" @click="create">新增</button>
		</view>
		<scroll-view scroll-y class="list">
			<view class="item" v-for="u in list" :key="u.id">
				<input v-model.trim="u.name" />
				<view class="ops">
					<button size="mini" @click="update(u)">保存</button>
					<button size="mini" type="warn" @click="remove(u)">删除</button>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { get, post, put, del } from '../../common/http.js'

export default {
	data() {
		return { name: '', list: [] }
	},
	onLoad() { this.reload() },
	methods: {
		async reload() {
			try {
				const res = await get('/api/product-units')
				this.list = Array.isArray(res?.list) ? res.list : (Array.isArray(res) ? res : [])
			} catch (_) {}
		},
		async create() {
			if (!this.name) return
			await post('/api/product-units', { name: this.name })
			this.name = ''
			this.reload()
		},
		async update(u) {
			await put('/api/product-units/' + u.id, { name: u.name })
			uni.showToast({ title: '已保存', icon: 'success' })
		},
		async remove(u) {
			uni.showModal({ content: '确定删除该单位？', success: async (r) => {
				if (!r.confirm) return
				await del('/api/product-units/' + u.id)
				this.reload()
			}})
		}
	}
}
</script>

<style>
.page { display:flex; flex-direction: column; height: 100vh; }
.toolbar { display:flex; gap: 12rpx; padding: 16rpx; background:#fff; }
.toolbar input { flex:1; background:#f6f6f6; border-radius: 12rpx; padding: 12rpx; }
.list { flex:1; }
.item { display:flex; gap: 12rpx; align-items:center; padding: 16rpx; background:#fff; border-bottom: 1rpx solid #f1f1f1; }
.item input { flex:1; background:#f7f7f7; border-radius: 10rpx; padding: 12rpx; }
.ops { display:flex; gap: 10rpx; }
</style>







