<template>
	<view class="container">
		<view class="main-content">
			<view class="input-group">
				<u-input :customStyle="customStyle" :placeholder-style="placeholderStyle" v-model="selectedWarehouse"
					placeholder="请选择仓库" readonly border="surround" />
				<u-button :customStyle="customStyle" type="info" color="#a4adb3" @click="openWarehouseSelector"
					text="选择" />
			</view>
			<view class="input-group">
				<u-input :customStyle="customStyle" :placeholder-style="placeholderStyle" v-model="form.packageCode"
					placeholder="扫描/输入物流单号" border="surround" />
				<u-button :customStyle="customStyle" type="info" color="#a4adb3" v-permission="'app:express:transferSign:confirm'"
					@click="handleBarcode(form.packageCode)" text="确定" />
			</view>
		</view>

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

		<WarehouseSelector v-model:show="showSelector" @warehouse-selected="handleWarehouseSelected" />
	</view>
</template>

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

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

	const selectedWarehouse = ref('');
	const form = ref({
		"packageCode": "",
		"godownId": "",
	})
	const showSelector = ref(false);

	function openWarehouseSelector() {
		showSelector.value = true;
	}

	//选择仓库之后后处理
	function handleWarehouseSelected(item) {
		selectedWarehouse.value = item.godownName;
		form.value.godownId = item.id
	}

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

	function handleBarcode(code) {
		if (!code) return uni.$u.toast('请输入物流单号')
		uni.$u.http.post('/app/ordersign/transferSign', form.value).then(res => {
			if (res.code == 200) {
				let text = code + '签收成功'
				uni.$u.ttsModule.speak(text)
			} else {
				let text = code + '订单不存在'
				uni.$u.ttsModule.speak(text)
			}
		})
	}

	//获取用户绑定的仓库
	function getUserBindWarehouse() {
		uni.$u.http.get('/app/appUser/getUserBindGodown').then(res => {
			if (res.code == 200) {
				selectedWarehouse.value = res.data?.godownName
				form.value.godownId = res.data?.id
			}
		})
	}

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

<style lang="scss" scoped>
	.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;
		}
	}
</style>