<template>
	<view class="page">
		<view class="search">
			<input v-model="kw" placeholder="搜索客户名称/电话" @confirm="search" />
			<button size="mini" @click="search">搜索</button>
			<button size="mini" :type="debtOnly ? 'primary' : 'default'" @click="toggleDebtOnly">只看欠款</button>
		</view>
		<scroll-view scroll-y class="list">
			<view class="item" v-for="c in customers" :key="c.id" @click="openDetail(c)">
				<view class="name">{{ c.name }}</view>
				<view class="meta">
					{{ c.mobile || '—' }}
					<text v-if="typeof c.receivable === 'number'">｜应收：¥ {{ Number(c.receivable).toFixed(2) }}</text>
				</view>
			</view>
		</scroll-view>
		<view class="bottom">
			<button class="primary" @click="createCustomer">新增客户</button>
		</view>
	</view>
</template>

<script>
	import { get } from '../../common/http.js'
	export default {
		data() { return { kw: '', debtOnly: false, customers: [] } },
		onLoad() { this.search() },
		onShow() { this.search() },
		methods: {
			toggleDebtOnly() { this.debtOnly = !this.debtOnly; this.search() },
			async search() {
				try {
					const res = await get('/api/customers', { kw: this.kw, debtOnly: this.debtOnly, page: 1, size: 50 })
					this.customers = Array.isArray(res?.list) ? res.list : (Array.isArray(res) ? res : [])
				} catch(e) { uni.showToast({ title: '加载失败', icon: 'none' }) }
			},
			createCustomer() { uni.navigateTo({ url: '/pages/customer/form' }) },
			select(c) {
				const pages = getCurrentPages()
				const prev = pages.length >= 2 ? pages[pages.length - 2] : null
				const vm = prev && prev.$vm ? prev.$vm : null
				if (vm && vm.order) {
					vm.order.customerId = c.id
					vm.customerName = c.name
				}
				uni.navigateBack()
			}
			,
			openDetail(c) { uni.navigateTo({ url: '/pages/customer/detail?id=' + c.id }) }
		}
	}
</script>

<style lang="scss">
	.page { display:flex; flex-direction: column; height: 100vh; }
	.search { display:flex; gap: 12rpx; padding: 16rpx; background:$uni-bg-color-grey; align-items:center; }
	.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; }
	.bottom { position: fixed; left:0; right:0; bottom:0; background:$uni-bg-color-grey; padding: 16rpx 24rpx calc(env(safe-area-inset-bottom) + 16rpx); box-shadow: 0 -4rpx 12rpx rgba(0,0,0,0.10); }
	.primary { width: 100%; background: $uni-color-primary; color:#fff; border-radius: 999rpx; padding: 20rpx 0; }
</style>



