<template>
	<view class="page">
		<view class="search">
			<input v-model="kw" placeholder="搜索商品名称/编码" @confirm="search" />
			<button size="mini" @click="search">搜索</button>
		</view>
		<scroll-view scroll-y class="list">
			<view class="item" v-for="p in products" :key="p.id" @click="select(p)">
				<view class="name">{{ p.name }}</view>
				<view class="meta">{{ (p.brand||'') + ' ' + (p.model||'') + ' ' + (p.spec||'') }} · 库存：{{ p.stock ?? 0 }}</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import { get } from '../../common/http.js'
	export default {
		data() { return { kw: '', products: [] } },
		onLoad() { this.search() },
		methods: {
			async search() {
				try {
					const res = await get('/api/products', { kw: this.kw, page: 1, size: 50 })
					this.products = Array.isArray(res?.list) ? res.list : (Array.isArray(res) ? res : [])
				} catch(e) { uni.showToast({ title: '加载失败', icon: 'none' }) }
			},
			select(p) {
				const opener = getCurrentPages()[getCurrentPages().length-2]
				if (opener && opener.$vm && opener.$vm.items) {
					const initPrice = Number((p.retailPrice != null ? p.retailPrice : (p.price || 0)))
					opener.$vm.items.push({ productId: p.id, productName: p.name, quantity: 1, unitPrice: initPrice, _autoPrice: true })
				}
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss">
	.page { display:flex; flex-direction: column; height: 100vh; }
	.search { display:flex; gap: 12rpx; padding: 16rpx; background:$uni-bg-color-grey; }
	.search input { flex:1; background:$uni-bg-color-hover; border-radius: 12rpx; padding: 12rpx; color:$uni-text-color; }
	.list { flex:1; }
	.item { padding: 20rpx 24rpx; background:$uni-bg-color-grey; border-bottom: 1rpx solid $uni-border-color; }
	.name { color:$uni-text-color; margin-bottom: 6rpx; }
	.meta { color:$uni-text-color-grey; font-size: 24rpx; }
</style>



