<template>
	<view class="container">
		<uni-forms ref="valiForm" label-align="right" :label-width="80" :rules="rules" :modelValue="valiFormData">
			<uni-forms-item label="单据编号" required name="order_code">
				<uni-easyinput v-model="valiFormData.order_code" placeholder="请输入单据编号" suffixIcon="scan"
					:focus="focusType" @iconClick="scanInput" @blur="setfocus" @confirm="onsubmit" />
			</uni-forms-item>
		</uni-forms>
		<view class="button-group">
			<button type="info" @click="reset">重置</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="warehouseLogHistory.length > 0" class="history">
			<text class="title">记录(最近5条)</text>
		</view>
		<view class="history">
			<view class="item" v-for="(item, i) in warehouseLogHistory.slice(0, 5)" :key="i">
				<text class="code" :style="{ color: item.status ? 'green' : '#666' }">{{ item.order_code }}</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, nextTick } from 'vue';
	import permision from '@/common/permission.js';
	import {
		onShow,
		onLoad,
		onUnload,
		onHide,
		onBackPress,
		onNavigationBarButtonTap

	} from '@dcloudio/uni-app';
	import { warehouseScanURL } from '@/utils/api.js';
	const token = ref();
	const loading = ref(false);
	const hidePage = ref(false);
	const focusType = ref(true);
	const warehouseLogHistory = ref([]);
	const messageRef = ref();
	const messageType = ref();
	const messageText = ref();
	let st : NodeJS.Timeout;

	const valiFormData = ref({
		order_code: ''
	});
	const rules = reactive({
		order_code: {
			rules: [
				{
					required: true,
					errorMessage: '单据编号不能为空'
				}
			]
		}
	});

	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.order_code = res.result;
				onsubmit();
			},
			fail: (err) => {
				// 需要注意的是小程序扫码不需要申请相机权限
			}
		});

	};
	const reset = () => {
		loading.value = false;
		valiFormData.value.order_code = '';
	};

	const setfocus = () => {
		if (hidePage.value) {
			return;
		}
		focusType.value = false;
		nextTick(() => {
			focusType.value = true;
		});
	}

	const onsubmit = () => {
		st && clearTimeout(st);
		loading.value = true;
		uni.request({
			url: warehouseScanURL,
			method: 'POST',
			header: {
				batoken: token.value
			},
			data: {
				order_code: valiFormData.value.order_code
			},
			success: (res : any) => {
				loading.value = false;
				if (res.data.code == 1) {
					messageType.value = 'success';
					messageText.value = res.data.msg;
					messageRef.value.open();

					const historyItem = {
						order_code: valiFormData.value.order_code,
						createTime: new Date(),
						type: '单据扫描',
						status: true
					};
					warehouseLogHistory.value.unshift(historyItem);
					uni.setStorageSync('warehouseLogHistory', warehouseLogHistory.value);
					getHistory();
				} else {
					messageType.value = 'error';
					messageText.value = res.data.msg;
					messageRef.value.open();
					const historyItem = {
						order_code: valiFormData.value.order_code,
						createTime: new Date(),
						type: '单据扫描',
						status: false
					};
					warehouseLogHistory.value.unshift(historyItem);
					uni.setStorageSync('warehouseLogHistory', warehouseLogHistory.value);
					getHistory();
				}
				st = setTimeout(() => {
					reset();
					st && clearTimeout(st);
				}, 1000);
			}
		});
	};

	const getHistory = () => {
		warehouseLogHistory.value = uni.getStorageSync('warehouseLogHistory') || [];
	};
	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');
		hidePage.value = false;
		getHistory();
	});

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

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

	.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>