<template>
	<view class="container">
		<uni-forms ref="valiForm" label-align="right" :label-width="80" :rules="rules" :modelValue="valiFormData">
			<uni-forms-item label="运单号码" required name="orderNum">
				<uni-easyinput v-model="valiFormData.orderNum" placeholder="请输入单号" suffixIcon="scan" :focus="focusType" @iconClick="scanInput" />
			</uni-forms-item>
			<uni-forms-item label="复称重量" name="weight">
				<uni-easyinput
					v-model="valiFormData.weight"
					placeholder="请输入复称重量"
					oninput="value=value.replace(/[^\d.]/g,'').replace(/^\./g, '').replace(/\.{2,}/g, '').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').match(/^\d*(\.?\d{0,2})/g)[0] || null"
				>
					<template #right>
						<view class="weight-right">KG</view>
					</template>
				</uni-easyinput>
			</uni-forms-item>
			<!-- <text class='weight-tip'>复称重量作用是确保句惠完整，防止工作人员计费称車后进行的其他操作引起的物品丢失问题</text> -->
			<!-- <uni-section title="绑定批托盘号" type="line" padding style="height: calc(100vh - 100px)"> -->
			<uni-forms-item label="绑定批次号" name="batchNum">
				<uni-data-select v-model="valiFormData.batchNum" placeholder="请选择批次号" :localdata="options.batch" :clear="false"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="绑定托盘号" name="palletNum">
				<uni-data-picker
					placeholder="请选择托盘号"
					popup-title="绑定托盘号"
					:localdata="options.pallet"
					v-model="valiFormData.palletNum"
					@change="onchange"
					@nodeclick="onnodeclick"
					@popupopened="onpopupopened"
					@popupclosed="onpopupclosed"
				></uni-data-picker>
			</uni-forms-item>
			<!-- </uni-section> -->
		</uni-forms>
		<view class="button-group">
			<button type="info" @click="reset">重置</button>
			<button type="default" @click="checkOrder" :loading="loading">
				<uni-icons v-if="!loading" type="search" size="18"></uni-icons>
				查看运单
			</button>
			<button type="primary" @click="onsubmit" :loading="loading">
				<uni-icons v-if="!loading" type="checkmarkempty" size="18" color="white"></uni-icons>
				提交
			</button>
		</view>
		<view v-if="lotnoLogHistory.length > 0" class="history">
			<text class="title">记录(最近5条)</text>
		</view>
		<view class="history">
			<view class="item" v-for="(item, i) in lotnoLogHistory.slice(0, 5)" :key="i">
				<text class="type">{{ item.type }}</text>
				<text class="code" :style="{ color: item.status ? 'green' : '#666' }">{{ item.orderNum }}</text>
				<uni-icons v-if="item.status" type="checkmarkempty" class="status" size="16" color="green"></uni-icons>
				<text class="status fail" v-else>F</text>
				<text style="margin-left: 10rpx; font-weight: 300">
					{{ '\r\n' + item.createTime }}
				</text>
			</view>
		</view>

		<uni-popup ref="messageRef" type="message">
			<uni-popup-message :type="messageType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import permision from '@/common/permission.js';
import { onShow, onLoad, onUnload, onHide, onBackPress, onNavigationBarButtonTap } from '@dcloudio/uni-app';
import { getBindParamsURL, bindShippingURL, getWaybillsURL } from '@/utils/api.js';
const token = ref();
const loading = ref(false);
const hidePage = ref(false);
const focusType = ref(true);
const lotnoLogHistory = ref([]);
const messageRef = ref();
const messageType = ref();
const messageText = ref();
let st: NodeJS.Timeout;

const valiFormData = ref({
	orderNum: '',
	weight: '',
	batchNum: '',
	palletNum: ''
});

const rules = reactive({
	orderNum: {
		rules: [
			{
				required: true,
				errorMessage: '单号不能为空'
			}
		]
	}
});

const options = reactive({
	batch: [] as any,
	pallet: [] as any
});

const onnodeclick = () => {};
const onpopupopened = () => {};
const onpopupclosed = () => {};
const onchange = () => {};
const checkPermission = async () => {
	let status = permision.isIOS ? await permision.requestIOS('camera') : await permision.requestAndroid('android.permission.CAMERA');

	if (status === null || status === 1) {
		status = 1;
	} else {
		uni.showModal({
			content: 'Camera permission required',
			confirmText: 'Setting',
			success: function (res) {
				if (res.confirm) {
					permision.gotoAppSetting();
				}
			}
		});
	}
	return status;
};
const scanInput = async () => {
	// #ifdef APP-PLUS
	let status = await checkPermission();
	if (status !== 1) {
		return;
	}
	// #endif
	uni.scanCode({
		success: (res: any) => {
			valiFormData.value.orderNum = res.result;
			// onsubmit();
		},
		fail: (err) => {
			// 需要注意的是小程序扫码不需要申请相机权限
		}
	});
};
const reset = () => {
	loading.value = false;
	valiFormData.value.orderNum = '';
	valiFormData.value.weight = '';
	valiFormData.value.batchNum = '';
	valiFormData.value.palletNum = '';
};

const checkOrder = () => {
	loading.value = true;
	uni.setStorageSync('waybills', []);
	uni.request({
		url: getWaybillsURL,
		method: 'POST',
		header: {
			batoken: token.value
		},
		data: {
			order_no: valiFormData.value.orderNum,
			batch_number: valiFormData.value.batchNum,
			pallet_number: valiFormData.value.palletNum ? findPalletNumIdByValue(options.pallet, valiFormData.value.palletNum) : ''
		},
		success: (res: any) => {
			loading.value = false;
			if (res.data.code == 1) {
				messageType.value = 'success';
				messageText.value = res.data.msg;
				messageRef.value.open();
				uni.setStorageSync('waybills', res.data.data.waybills);
				uni.navigateTo({
					url: '/pages/scanLotno/waybillsList'
				});
			} else {
				messageType.value = 'error';
				messageText.value = res.data.msg;
				messageRef.value.open();
			}
		}
	});
};

const findPalletNumIdByValue = (data: any, targetValue: any) => {
	for (let i = 0; i < data.length; i++) {
		const item = data[i];
		// 检查当前项的 label
		if (item.id === targetValue || item.value === targetValue) {
			return [item.id];
		} else if (item.children && item.children.length > 0) {
			const childId = findPalletNumIdByValue(item.children, targetValue) as any;
			if (childId !== null) {
				return childId;
			}
		}
	}
	return null;
};

const onsubmit = () => {
	st && clearTimeout(st);
	loading.value = true;
	uni.request({
		url: bindShippingURL,
		method: 'POST',
		header: {
			batoken: token.value
		},
		data: {
			order_no: valiFormData.value.orderNum,
			reweighting: valiFormData.value.weight,
			batch_number: valiFormData.value.batchNum,
			pallet_number: valiFormData.value.palletNum ? findPalletNumIdByValue(options.pallet, valiFormData.value.palletNum) : ''
		},
		success: (res: any) => {
			loading.value = false;
			if (res.data.code == 1) {
				messageType.value = 'success';
				messageText.value = res.data.msg;
				messageRef.value.open();

				if (res.data.data.labels && res.data.data.labels.length > 0) {
					console.log('有打印面单');
					// res.data.data.labels.map((url: string) => {
					// 	let path = fullUrl(url);
					// 	window.open(path, '_blank');
					// });
				}
				const historyItem = {
					orderNum: valiFormData.value.orderNum,
					createTime: new Date(),
					type: valiFormData.value.batchNum ? '绑定批次' : '绑定托盘',
					status: true
				};
				console.log('lotnoLogHistory--', lotnoLogHistory);
				lotnoLogHistory.value.unshift(historyItem);
				uni.setStorageSync('lotnoLogHistory', lotnoLogHistory.value);
				getHistory();
			} else {
				messageType.value = 'error';
				messageText.value = res.data.msg;
				messageRef.value.open();
				const historyItem = {
					orderNum: valiFormData.value.orderNum,
					createTime: new Date(),
					type: valiFormData.value.batchNum ? '绑定批次' : '绑定托盘',
					status: false
				};
				lotnoLogHistory.value.unshift(historyItem);
				uni.setStorageSync('lotnoLogHistory', lotnoLogHistory.value);
				getHistory();
			}
			st = setTimeout(() => {
				reset();
				st && clearTimeout(st);
			}, 1000);
		}
	});
};

const getHistory = () => {
	lotnoLogHistory.value = uni.getStorageSync('lotnoLogHistory') || [];
};
const keypress = (e: any) => {
	console.log(e, '按键码');
	// 102  左侧    103  右侧   104  中间按键
	if (e.keyCode === 102 || e.keyCode === 103 || e.keyCode === 104) {
		//这里按键成功
	}

	if (e.keyCode == 66) {
		//enter按键
		//这里input已经拿到数据了，在这里把拿到的数据，通过接口数据联调起来
		onsubmit();
	}
};
onLoad(() => {
	// #ifdef APP-PLUS
	plus.key.addEventListener('keyup', keypress);
	// #endif
	// #ifdef H5
	document.addEventListener('keyup', keypress);
	// #endif
});
onUnload(() => {
	// #ifdef APP-PLUS
	plus.key.removeEventListener('keyup', keypress);
	// #endif
	// #ifdef H5
	document.removeEventListener('keyup', keypress);
	// #endif
});
onHide(() => {
	hidePage.value = true;
	// #ifdef APP-PLUS
	plus.key.removeEventListener('keyup', keypress);
	// #endif
	// #ifdef H5
	document.removeEventListener('keyup', keypress);
	// #endif
});
onBackPress(() => {
	// #ifdef APP-PLUS
	plus.key.removeEventListener('keyup', keypress);
	// #endif
	// #ifdef H5
	document.removeEventListener('keyup', keypress);
	// #endif
});
onShow(() => {
	token.value = uni.getStorageSync('token');
	getBindParams();
	getHistory();
});

const getBindParams = () => {
	uni.request({
		url: getBindParamsURL,
		method: 'GET',
		header: {
			batoken: token.value
		},
		success: (res: any) => {
			if (res.data.code === 1) {
				options.batch = res.data.data.batch_number.map((item: any) => {
					return { text: item.name, value: item.id };
				});
				function transformData(data: any[]) {
					return data.map((item) => {
						const { id, value, label, ...rest } = item;

						return {
							id: id || value,
							value: value,
							text: label,
							...rest,
							children: item.children ? transformData(item.children) : []
						};
					});
				}
				const shipping = transformData(res.data.data.shipping);
				options.pallet = shipping;
			}
		},
		fail(e) {
			console.log('fail--', e);
		}
	});
};

onNavigationBarButtonTap((event) => {
	if (event.index === 0) {
		uni.navigateTo({
			url: '/pages/scanLotno/lotnoLog'
		});
	}
});
</script>

<style lang="scss">
.container {
	padding: 15px;
	background-color: #fff;
}

.weight-right {
	padding-right: 10rpx;
	font-size: 14rpx;
}

.weight-tip {
	color: gray;
	font-size: 12rpx;
}

.button-group {
	margin-top: 15px;
	display: flex;
	flex-direction: row;
	justify-content: space-around;

	button {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 35px;
		width: 50%;
		margin-left: 10px;
		font-size: 16rpx;
	}

	.uni-icons {
		margin-right: 10px;
	}
}

.history {
	display: flex;
	width: 100%;
	flex-direction: column;
	justify-items: start;

	.title {
		padding: 20rpx;
		font-size: 24rpx;
		font-weight: 600;
	}

	.type {
		padding-right: 20rpx;
		font-size: 24rpx;
	}

	.code {
		font-weight: 600;
	}

	.item {
		padding: 20rpx;
		font-size: 20rpx;
		color: #666;

		.status {
			padding-left: 20rpx;
		}

		.fail {
			font-weight: 600;
			color: #f00;
		}
	}

	.is-empty {
		text-align: center;
		margin: 40px 0;
		color: #999;
	}
}
</style>
