<template>
	<view class="container">
		<view class="main-content">
			<view class="input-group">
				<u-input :customStyle="customStyle" :placeholder-style="placeholderStyle" v-model="form.isbn"
					placeholder="扫描ISBN" border="surround" />
				<u-button :customStyle="customStyle" type="info" color="#a4adb3" 
					@click="handleSubmit" text="提交" />
			</view>
		</view>

		<view class="fixed-bottom">
			<u-button size="large" type="success" @click="scanCode" text="扫码" class="scan-button" />
		</view>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		onUnmounted
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'

	const placeholderStyle = "font-size:32rpx"
	const customStyle = reactive({
		height: '90rpx'
	})

	const form = ref({
		"isbn": "",
	})

	function scanCode() {
		uni.scanCode({
			success: (res) => {
				form.value.isbn = res.result;
				handleSubmit();
			},
			fail: (err) => {
				uni.$u.toast('扫码失败');
			}
		});
	}

	function handleSubmit() {
		if (!form.value.isbn) return uni.$u.toast('请输入ISBN');
		
		// Call your API endpoint for commodity scanning
		uni.$u.http.post('/app/book/bookPushErp', form.value).then(res => {
            console.log(res);
			if (res.code == 200) {
				let text = form.value.isbn + res.msg;
				uni.$u.ttsModule.speak(text);
				form.value.isbn = '';
			} else {
				uni.$u.ttsModule.speak(res.msg);
			}
		}).catch(err => {
			uni.$u.toast('提交失败，请重试');
		});
	}

	onLoad(() => {
		// #ifdef APP-PLUS
		uni.$u.useGlobalEvent((e) => {
			if (e.barcode) {
				form.value.isbn = e.barcode;
				handleSubmit();
			}
		})
		// #endif
	})
    
	// #ifdef APP-PLUS
	onShow(() => {
		uni.$u.updateActivePageOnShow();
	})
	onUnmounted(() => {
		uni.$u.cleanupOnPageUnload();
	});
	// #endif
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}
	
	.header {
		background-color: #27ae60;
		padding: 20rpx;
		color: white;
		text-align: center;
		font-size: 36rpx;
		position: relative;
		
		.title {
			font-weight: bold;
		}
	}
	
	.main-content {
		padding: 20px;
		gap: 20px;
	}

	.input-group {
		display: flex;
		gap: 10px;
		margin-bottom: 30rpx;

		:deep(.u-button) {
			width: 160rpx;
		}

		.u-input {
			background-color: #fff;
		}
	}
	
	.status-box {
		margin: 20rpx;
		background-color: #fff;
		border-radius: 10rpx;
		overflow: hidden;
		border: 1px solid #f0f0f0;
		
		.status-header {
			background-color: #f1c40f;
			padding: 10rpx 20rpx;
			color: #333;
			font-weight: bold;
		}
		
		.status-message {
			padding: 20rpx;
			border-bottom: 1px solid #eee;
			font-weight: bold;
		}
		
		.status-option {
			padding: 10rpx 20rpx;
			border-bottom: 1px solid #eee;
		}
		
		.footer {
			padding: 10rpx 20rpx;
			color: #999;
			font-size: 24rpx;
			text-align: right;
		}
	}
	
	.fixed-bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		
		.scan-button {
			background-color: #27ae60;
		}
	}
</style>
