<template>
	<view class="container">
		<view class="example">
			<!-- 基础表单校验 -->
			<uni-forms ref="valiForm" label-align="right" :rules="rules" :modelValue="valiFormData">
				<uni-forms-item label="单号" :required="valiFormData.search_order_choice !== 2" name="orderNum">
					<uni-easyinput v-model="valiFormData.orderNum" placeholder="请输入单号" suffixIcon="scan" :focus="focusType" @iconClick="scan" />
				</uni-forms-item>
				<uni-forms-item v-if="valiFormData.search_order_choice === 2" label="批次号" name="batch_number">
					<uni-data-select v-model="valiFormData.batch_number" :localdata="batchOptions" placeholder="请选择批次号"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="仓位编码" name="space_code">
					<uni-data-select v-model="valiFormData.space_code" :localdata="spaces" placeholder="请选择仓位编码"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item v-if="valiFormData.search_order_choice !== 2" label="重量" required 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>
				<uni-forms-item>
					<view @click="searchPkgChange" class="checkbox-cum" :style="{ color: valiFormData.search_pkg ? '#007AFF' : 'gray' }">
						<checkbox :checked="valiFormData.search_pkg" @click="searchPkgChange" />
						搜索寄存包裹
					</view>

					<view class="sub-choice">
						<checkbox :disabled="!valiFormData.search_pkg" :checked="valiFormData.typing" />
						<text
							@click="
								() => {
									if (valiFormData.search_pkg) {
										valiFormData.typing = !valiFormData.typing;
									}
								}
							"
							:style="{ color: valiFormData.search_pkg && valiFormData.typing ? '#007AFF' : 'gray' }"
						>
							包裹寄存、代购、运单都找不到时手工添加包裹
						</text>
					</view>

					<view @click="searchOrderChoiceChange" class="checkbox-cum" :style="{ color: valiFormData.search_order ? '#007AFF' : 'gray' }">
						<checkbox :checked="valiFormData.search_order" @click="searchOrderChoiceChange" />
						搜索运单
					</view>

					<view>
						<uni-data-checkbox :disabled="!valiFormData.search_order" v-model="valiFormData.search_order_choice" :localdata="searchOrderChoice" />
					</view>
				</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>

		<view class="history">
			<view class="item" v-for="(item, i) in instockHistory.slice(0, 5)" :key="i">
				<text class="code" :style="{ color: item.status ? 'green' : '#666' }">
					{{ item.orderNum }}
					<text v-if="item.batch_text">批次号: {{ item.batch_text }}</text>
					{{ item.type }}
				</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="message" type="message">
			<uni-popup-message :type="messageType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>

		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog
				type="info"
				cancelText="否"
				confirmText="是"
				title="提示"
				content="是否按默认申报（默认申报为：衣服，10件，单价1）"
				@confirm="dialogConfirm"
				@close="dialogClose"
			></uni-popup-dialog>
		</uni-popup>
	</view>
</template>
<script>
import permision from '@/common/permission.js';
import { ref, reactive, nextTick } from 'vue';
import { instockScanURL, outStockScanURL, weighScanURL, checkWaybillGoodsURL, getWarehouseSpaceURL, getBindParamsURL } from '@/utils/api.js';
export default {
	data() {
		const token = ref(null);
		const user = ref(null);
		const loading = ref(false);
		return {
			token,
			user,
			messageType: '',
			messageText: '',
			batchOptions: [],
			spaces: [],
			instockHistory: [],
			focusType: true,
			loading,
			// 校验表单数据
			valiFormData: {
				orderNum: '',
				batch_number: '',
				space_code: '',
				weight: '',
				search_pkg: true,
				typing: true,
				search_order: true,
				search_order_choice: 1
			},

			searchOrderChoice: [
				{
					text: '更新为已入库,状态为【已入库】',
					value: 1
				},
				{
					text: '更新为已出库,状态为【已出库】',
					value: 2
				},
				{
					text: '称重计费',
					value: 3
				}
			]
		};
	},
	computed: {
		rules: function () {
			return {
				orderNum: {
					rules: [
						{
							required: this.valiFormData.search_order_choice !== 2,
							errorMessage: '单号不能为空'
						}
					]
				},
				weight: {
					rules: [
						{
							required: true,
							errorMessage: '重量不能为空'
						},
						{
							format: 'number',
							errorMessage: '重量只能输入数字'
						}
					]
				}
			};
		}
	},
	onShow() {
		this.focusType = true;
		this.loading = false;
		this.token = uni.getStorageSync('token');
		this.user = uni.getStorageSync('user');
		this.getWarehouseSpace();
		this.getBindParams();
	},
	onHide() {
		this.focusType = false;
		this.loading = false;
	},
	onReady() {},
	onNavigationBarButtonTap(event) {
		if (event.index === 0) {
			uni.navigateTo({
				url: '/pages/instock/instockLog'
			});
		}
	},
	methods: {
		getWarehouseSpace() {
			uni.request({
				url: getWarehouseSpaceURL,
				method: 'POST',
				header: {
					batoken: this.token
				},
				data: {
					code: ''
				},
				success: (res) => {
					if (res.data.code === 1) {
						this.spaces = res.data.data.spaces.map((item) => {
							return {
								text: item.name,
								value: item.code
							};
						});
					}
				}
			});
		},
		getBindParams() {
			uni.request({
				url: getBindParamsURL,
				method: 'GET',
				header: {
					batoken: this.token
				},
				success: (res) => {
					if (res.data.code === 1) {
						this.batchOptions = res.data.data.batch_number.map((item) => {
							return { text: item.name, value: item.id };
						});
					}
				},
				fail(e) {
					console.log('fail--', e);
				}
			});
		},
		batchText(batch_number) {
			return this.batchOptions.find((item) => item.value === batch_number).text;
		},
		searchPkgChange() {
			this.valiFormData.search_pkg = !this.valiFormData.search_pkg;
			this.valiFormData.typing = this.valiFormData.search_pkg;
		},
		searchOrderChoiceChange() {
			this.valiFormData.search_order = !this.valiFormData.search_order;
			this.valiFormData.search_order_choice = this.valiFormData.search_order ? 3 : '';
		},
		reset() {
			this.loading = false;
			this.focusType = false;

			this.valiFormData = {
				...this.valiFormData,
				orderNum: '',
				space_code: '',
				batch_number: '',
				weight: '',
				search_pkg: true,
				typing: true,
				search_order: true
			};
			nextTick(() => {
				this.focusType = true;
			});
		},

		async scan() {
			// #ifdef APP-PLUS
			let status = await this.checkPermission();
			if (status !== 1) {
				return;
			}
			// #endif
			uni.scanCode({
				success: (res) => {
					this.result = res.result;
					this.valiFormData.orderNum = res.result;
					// this.onsubmit();
				},
				fail: (err) => {
					// 需要注意的是小程序扫码不需要申请相机权限
				}
			});
		},
		// #ifdef APP-PLUS
		async checkPermission(code) {
			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;
		},
		// #endif
		async warehouseScan() {
			this.st && clearTimeout(this.st);

			if (this.valiFormData.search_order_choice === 1) {
				await this.checkWaybillGoods();
			} else if (this.valiFormData.search_order_choice === 2) {
				await this.scanOutstock();
			} else if (this.valiFormData.search_order_choice === 3) {
				await this.weighScan();
			}
		},
		async checkWaybillGoods() {
			this.loading = true;
			uni.request({
				url: checkWaybillGoodsURL,
				method: 'POST',
				header: {
					batoken: this.token
				},
				data: {
					order_no: this.valiFormData.orderNum
				},
				success: (res) => {
					this.loading = false;
					if (res.data.code === 1 && res.data.data.is_goods_empty) {
						this.$refs.alertDialog.open();
					} else {
						this.instockScan(0);
					}
				}
			});
		},
		instockScan(is_save_goods) {
			uni.request({
				url: instockScanURL,
				method: 'POST',
				header: {
					batoken: this.token
				},
				data: {
					order_no: this.valiFormData.orderNum,
					weight: this.valiFormData.weight,
					space_code: this.valiFormData.space_code,
					is_save_goods: is_save_goods
				},
				success: (res) => {
					this.loading = false;
					if (res.data.code == 1) {
						this.messageType = 'success';
						this.messageText = res.data.msg;
						this.$refs.message.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: this.valiFormData.orderNum,
							createTime: new Date(),
							type: '入库',
							status: true
						};
						this.instockHistory.unshift(historyItem);
						uni.setStorageSync('instockHistory', this.instockHistory);
						this.getHistory();
					} else {
						this.messageType = 'error';
						this.messageText = res.data.msg;
						this.$refs.message.open();
						const historyItem = {
							orderNum: this.valiFormData.orderNum,
							createTime: new Date(),
							type: '入库',
							status: false
						};
						this.instockHistory.unshift(historyItem);
						uni.setStorageSync('instockHistory', this.instockHistory);
						this.getHistory();
					}
					this.st = setTimeout(() => {
						this.reset();
						this.st && clearTimeout(this.st);
					}, 1000);
				}
			});
		},
		scanOutstock() {
			console.log(this.valiFormData.orderNum, this.valiFormData.batch_number);
			if (this.valiFormData.orderNum.length === 0 && this.valiFormData.batch_number.length === 0) {
				this.messageType = 'error';
				this.messageText = '单号或批次号至少填一个';
				this.$refs.message.open();
				return;
			}
			this.loading = true;
			uni.request({
				url: outStockScanURL,
				method: 'POST',
				header: {
					batoken: this.token
				},
				data: {
					order_no: this.valiFormData.orderNum,
					batch_number: this.valiFormData.batch_number
				},
				success: (res) => {
					this.loading = false;
					if (res.data.code == 1) {
						this.messageType = 'success';
						this.messageText = res.data.msg;
						this.$refs.message.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: this.valiFormData.orderNum,
							batch_text: this.batchText(this.valiFormData.batch_number),
							createTime: new Date(),
							type: '出库',
							status: true
						};
						this.instockHistory.unshift(historyItem);
						this.instockHistory.length > 10 && (this.instockHistory.length = 10);
						uni.setStorageSync('instockHistory', this.instockHistory);
						this.getHistory();
					} else {
						this.messageType = 'error';
						this.messageText = res.data.msg;
						this.$refs.message.open();
						const historyItem = {
							orderNum: this.valiFormData.orderNum,
							batch_text: this.batchText(this.valiFormData.batch_number),
							createTime: new Date(),
							type: '出库',
							status: false
						};
						this.instockHistory.unshift(historyItem);
						this.instockHistory.length > 10 && (this.instockHistory.length = 10);
						uni.setStorageSync('instockHistory', this.instockHistory);
						this.getHistory();
					}
					this.st = setTimeout(() => {
						this.reset();
						this.st && clearTimeout(this.st);
					}, 1000);
				}
			});
		},
		weighScan() {
			this.loading = true;
			uni.request({
				url: weighScanURL,
				method: 'POST',
				header: {
					batoken: this.token
				},
				data: {
					order_no: this.valiFormData.orderNum,
					weight: this.valiFormData.weight
				},
				success: (res) => {
					this.loading = false;
					if (res.data.code == 1) {
						this.messageType = 'success';
						this.messageText = res.data.msg;
						this.$refs.message.open();
						const historyItem = {
							orderNum: this.valiFormData.orderNum,
							createTime: new Date(),
							type: '称重',
							status: true
						};
						this.instockHistory.unshift(historyItem);
						this.instockHistory.length > 10 && (this.instockHistory.length = 10);
						uni.setStorageSync('instockHistory', this.instockHistory);
						this.getHistory();
					} else {
						this.messageType = 'error';
						this.messageText = res.data.msg;
						this.$refs.message.open();
						const historyItem = {
							orderNum: this.valiFormData.orderNum,
							createTime: new Date(),
							type: '称重',
							status: false
						};
						this.instockHistory.unshift(historyItem);
						this.instockHistory.length > 10 && (this.instockHistory.length = 10);
						uni.setStorageSync('instockHistory', this.instockHistory);
						this.getHistory();
					}
					this.st = setTimeout(() => {
						this.reset();
						this.st && clearTimeout(this.st);
					}, 1000);
				}
			});
		},
		isNotGoods() {
			this.instockScan(0);
		},
		dialogConfirm() {
			console.log('点击确认');
			this.instockScan(1);
		},
		dialogClose() {
			this.instockScan(0);
		},
		onsubmit() {
			this.$refs.valiForm
				.validate()
				.then((res) => {
					this.warehouseScan();
				})
				.catch((err) => {
					console.log('err', err);
				});
		},
		getHistory() {
			// this.instockHistory = uni.getStorageSync('history')
		}
	}
};
</script>
<style lang="scss">
.example {
	padding: 15px;
	background-color: #fff;
}

.checkbox-cum {
	margin-bottom: 20rpx;
	font-size: 14rpx;
}

.sub-choice {
	margin-bottom: 20rpx;
	margin-left: 20rpx;
	font-size: 14rpx;
}

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

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

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

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

	.code {
		font-weight: 600;
	}

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

		.status {
			padding-left: 20rpx;
		}

		.fail {
			font-weight: 600;
			color: #f00;
		}
	}
}
</style>
