<template>
	<view class="container">
		<view class="checkbox">
			<uni-data-checkbox v-model="selectType" :localdata="printType"></uni-data-checkbox>
		</view>

		<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="printLogHistory.length > 0" class="history">
			<text class="title">记录(最近5条)</text>
		</view>
		<view class="history">
			<view class="item" v-for="(item, i) in printLogHistory.slice(0, 5)" :key="i">
				<text class="code" :style="{ color: item.status ? 'green' : '#666' }">{{item.type}} {{ 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>
		<uni-popup ref="printerDialog" type="dialog" :is-mask-click="false">
			<view style="width: 90%; margin: 0 auto; min-height: 250px; background-color: #fff; border-radius: 5px">
				<view class="" style="font-size: 20px; border-bottom: 1px solid #e1e1e1; padding: 15px 10px">
					<view>
						<view style="margin-bottom: 20px">
							<text>打印尾程面单</text>
						</view>
						<view>
							<view v-if="printerList">
								<view>
									<uni-data-checkbox
										multiple
										v-model="sendToPeinter"
										:localdata="[
											{
												text: '发送到标签打印机打印',
												value: 1
											}
										]"
										@change="sendToPeinterFun"
									>
										>
									</uni-data-checkbox>
									<uni-data-checkbox :disabled="sendToPeinter.length === 0" v-model="selectPrinter" :localdata="printers"></uni-data-checkbox>
								</view>
							</view>
						</view>
					</view>
					<view style="text-align: center; position: absolute; bottom: 10px; width: 90%; display: flex; margin: 0 auto; left: 0; right: 0">
						<button @click="close" style="width: 35%">关闭</button>
						<button
							@click="printConfirm"
							:hover-stay-time="500"
							:loading="subLoading"
							:disabled="sendToPeinter.length === 0 || subLoading"
							class="my-bt-bg"
							style="width: 35%"
						>
							打印
						</button>
					</view>
				</view>
			</view>
		</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 { printCustomerLabelURL, getPrinterListURL, printWaybillLabelURL } from '@/utils/api.js';
const token = ref();
const loading = ref(false);
const hidePage = ref(false);
const focusType = ref(true);
const selectType = ref(1);
const printType = ref([
	{
		text: '打印尾程面单',
		value: 1
	},
	{
		text: '打印客户联(详细)',
		value: 2
	},
	{
		text: '打印客户联(简单)',
		value: 3
	}
]);
const printerDialog = ref();
const subLoading = ref(false);
const printerList = ref([]);
const printers = ref([]);
const downloadFile = ref([]);
const sendToPeinter = ref([1]);
const selectPrinter = ref(0);
const printLogHistory = 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 close = () => {
	printerDialog.value.close();
	st = setTimeout(() => {
		reset();
		st && clearTimeout(st);
	}, 700);
};

const sendToPeinterFun = (res: any) => {
	if (res.detail.value.length === 0) {
		selectPrinter.value = 0;
	} else {
		selectPrinter.value = printers.value[0].value;
	}
};
const printConfirm = () => {
	subLoading.value = true;
	const url = selectType.value === 1 ? printWaybillLabelURL : printCustomerLabelURL;
	let data = {
		order_no: valiFormData.value.order_code,
		printer_code: selectPrinter.value
	} as any;
	let type = '尾程面单打印';
	if (selectType.value === 2) {
		data.style = 'detail';
		type = '打印客户联(详细)';
	}
	if (selectType.value === 3) {
		data.style = 'simple';
		type = '打印客户联(简单)';
	}
	uni.request({
		url: url,
		method: 'POST',
		header: {
			batoken: token.value
		},
		data: data,
		success: (res: any) => {
			subLoading.value = false;
			console.log('打印成功', res);
			messageType.value = res.data.code ? 'success' : 'error';
			messageText.value = res.data.msg;
			messageRef.value.open();

			const historyItem = {
				order_code: valiFormData.value.order_code,
				createTime: new Date(),
				type: type,
				status: res.data.code
			};
			printLogHistory.value.unshift(historyItem);
			uni.setStorageSync('printLogHistory', printLogHistory.value);
			getHistory();
			close();
		},
		fail: (err: any) => {
			subLoading.value = false;
			console.log('打印失败', err);
			messageType.value = 'error';
			messageText.value = '打印失败';
			messageRef.value.open();
			const historyItem = {
				order_code: valiFormData.value.order_code,
				createTime: new Date(),
				type: type,
				status: false
			};
			printLogHistory.value.unshift(historyItem);
			uni.setStorageSync('printLogHistory', printLogHistory.value);
			getHistory();
			close();
		}
	});
};

const getPrinterList = () => {
	uni.request({
		url: getPrinterListURL,
		method: 'GET',
		header: {
			batoken: token.value
		},
		success: (res: any) => {
			if (res.data.code === 1) {
				printerList.value = res.data.data.printers;
				printers.value = Object.values(printerList.value).map((item) => {
					return {
						text: item.name,
						value: item.value
					};
				});
			}
		},
		fail(e) {
			console.log('fail--', e);
		}
	});
};

const onsubmit = () => {
	if (valiFormData.value.order_code) {
		loading.value = true;
		st && clearTimeout(st);
		selectPrinter.value = sendToPeinter.value.length > 0 ? printers.value[0].value : 0;
		printerDialog.value.open();
		loading.value = false;
	} else {
		messageType.value = 'error';
		messageText.value = '请填写运单号';
		messageRef.value.open();
	}
};

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

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

<style lang="scss" scoped>
.container {
	padding: 15px;
	background-color: #fff;
}
.checkbox {
	margin-bottom: 10px;
	.uni-data-checklist .checklist-group {
		flex-direction: column;
	}
}

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